diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 66be15b287..e712bd08bd 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -16,6 +16,9 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: false +permissions: + contents: write + jobs: images: name: Deployment @@ -25,7 +28,7 @@ jobs: - uses: actions/checkout@v6 - uses: actions/setup-python@v6 with: - python-version: '3.10' + python-version: '3.12' - uses: abatilo/actions-poetry@v4 with: @@ -37,6 +40,11 @@ jobs: - name: Generate Webpages and Images run: poetry run python scripts/automate.py + # Don't rebuild the website when changes are pushed to gh-pages branch + # since that branch contains the built HTML pages + - name: Add .nojekyll + run: touch docs/.nojekyll + - name: Build Webpages with Jekyll uses: actions/jekyll-build-pages@v1 with: @@ -44,23 +52,10 @@ jobs: destination: docs/_site token: ${{ secrets.GITHUB_TOKEN }} - # Only build webpage if not on main branch - if: ${{ github.ref != 'refs/heads/main' }} - - - name: Commit Changes - uses: EndBug/add-and-commit@v9 + # Push the changes to the gh-pages branch + - name: Publish Site + uses: JamesIves/github-pages-deploy-action@v4 with: - message: | - Generated Sample Programs website automatically - - - on-behalf-of: @TheRenegadeCoder - author_name: GitHub Actions - author_email: action@github.com - - env: - # This is necessary in order to push a commit to the repo - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Leave this line unchanged - - # Only commit if on main branch + folder: docs/_site + token: ${{ secrets.GITHUB_TOKEN }} if: ${{ github.ref == 'refs/heads/main' }} diff --git a/.gitignore b/.gitignore index fbd69abb0a..bf55be2707 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ /venv /docs/_site +/docs/languages +/docs/projects /docs/Gemfile.lock +/docs/index.md generated/ -/requirements-dev.txt diff --git a/docs/index.md b/docs/index.md deleted file mode 100644 index 0e43fe1021..0000000000 --- a/docs/index.md +++ /dev/null @@ -1,12 +0,0 @@ ---- -date: 2018-03-15 -last-modified: 2026-05-23 -layout: default -title: Sample Programs in Every Language -title1: Sample Programs -title2: in Every Language ---- - -Welcome to Sample Programs in Every Language, a collection of code snippets in as many languages as possible. Thanks for taking an interest in our collection which currently contains 1838 articles written by 302 authors. - -If you'd like to contribute to this growing collection, check out our [contributing document](https://github.com/TheRenegadeCoder/sample-programs/blob/master/.github/CONTRIBUTING.md) for more information. In addition, you can explore our documentation which is organized by [project](/projects) and by [language](/languages). If you don't find what you're look for, check out our list of related [open-source projects](/related). Finally, if code isn't your thing but you'd still like to help, there are plenty of other ways to [support the project](https://therenegadecoder.com/updates/5-ways-you-can-support-the-renegade-coder/). \ No newline at end of file diff --git a/docs/languages/ada/index.md b/docs/languages/ada/index.md deleted file mode 100644 index db4ef80971..0000000000 --- a/docs/languages/ada/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -date: 2018-04-24 -featured-image: programming-languages.jpg -last-modified: 2026-05-12 -layout: default -tags: -- ada -title: The Ada Programming Language -title1: The Ada Programming -title2: Language ---- - - - -Welcome to the Ada page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 25 articles: - -- [Baklava in Ada](/projects/baklava/ada) -- [Base64 Encode Decode in Ada](/projects/base64-encode-decode/ada) -- [Binary Search in Ada](/projects/binary-search/ada) -- [Bubble Sort in Ada](/projects/bubble-sort/ada) -- [Capitalize in Ada](/projects/capitalize/ada) -- [Convex Hull in Ada](/projects/convex-hull/ada) -- [Depth First Search in Ada](/projects/depth-first-search/ada) -- [Dijkstra in Ada](/projects/dijkstra/ada) -- [Duplicate Character Counter in Ada](/projects/duplicate-character-counter/ada) -- [Even Odd in Ada](/projects/even-odd/ada) -- [Factorial in Ada](/projects/factorial/ada) -- [Fibonacci in Ada](/projects/fibonacci/ada) -- [File Input Output in Ada](/projects/file-input-output/ada) -- [Fizz Buzz in Ada](/projects/fizz-buzz/ada) -- [Fraction Math in Ada](/projects/fraction-math/ada) -- [Hello World in Ada](/projects/hello-world/ada) -- [Insertion Sort in Ada](/projects/insertion-sort/ada) -- [Job Sequencing in Ada](/projects/job-sequencing/ada) -- [Josephus Problem in Ada](/projects/josephus-problem/ada) -- [Linear Search in Ada](/projects/linear-search/ada) -- [Longest Common Subsequence in Ada](/projects/longest-common-subsequence/ada) -- [Longest Palindromic Substring in Ada](/projects/longest-palindromic-substring/ada) -- [Longest Word in Ada](/projects/longest-word/ada) -- [Maximum Array Rotation in Ada](/projects/maximum-array-rotation/ada) -- [Maximum Subarray in Ada](/projects/maximum-subarray/ada) \ No newline at end of file diff --git a/docs/languages/agda/index.md b/docs/languages/agda/index.md deleted file mode 100644 index 7b26025019..0000000000 --- a/docs/languages/agda/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-11-10 -featured-image: programming-languages.jpg -last-modified: 2025-01-20 -layout: default -tags: -- agda -title: The Agda Programming Language -title1: The Agda Programming -title2: Language ---- - - - -Welcome to the Agda page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Agda](/projects/baklava/agda) -- [Hello World in Agda](/projects/hello-world/agda) \ No newline at end of file diff --git a/docs/languages/algol60/index.md b/docs/languages/algol60/index.md deleted file mode 100644 index f2bd05a835..0000000000 --- a/docs/languages/algol60/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -date: 2026-03-12 -featured-image: programming-languages.jpg -last-modified: 2026-04-24 -layout: default -tags: -- algol60 -title: The ALGOL 60 Programming Language -title1: The ALGOL 60 -title2: Programming Language ---- - - - -Welcome to the ALGOL 60 page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 37 articles: - -- [Baklava in ALGOL 60](/projects/baklava/algol60) -- [Base64 Encode Decode in ALGOL 60](/projects/base64-encode-decode/algol60) -- [Binary Search in ALGOL 60](/projects/binary-search/algol60) -- [Bubble Sort in ALGOL 60](/projects/bubble-sort/algol60) -- [Capitalize in ALGOL 60](/projects/capitalize/algol60) -- [Convex Hull in ALGOL 60](/projects/convex-hull/algol60) -- [Depth First Search in ALGOL 60](/projects/depth-first-search/algol60) -- [Dijkstra in ALGOL 60](/projects/dijkstra/algol60) -- [Duplicate Character Counter in ALGOL 60](/projects/duplicate-character-counter/algol60) -- [Even Odd in ALGOL 60](/projects/even-odd/algol60) -- [Factorial in ALGOL 60](/projects/factorial/algol60) -- [Fibonacci in ALGOL 60](/projects/fibonacci/algol60) -- [Fizz Buzz in ALGOL 60](/projects/fizz-buzz/algol60) -- [Fraction Math in ALGOL 60](/projects/fraction-math/algol60) -- [Hello World in ALGOL 60](/projects/hello-world/algol60) -- [Insertion Sort in ALGOL 60](/projects/insertion-sort/algol60) -- [Job Sequencing in ALGOL 60](/projects/job-sequencing/algol60) -- [Josephus Problem in ALGOL 60](/projects/josephus-problem/algol60) -- [Linear Search in ALGOL 60](/projects/linear-search/algol60) -- [Longest Common Subsequence in ALGOL 60](/projects/longest-common-subsequence/algol60) -- [Longest Palindromic Substring in ALGOL 60](/projects/longest-palindromic-substring/algol60) -- [Longest Word in ALGOL 60](/projects/longest-word/algol60) -- [Maximum Array Rotation in ALGOL 60](/projects/maximum-array-rotation/algol60) -- [Maximum Subarray in ALGOL 60](/projects/maximum-subarray/algol60) -- [Merge Sort in ALGOL 60](/projects/merge-sort/algol60) -- [Minimum Spanning Tree in ALGOL 60](/projects/minimum-spanning-tree/algol60) -- [Palindromic Number in ALGOL 60](/projects/palindromic-number/algol60) -- [Prime Number in ALGOL 60](/projects/prime-number/algol60) -- [Quick Sort in ALGOL 60](/projects/quick-sort/algol60) -- [Quine in ALGOL 60](/projects/quine/algol60) -- [Remove All Whitespace in ALGOL 60](/projects/remove-all-whitespace/algol60) -- [Reverse String in ALGOL 60](/projects/reverse-string/algol60) -- [Roman Numeral in ALGOL 60](/projects/roman-numeral/algol60) -- [Rot13 in ALGOL 60](/projects/rot13/algol60) -- [Selection Sort in ALGOL 60](/projects/selection-sort/algol60) -- [Transpose Matrix in ALGOL 60](/projects/transpose-matrix/algol60) -- [Zeckendorf in ALGOL 60](/projects/zeckendorf/algol60) \ No newline at end of file diff --git a/docs/languages/algol68/index.md b/docs/languages/algol68/index.md deleted file mode 100644 index 123a8b7f48..0000000000 --- a/docs/languages/algol68/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-05-06 -featured-image: programming-languages.jpg -last-modified: 2026-01-20 -layout: default -tags: -- algol68 -title: The ALGOL 68 Programming Language -title1: The ALGOL 68 -title2: Programming Language ---- - - - -Welcome to the ALGOL 68 page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski - -## Description - -ALGOL 68, also known as Algorithmic Language 68, is a successor to the ALGOL 60 -language. As the name suggests, ALGOL 68 first appeared in 1968 as an imperative -programming language. - -That said, ALGOL 68 has a much wider scope than ALGOL 60. For instance, ALGOL 68 -includes user-declared types, expression-based syntax, concurrency, and even slicing. - -Of course, I think the most interesting language feature is the overwhelming list of -reserved words which includes 60 different symbols. Most of these symbols I couldn't -even guess their purpose. For example, what do you think `esac` does? How about -`ouse`? James Jones offers a great explanation: - -![Oh about some of these keywords... Algol 68 has a convention of ending constructs with the reverse of the keyword that begins them. So if statements end with fi, the loop body that starts with do ends with od, and case is ended with esac.](https://therenegadecoder.com/wp-content/uploads/2020/04/algol-keywords-explanation.png) - -In general though, I find that most of the symbols are pretty typical. Many of which -provide either control flow or iteration. Meanwhile, others provide typing. So, -overall the language seems pretty tame. Feel free to check out the Wikipedia page -for the full syntax and features list. - - -## Articles - -There are 38 articles: - -- [Baklava in ALGOL 68](/projects/baklava/algol68) -- [Base64 Encode Decode in ALGOL 68](/projects/base64-encode-decode/algol68) -- [Binary Search in ALGOL 68](/projects/binary-search/algol68) -- [Bubble Sort in ALGOL 68](/projects/bubble-sort/algol68) -- [Capitalize in ALGOL 68](/projects/capitalize/algol68) -- [Convex Hull in ALGOL 68](/projects/convex-hull/algol68) -- [Depth First Search in ALGOL 68](/projects/depth-first-search/algol68) -- [Dijkstra in ALGOL 68](/projects/dijkstra/algol68) -- [Duplicate Character Counter in ALGOL 68](/projects/duplicate-character-counter/algol68) -- [Even Odd in ALGOL 68](/projects/even-odd/algol68) -- [Factorial in ALGOL 68](/projects/factorial/algol68) -- [Fibonacci in ALGOL 68](/projects/fibonacci/algol68) -- [File Input Output in ALGOL 68](/projects/file-input-output/algol68) -- [Fizz Buzz in ALGOL 68](/projects/fizz-buzz/algol68) -- [Fraction Math in ALGOL 68](/projects/fraction-math/algol68) -- [Hello World in ALGOL 68](/projects/hello-world/algol68) -- [Insertion Sort in ALGOL 68](/projects/insertion-sort/algol68) -- [Job Sequencing in ALGOL 68](/projects/job-sequencing/algol68) -- [Josephus Problem in ALGOL 68](/projects/josephus-problem/algol68) -- [Linear Search in ALGOL 68](/projects/linear-search/algol68) -- [Longest Common Subsequence in ALGOL 68](/projects/longest-common-subsequence/algol68) -- [Longest Palindromic Substring in ALGOL 68](/projects/longest-palindromic-substring/algol68) -- [Longest Word in ALGOL 68](/projects/longest-word/algol68) -- [Maximum Array Rotation in ALGOL 68](/projects/maximum-array-rotation/algol68) -- [Maximum Subarray in ALGOL 68](/projects/maximum-subarray/algol68) -- [Merge Sort in ALGOL 68](/projects/merge-sort/algol68) -- [Minimum Spanning Tree in ALGOL 68](/projects/minimum-spanning-tree/algol68) -- [Palindromic Number in ALGOL 68](/projects/palindromic-number/algol68) -- [Prime Number in ALGOL 68](/projects/prime-number/algol68) -- [Quick Sort in ALGOL 68](/projects/quick-sort/algol68) -- [Quine in ALGOL 68](/projects/quine/algol68) -- [Remove All Whitespace in ALGOL 68](/projects/remove-all-whitespace/algol68) -- [Reverse String in ALGOL 68](/projects/reverse-string/algol68) -- [Roman Numeral in ALGOL 68](/projects/roman-numeral/algol68) -- [Rot13 in ALGOL 68](/projects/rot13/algol68) -- [Selection Sort in ALGOL 68](/projects/selection-sort/algol68) -- [Transpose Matrix in ALGOL 68](/projects/transpose-matrix/algol68) -- [Zeckendorf in ALGOL 68](/projects/zeckendorf/algol68) \ No newline at end of file diff --git a/docs/languages/arkscript/index.md b/docs/languages/arkscript/index.md deleted file mode 100644 index a10cae355e..0000000000 --- a/docs/languages/arkscript/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Alexandre Plateau -date: 2020-10-03 -featured-image: programming-languages.jpg -last-modified: 2025-01-20 -layout: default -tags: -- arkscript -title: The ArkScript Programming Language -title1: The ArkScript -title2: Programming Language ---- - - - -Welcome to the ArkScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Alexandre Plateau - -## Description - -ArkScript is -- small: the core fit under 8000 lines of code ; also small in terms of keywords (only 9) -- a scripting language: very easy to embed it in your projects. Registering your own functions in the language is made easy -- portable: a unique bytecode which can be run everywhere the virtual machine is -- a functional language: every parameter is passed by value, everything is immutable unless specified -- powerful: provides closures and explicit capture -- promoting functionalities before performances: expressiveness often brings more productivity, though performances aren't left behind -- a Lisp inspired language, with fewer parentheses: `[...]` is expanded to `(list ...)` and `{...}` to `(begin ...)` -- extensible: supports C++ module to use it in the language, adding functionalities - -Also, it has: -- macros: if/else, values, and functions -- tail call optimization -- a REPL with autocompletion and coloration - -Example: - -```arkscript -(let fibo (fun (n) - (if (< n 2) - n - (+ (fibo (- n 1)) (fibo (- n 2)))))) - -(print (fibo 28)) # display 317811 -``` - -On the first line: -- we define a variable named `fibo`, using the `let` keyword -- we define its value as a function with `fun`, taking a single argument, `n` - -On the second line, we check if n is less than 2 (all functions and keywords are always after an opened paren `(`). - -If the condition is true, on line 3 we return the value of `n`. - -Otherwise, on line 4, we return the addition of `(fibo (- n 1))` and `(fibo (- n 2))`. - -Then on line 6 we call `print` with the function call `(fibo 28)` as its argument. - - - -## Articles - -There are 3 articles: - -- [Baklava in ArkScript](/projects/baklava/arkscript) -- [Fizz Buzz in ArkScript](/projects/fizz-buzz/arkscript) -- [Hello World in ArkScript](/projects/hello-world/arkscript) \ No newline at end of file diff --git a/docs/languages/awk/index.md b/docs/languages/awk/index.md deleted file mode 100644 index 57ecf2684f..0000000000 --- a/docs/languages/awk/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2025-04-06 -featured-image: programming-languages.jpg -last-modified: 2026-01-31 -layout: default -tags: -- awk -title: The AWK Programming Language -title1: The AWK Programming -title2: Language ---- - - - -Welcome to the AWK page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in AWK](/projects/baklava/awk) -- [Base64 Encode Decode in AWK](/projects/base64-encode-decode/awk) -- [Binary Search in AWK](/projects/binary-search/awk) -- [Bubble Sort in AWK](/projects/bubble-sort/awk) -- [Capitalize in AWK](/projects/capitalize/awk) -- [Convex Hull in AWK](/projects/convex-hull/awk) -- [Depth First Search in AWK](/projects/depth-first-search/awk) -- [Dijkstra in AWK](/projects/dijkstra/awk) -- [Duplicate Character Counter in AWK](/projects/duplicate-character-counter/awk) -- [Even Odd in AWK](/projects/even-odd/awk) -- [Factorial in AWK](/projects/factorial/awk) -- [Fibonacci in AWK](/projects/fibonacci/awk) -- [File Input Output in AWK](/projects/file-input-output/awk) -- [Fizz Buzz in AWK](/projects/fizz-buzz/awk) -- [Fraction Math in AWK](/projects/fraction-math/awk) -- [Hello World in AWK](/projects/hello-world/awk) -- [Insertion Sort in AWK](/projects/insertion-sort/awk) -- [Job Sequencing in AWK](/projects/job-sequencing/awk) -- [Josephus Problem in AWK](/projects/josephus-problem/awk) -- [Linear Search in AWK](/projects/linear-search/awk) -- [Longest Common Subsequence in AWK](/projects/longest-common-subsequence/awk) -- [Longest Palindromic Substring in AWK](/projects/longest-palindromic-substring/awk) -- [Longest Word in AWK](/projects/longest-word/awk) -- [Maximum Array Rotation in AWK](/projects/maximum-array-rotation/awk) -- [Maximum Subarray in AWK](/projects/maximum-subarray/awk) -- [Merge Sort in AWK](/projects/merge-sort/awk) -- [Minimum Spanning Tree in AWK](/projects/minimum-spanning-tree/awk) -- [Palindromic Number in AWK](/projects/palindromic-number/awk) -- [Prime Number in AWK](/projects/prime-number/awk) -- [Quick Sort in AWK](/projects/quick-sort/awk) -- [Quine in AWK](/projects/quine/awk) -- [Remove All Whitespace in AWK](/projects/remove-all-whitespace/awk) -- [Reverse String in AWK](/projects/reverse-string/awk) -- [Roman Numeral in AWK](/projects/roman-numeral/awk) -- [Rot13 in AWK](/projects/rot13/awk) -- [Selection Sort in AWK](/projects/selection-sort/awk) -- [Transpose Matrix in AWK](/projects/transpose-matrix/awk) -- [Zeckendorf in AWK](/projects/zeckendorf/awk) \ No newline at end of file diff --git a/docs/languages/baik/index.md b/docs/languages/baik/index.md deleted file mode 100644 index 324faaedad..0000000000 --- a/docs/languages/baik/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-12-09 -featured-image: programming-languages.jpg -last-modified: 2025-01-20 -layout: default -tags: -- baik -title: The BAIK Programming Language -title1: The BAIK Programming -title2: Language ---- - - - -Welcome to the BAIK page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in BAIK](/projects/baklava/baik) -- [Hello World in BAIK](/projects/hello-world/baik) \ No newline at end of file diff --git a/docs/languages/ballerina/index.md b/docs/languages/ballerina/index.md deleted file mode 100644 index c0a3652920..0000000000 --- a/docs/languages/ballerina/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-06-15 -featured-image: programming-languages.jpg -last-modified: 2025-01-20 -layout: default -tags: -- ballerina -title: The Ballerina Programming Language -title1: The Ballerina -title2: Programming Language ---- - - - -Welcome to the Ballerina page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Ballerina](/projects/baklava/ballerina) -- [Fizz Buzz in Ballerina](/projects/fizz-buzz/ballerina) -- [Hello World in Ballerina](/projects/hello-world/ballerina) \ No newline at end of file diff --git a/docs/languages/bash/index.md b/docs/languages/bash/index.md deleted file mode 100644 index 23bde9e11d..0000000000 --- a/docs/languages/bash/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-05-09 -featured-image: programming-languages.jpg -last-modified: 2025-04-06 -layout: default -tags: -- bash -title: The Bash Programming Language -title1: The Bash Programming -title2: Language ---- - - - -Welcome to the Bash page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -[Bash][1] is a command language first released back in 1989. Despite its age, Bash is -still heavily maintained with changes tracked in git. - -In terms of features, Bash supports variables, piping, globbing, control flow, -and even iteration. Of those features, perhaps the coolest is globbing, also -known as wildcard matching. Globbing can be used to retrieves sets of files that -match a wildcard expression. - -Beyond that, Bash is ubiquitous in the Linux/Unix/Mac communities. After all, -it's the standard shell on most systems. In fact, it even has support on -Windows 10. That means shell scripts are fairly portable. However, users will -have to pay attention to code that doesn't conform the Bourne shell standards. - -You'd be hard pressed to find a popular system that doesn't support Bash today. -Even Jenkins, a continuous integration utility, supports Bash scripting during -builds. - -[1]: https://en.wikipedia.org/wiki/Bash_(Unix_shell) - - -## Articles - -There are 15 articles: - -- [Baklava in Bash](/projects/baklava/bash) -- [Base64 Encode Decode in Bash](/projects/base64-encode-decode/bash) -- [Bubble Sort in Bash](/projects/bubble-sort/bash) -- [Capitalize in Bash](/projects/capitalize/bash) -- [Even Odd in Bash](/projects/even-odd/bash) -- [Factorial in Bash](/projects/factorial/bash) -- [Fibonacci in Bash](/projects/fibonacci/bash) -- [File Input Output in Bash](/projects/file-input-output/bash) -- [Fizz Buzz in Bash](/projects/fizz-buzz/bash) -- [Hello World in Bash](/projects/hello-world/bash) -- [Prime Number in Bash](/projects/prime-number/bash) -- [Quick Sort in Bash](/projects/quick-sort/bash) -- [Quine in Bash](/projects/quine/bash) -- [Reverse String in Bash](/projects/reverse-string/bash) -- [Selection Sort in Bash](/projects/selection-sort/bash) \ No newline at end of file diff --git a/docs/languages/batch/index.md b/docs/languages/batch/index.md deleted file mode 100644 index d20947fb27..0000000000 --- a/docs/languages/batch/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2020-04-23 -featured-image: programming-languages.jpg -last-modified: 2025-01-20 -layout: default -tags: -- batch -title: The Batch Programming Language -title1: The Batch Programming -title2: Language ---- - - - -Welcome to the Batch page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Batch](/projects/baklava/batch) -- [Fizz Buzz in Batch](/projects/fizz-buzz/batch) -- [Hello World in Batch](/projects/hello-world/batch) \ No newline at end of file diff --git a/docs/languages/beef/index.md b/docs/languages/beef/index.md deleted file mode 100644 index a38df64320..0000000000 --- a/docs/languages/beef/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2024-01-11 -featured-image: programming-languages.jpg -last-modified: 2026-01-31 -layout: default -tags: -- beef -title: The Beef Programming Language -title1: The Beef Programming -title2: Language ---- - - - -Welcome to the Beef page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in Beef](/projects/baklava/beef) -- [Base64 Encode Decode in Beef](/projects/base64-encode-decode/beef) -- [Binary Search in Beef](/projects/binary-search/beef) -- [Bubble Sort in Beef](/projects/bubble-sort/beef) -- [Capitalize in Beef](/projects/capitalize/beef) -- [Convex Hull in Beef](/projects/convex-hull/beef) -- [Depth First Search in Beef](/projects/depth-first-search/beef) -- [Dijkstra in Beef](/projects/dijkstra/beef) -- [Duplicate Character Counter in Beef](/projects/duplicate-character-counter/beef) -- [Even Odd in Beef](/projects/even-odd/beef) -- [Factorial in Beef](/projects/factorial/beef) -- [Fibonacci in Beef](/projects/fibonacci/beef) -- [File Input Output in Beef](/projects/file-input-output/beef) -- [Fizz Buzz in Beef](/projects/fizz-buzz/beef) -- [Fraction Math in Beef](/projects/fraction-math/beef) -- [Hello World in Beef](/projects/hello-world/beef) -- [Insertion Sort in Beef](/projects/insertion-sort/beef) -- [Job Sequencing in Beef](/projects/job-sequencing/beef) -- [Josephus Problem in Beef](/projects/josephus-problem/beef) -- [Linear Search in Beef](/projects/linear-search/beef) -- [Longest Common Subsequence in Beef](/projects/longest-common-subsequence/beef) -- [Longest Palindromic Substring in Beef](/projects/longest-palindromic-substring/beef) -- [Longest Word in Beef](/projects/longest-word/beef) -- [Maximum Array Rotation in Beef](/projects/maximum-array-rotation/beef) -- [Maximum Subarray in Beef](/projects/maximum-subarray/beef) -- [Merge Sort in Beef](/projects/merge-sort/beef) -- [Minimum Spanning Tree in Beef](/projects/minimum-spanning-tree/beef) -- [Palindromic Number in Beef](/projects/palindromic-number/beef) -- [Prime Number in Beef](/projects/prime-number/beef) -- [Quick Sort in Beef](/projects/quick-sort/beef) -- [Quine in Beef](/projects/quine/beef) -- [Remove All Whitespace in Beef](/projects/remove-all-whitespace/beef) -- [Reverse String in Beef](/projects/reverse-string/beef) -- [Roman Numeral in Beef](/projects/roman-numeral/beef) -- [Rot13 in Beef](/projects/rot13/beef) -- [Selection Sort in Beef](/projects/selection-sort/beef) -- [Transpose Matrix in Beef](/projects/transpose-matrix/beef) -- [Zeckendorf in Beef](/projects/zeckendorf/beef) \ No newline at end of file diff --git a/docs/languages/befunge/index.md b/docs/languages/befunge/index.md deleted file mode 100644 index 15fbe41cd5..0000000000 --- a/docs/languages/befunge/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -- Stuart Irwin -date: 2018-10-22 -featured-image: programming-languages.jpg -last-modified: 2025-04-12 -layout: default -tags: -- befunge -title: The Befunge Programming Language -title1: The Befunge -title2: Programming Language ---- - - - -Welcome to the Befunge page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman -- Stuart Irwin - -## Description - -[Befunge][1] is a programming language with some very unusual standards, -as a two-dimensional, self-modifying, stack-based programming language. -Apparently, it was designed in 1993 by Chris Pressey, merely to be as -difficult to compile as possible. - -All operations in Befunge are limited to a single character, and the -source text can be traversed in any direction through the file. The -"Instruction Pointer" starts in the upper left corner and proceeds -to the right, running every character it crosses. When it reaches -an arrow, `< > ^ v`, that pointer will turn and travel in the new -indicated direction. - -Instead of variables, all operations act on one global stack of -integers, similar to Forth. 0-9 will just push their value, -`+ - * / %` pop the top two values and push their normal result, -`.` prints out the top number, and `,` prints the corresponding -character instead. - -[1]: https://en.wikipedia.org/wiki/Befunge - - -## Articles - -There are 4 articles: - -- [Baklava in Befunge](/projects/baklava/befunge) -- [Fizz Buzz in Befunge](/projects/fizz-buzz/befunge) -- [Hello World in Befunge](/projects/hello-world/befunge) -- [Quine in Befunge](/projects/quine/befunge) \ No newline at end of file diff --git a/docs/languages/boo/index.md b/docs/languages/boo/index.md deleted file mode 100644 index 4e37761e97..0000000000 --- a/docs/languages/boo/index.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -date: 2020-10-02 -featured-image: programming-languages.jpg -last-modified: 2025-04-17 -layout: default -tags: -- boo -title: The Boo Programming Language -title1: The Boo Programming -title2: Language ---- - - - -Welcome to the Boo page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 4 articles: - -- [Baklava in Boo](/projects/baklava/boo) -- [Fibonacci in Boo](/projects/fibonacci/boo) -- [Fizz Buzz in Boo](/projects/fizz-buzz/boo) -- [Hello World in Boo](/projects/hello-world/boo) \ No newline at end of file diff --git a/docs/languages/bracmat/index.md b/docs/languages/bracmat/index.md deleted file mode 100644 index e6dc67974b..0000000000 --- a/docs/languages/bracmat/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2020-12-07 -featured-image: programming-languages.jpg -last-modified: 2025-01-20 -layout: default -tags: -- bracmat -title: The Bracmat Programming Language -title1: The Bracmat -title2: Programming Language ---- - - - -Welcome to the Bracmat page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Bracmat](/projects/baklava/bracmat) -- [Hello World in Bracmat](/projects/hello-world/bracmat) \ No newline at end of file diff --git a/docs/languages/brainfuck/index.md b/docs/languages/brainfuck/index.md deleted file mode 100644 index 665b137ecf..0000000000 --- a/docs/languages/brainfuck/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-08-23 -featured-image: programming-languages.jpg -last-modified: 2023-12-22 -layout: default -tags: -- brainfuck -title: The Brainfuck Programming Language -title1: The Brainfuck -title2: Programming Language ---- - - - -Welcome to the Brainfuck page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -[Brainfuck][1] is an esoteric programming language created in 1992, and notable for -its extreme minimalism. As people have implemented more and more ridiculous -programs with the language, it has become relatively well-known over the years. -Nowadays some see it as the ultimate coding challenge to create something -useful in Brainfuck. - -At the core of the language is a more-than-compact instruction set, comprising -of a whopping eight instructions. Brainfuck uses a machine model consisting of -an infinite list of one-byte cells, an instruction pointer, and a cell pointer. -The instructions can be used to interact with this environment: `<` and `>` -move the cell pointer, `+` and `-` increment or decrement the value of the cell -at the current pointer, and `[` and `]` denote a loop. - -A loop only starts when the value of the current cell is non-zero, otherwise -execution jumps to the end of the loop. Likewise, a loop ends when the value is -zero, otherwise the program jumps to the beginning of the loop. The remaining -two instructions, `,` and `.` read one character from the input into the current -cell and write one character from the current cell to the output, respectively. -That's it! - -[1]: https://en.wikipedia.org/wiki/Brainfuck - - -## Articles - -There are 8 articles: - -- [Baklava in Brainfuck](/projects/baklava/brainfuck) -- [Capitalize in Brainfuck](/projects/capitalize/brainfuck) -- [Fizz Buzz in Brainfuck](/projects/fizz-buzz/brainfuck) -- [Hello World in Brainfuck](/projects/hello-world/brainfuck) -- [Longest Word in Brainfuck](/projects/longest-word/brainfuck) -- [Remove All Whitespace in Brainfuck](/projects/remove-all-whitespace/brainfuck) -- [Reverse String in Brainfuck](/projects/reverse-string/brainfuck) -- [Rot13 in Brainfuck](/projects/rot13/brainfuck) \ No newline at end of file diff --git a/docs/languages/c-plus-plus/index.md b/docs/languages/c-plus-plus/index.md deleted file mode 100644 index 7e5079bc9e..0000000000 --- a/docs/languages/c-plus-plus/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ron Zuckerman -date: 2018-03-21 -featured-image: programming-languages.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -title: The C++ Programming Language -title1: The C++ Programming -title2: Language ---- - - - -Welcome to the C++ page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Ron Zuckerman - -## Description - -According to [Wikipedia][1], C++ is a general-purpose programming language developed back in 1979 by [Bjarne Stroustrup][2]. Back then, C++ was called "C with Classes." As you can probably imagine, the name was changed to C++ which is a play on the increment operator. - -C++ is probably the most powerful language in existence as it supports both imperative and object-oriented programming features. In addition, it allows you to get extremely close to hardware, so it's not uncommon to see C++ used in embedded environments and game development. - -However, with great power comes great responsibility. As a result, I personally find C++ to be an extremely rough language to use. Unlike [Python][3], which was designed with the "one-way-only" paradigm, C++ allows you to code up a solution in literally any way you want. This can lead to some truly unreadable and complex code. - -[1]: https://en.wikipedia.org/wiki/C%2B%2B -[2]: https://en.wikipedia.org/wiki/Bjarne_Stroustrup -[3]: https://en.wikipedia.org/wiki/Python_(programming_language) - - -## Articles - -There are 38 articles: - -- [Baklava in C++](/projects/baklava/c-plus-plus) -- [Base64 Encode Decode in C++](/projects/base64-encode-decode/c-plus-plus) -- [Binary Search in C++](/projects/binary-search/c-plus-plus) -- [Bubble Sort in C++](/projects/bubble-sort/c-plus-plus) -- [Capitalize in C++](/projects/capitalize/c-plus-plus) -- [Convex Hull in C++](/projects/convex-hull/c-plus-plus) -- [Depth First Search in C++](/projects/depth-first-search/c-plus-plus) -- [Dijkstra in C++](/projects/dijkstra/c-plus-plus) -- [Duplicate Character Counter in C++](/projects/duplicate-character-counter/c-plus-plus) -- [Even Odd in C++](/projects/even-odd/c-plus-plus) -- [Factorial in C++](/projects/factorial/c-plus-plus) -- [Fibonacci in C++](/projects/fibonacci/c-plus-plus) -- [File Input Output in C++](/projects/file-input-output/c-plus-plus) -- [Fizz Buzz in C++](/projects/fizz-buzz/c-plus-plus) -- [Fraction Math in C++](/projects/fraction-math/c-plus-plus) -- [Hello World in C++](/projects/hello-world/c-plus-plus) -- [Insertion Sort in C++](/projects/insertion-sort/c-plus-plus) -- [Job Sequencing in C++](/projects/job-sequencing/c-plus-plus) -- [Josephus Problem in C++](/projects/josephus-problem/c-plus-plus) -- [Linear Search in C++](/projects/linear-search/c-plus-plus) -- [Longest Common Subsequence in C++](/projects/longest-common-subsequence/c-plus-plus) -- [Longest Palindromic Substring in C++](/projects/longest-palindromic-substring/c-plus-plus) -- [Longest Word in C++](/projects/longest-word/c-plus-plus) -- [Maximum Array Rotation in C++](/projects/maximum-array-rotation/c-plus-plus) -- [Maximum Subarray in C++](/projects/maximum-subarray/c-plus-plus) -- [Merge Sort in C++](/projects/merge-sort/c-plus-plus) -- [Minimum Spanning Tree in C++](/projects/minimum-spanning-tree/c-plus-plus) -- [Palindromic Number in C++](/projects/palindromic-number/c-plus-plus) -- [Prime Number in C++](/projects/prime-number/c-plus-plus) -- [Quick Sort in C++](/projects/quick-sort/c-plus-plus) -- [Quine in C++](/projects/quine/c-plus-plus) -- [Remove All Whitespace in C++](/projects/remove-all-whitespace/c-plus-plus) -- [Reverse String in C++](/projects/reverse-string/c-plus-plus) -- [Roman Numeral in C++](/projects/roman-numeral/c-plus-plus) -- [Rot13 in C++](/projects/rot13/c-plus-plus) -- [Selection Sort in C++](/projects/selection-sort/c-plus-plus) -- [Transpose Matrix in C++](/projects/transpose-matrix/c-plus-plus) -- [Zeckendorf in C++](/projects/zeckendorf/c-plus-plus) \ No newline at end of file diff --git a/docs/languages/c-sharp/index.md b/docs/languages/c-sharp/index.md deleted file mode 100644 index 4938dce9ce..0000000000 --- a/docs/languages/c-sharp/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-25 -featured-image: programming-languages.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -title: The C# Programming Language -title1: The C# Programming -title2: Language ---- - - - -Welcome to the C# page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -As always, I took to [Wikipedia][1] to learn more about C#. - -Just like our other programming languages so far, C# is a general-purpose -language. However, unlike our other languages, C# was designed for the Microsoft -platform as a part of the [.NET][2] initiative in 2000. We'll see something along the -same lines when we get to languages like Objective-C and Swift. - -Some notable features of C# include the virtual and var keywords as well as -properties and namespaces. Because of these features, C# can seem like a nice -cross between [Java][3] and [C++][4]. In fact, C# is often considered a clone of Java. - -Personally, I like C# much more than Java. I won't go into too much of a -tangent, but C# has this beautiful feature that allows us to declare getters and -setters in a single line. Just take a look: - -```csharp -public string Name { get; set; } -``` - -Now, we have a string which we can get and set directly and safely without -having to implement our own methods. **I love this syntax**. - -Also, I love the fact that C# can be used to develop games in Unity. Beyond -Android apps, I haven't seen many fun commercial uses for Java. - -[1]: https://en.wikipedia.org/wiki/C_Sharp_(programming_language) -[2]: https://en.wikipedia.org/wiki/.NET -[3]: https://en.wikipedia.org/wiki/Java_(programming_language) -[4]: https://en.wikipedia.org/wiki/C%2B%2B - - -## Articles - -There are 38 articles: - -- [Baklava in C#](/projects/baklava/c-sharp) -- [Base64 Encode Decode in C#](/projects/base64-encode-decode/c-sharp) -- [Binary Search in C#](/projects/binary-search/c-sharp) -- [Bubble Sort in C#](/projects/bubble-sort/c-sharp) -- [Capitalize in C#](/projects/capitalize/c-sharp) -- [Convex Hull in C#](/projects/convex-hull/c-sharp) -- [Depth First Search in C#](/projects/depth-first-search/c-sharp) -- [Dijkstra in C#](/projects/dijkstra/c-sharp) -- [Duplicate Character Counter in C#](/projects/duplicate-character-counter/c-sharp) -- [Even Odd in C#](/projects/even-odd/c-sharp) -- [Factorial in C#](/projects/factorial/c-sharp) -- [Fibonacci in C#](/projects/fibonacci/c-sharp) -- [File Input Output in C#](/projects/file-input-output/c-sharp) -- [Fizz Buzz in C#](/projects/fizz-buzz/c-sharp) -- [Fraction Math in C#](/projects/fraction-math/c-sharp) -- [Hello World in C#](/projects/hello-world/c-sharp) -- [Insertion Sort in C#](/projects/insertion-sort/c-sharp) -- [Job Sequencing in C#](/projects/job-sequencing/c-sharp) -- [Josephus Problem in C#](/projects/josephus-problem/c-sharp) -- [Linear Search in C#](/projects/linear-search/c-sharp) -- [Longest Common Subsequence in C#](/projects/longest-common-subsequence/c-sharp) -- [Longest Palindromic Substring in C#](/projects/longest-palindromic-substring/c-sharp) -- [Longest Word in C#](/projects/longest-word/c-sharp) -- [Maximum Array Rotation in C#](/projects/maximum-array-rotation/c-sharp) -- [Maximum Subarray in C#](/projects/maximum-subarray/c-sharp) -- [Merge Sort in C#](/projects/merge-sort/c-sharp) -- [Minimum Spanning Tree in C#](/projects/minimum-spanning-tree/c-sharp) -- [Palindromic Number in C#](/projects/palindromic-number/c-sharp) -- [Prime Number in C#](/projects/prime-number/c-sharp) -- [Quick Sort in C#](/projects/quick-sort/c-sharp) -- [Quine in C#](/projects/quine/c-sharp) -- [Remove All Whitespace in C#](/projects/remove-all-whitespace/c-sharp) -- [Reverse String in C#](/projects/reverse-string/c-sharp) -- [Roman Numeral in C#](/projects/roman-numeral/c-sharp) -- [Rot13 in C#](/projects/rot13/c-sharp) -- [Selection Sort in C#](/projects/selection-sort/c-sharp) -- [Transpose Matrix in C#](/projects/transpose-matrix/c-sharp) -- [Zeckendorf in C#](/projects/zeckendorf/c-sharp) \ No newline at end of file diff --git a/docs/languages/c-star/index.md b/docs/languages/c-star/index.md deleted file mode 100644 index 5d9a50f362..0000000000 --- a/docs/languages/c-star/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Ron Zuckerman -- rzuckerm -date: 2022-04-28 -featured-image: programming-languages.jpg -last-modified: 2025-10-28 -layout: default -tags: -- c-star -title: The C* Programming Language -title1: The C* Programming -title2: Language ---- - - - -Welcome to the C\* page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Ron Zuckerman -- rzuckerm - -## Description - -This is not the C* language described in [Wikipedia][1]. According to its -creator, [Emil Laine][2] in [this GitHub issue][3], it is a new language. -From the [commit history][4], it looks like the language was created in 2017. -However, according to the [issue][3], they are no longer actively maintaining -this language. At the time of this writing, the last commit was done in May -2023. - -According to the [C* documentation][5]: - -> C* (pronounced “C star”) is a hybrid low-level / high-level programming language - focused on runtime performance and developer productivity, in this order of priority. - The language is simple and unopinionated, has a clean C-like syntax, and supports - imperative, generic, data-oriented, functional, and object-oriented programming. - -According to the [C* introduction][6], the C* language is intended to overcome the -short-comings of [C][7] and the complexity of [C++][8]. Unlike [Rust][9], it is intended -to be used in non-safety-critical applications, so it does not have the complex -lifetime and ownership model that Rust does. However, it has some memory safety -features like these: - -- Array bounds checking -- Integer overflow checking -- Null checking - -For further information on this language, see the [C* documentation][5]. - -[1]: https://en.wikipedia.org/wiki/C* -[2]: https://github.com/emlai -[3]: https://github.com/cx-language/cx/issues/77 -[4]: https://github.com/cx-language/cx/commits/main -[5]: https://cx-language.github.io/ -[6]: https://cx-language.github.io/introduction -[7]: https://en.wikipedia.org/wiki/C_(programming_language) -[8]: https://en.wikipedia.org/wiki/C%2B%2B -[9]: https://en.wikipedia.org/wiki/Rust_(programming_language) - - -## Articles - -There are 3 articles: - -- [Baklava in C\*](/projects/baklava/c-star) -- [Fizz Buzz in C\*](/projects/fizz-buzz/c-star) -- [Hello World in C\*](/projects/hello-world/c-star) \ No newline at end of file diff --git a/docs/languages/c/index.md b/docs/languages/c/index.md deleted file mode 100644 index 840114a673..0000000000 --- a/docs/languages/c/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Johnny Fang -- Ron Zuckerman -date: 2018-03-15 -featured-image: programming-languages.jpg -last-modified: 2026-05-15 -layout: default -tags: -- c -title: The C Programming Language -title1: The C Programming -title2: Language ---- - - - -Welcome to the C page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Johnny Fang -- Ron Zuckerman - -## Description - -[C][1] is a general-purpose programming language that was developed as early -as 1969 at Bell Labs by Dennis Richie. Today, the C language has influenced -the design of many languages such as C++, C#, Go, Java, and many, many more. - -Features of C include static typing, lexical variable scope, and recursion. -In addition, function parameters are passed by value, not reference, but -pass-by-reference can be accomplished by explicitly using pointers. Also, -while C has static typing, variables are weakly typed and can be converted -implicitly. - -[1]: https://en.wikipedia.org/wiki/C_(programming_language) - - -## Articles - -There are 38 articles: - -- [Baklava in C](/projects/baklava/c) -- [Base64 Encode Decode in C](/projects/base64-encode-decode/c) -- [Binary Search in C](/projects/binary-search/c) -- [Bubble Sort in C](/projects/bubble-sort/c) -- [Capitalize in C](/projects/capitalize/c) -- [Convex Hull in C](/projects/convex-hull/c) -- [Depth First Search in C](/projects/depth-first-search/c) -- [Dijkstra in C](/projects/dijkstra/c) -- [Duplicate Character Counter in C](/projects/duplicate-character-counter/c) -- [Even Odd in C](/projects/even-odd/c) -- [Factorial in C](/projects/factorial/c) -- [Fibonacci in C](/projects/fibonacci/c) -- [File Input Output in C](/projects/file-input-output/c) -- [Fizz Buzz in C](/projects/fizz-buzz/c) -- [Fraction Math in C](/projects/fraction-math/c) -- [Hello World in C](/projects/hello-world/c) -- [Insertion Sort in C](/projects/insertion-sort/c) -- [Job Sequencing in C](/projects/job-sequencing/c) -- [Josephus Problem in C](/projects/josephus-problem/c) -- [Linear Search in C](/projects/linear-search/c) -- [Longest Common Subsequence in C](/projects/longest-common-subsequence/c) -- [Longest Palindromic Substring in C](/projects/longest-palindromic-substring/c) -- [Longest Word in C](/projects/longest-word/c) -- [Maximum Array Rotation in C](/projects/maximum-array-rotation/c) -- [Maximum Subarray in C](/projects/maximum-subarray/c) -- [Merge Sort in C](/projects/merge-sort/c) -- [Minimum Spanning Tree in C](/projects/minimum-spanning-tree/c) -- [Palindromic Number in C](/projects/palindromic-number/c) -- [Prime Number in C](/projects/prime-number/c) -- [Quick Sort in C](/projects/quick-sort/c) -- [Quine in C](/projects/quine/c) -- [Remove All Whitespace in C](/projects/remove-all-whitespace/c) -- [Reverse String in C](/projects/reverse-string/c) -- [Roman Numeral in C](/projects/roman-numeral/c) -- [Rot13 in C](/projects/rot13/c) -- [Selection Sort in C](/projects/selection-sort/c) -- [Transpose Matrix in C](/projects/transpose-matrix/c) -- [Zeckendorf in C](/projects/zeckendorf/c) \ No newline at end of file diff --git a/docs/languages/c2/index.md b/docs/languages/c2/index.md deleted file mode 100644 index 73c1ed9f22..0000000000 --- a/docs/languages/c2/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2021-05-25 -featured-image: programming-languages.jpg -last-modified: 2025-01-14 -layout: default -tags: -- c2 -title: The C2 Programming Language -title1: The C2 Programming -title2: Language ---- - - - -Welcome to the C2 page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in C2](/projects/baklava/c2) -- [Hello World in C2](/projects/hello-world/c2) \ No newline at end of file diff --git a/docs/languages/carp/index.md b/docs/languages/carp/index.md deleted file mode 100644 index c85f5697ba..0000000000 --- a/docs/languages/carp/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-07-29 -featured-image: programming-languages.jpg -last-modified: 2025-01-15 -layout: default -tags: -- carp -title: The Carp Programming Language -title1: The Carp Programming -title2: Language ---- - - - -Welcome to the Carp page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Carp](/projects/baklava/carp) -- [Hello World in Carp](/projects/hello-world/carp) \ No newline at end of file diff --git a/docs/languages/chaiscript/index.md b/docs/languages/chaiscript/index.md deleted file mode 100644 index b8dd46a406..0000000000 --- a/docs/languages/chaiscript/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2021-05-24 -featured-image: programming-languages.jpg -last-modified: 2025-01-15 -layout: default -tags: -- chaiscript -title: The ChaiScript Programming Language -title1: The ChaiScript -title2: Programming Language ---- - - - -Welcome to the ChaiScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in ChaiScript](/projects/baklava/chaiscript) -- [Hello World in ChaiScript](/projects/hello-world/chaiscript) \ No newline at end of file diff --git a/docs/languages/chapel/index.md b/docs/languages/chapel/index.md deleted file mode 100644 index 2c023f35fe..0000000000 --- a/docs/languages/chapel/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-11-22 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- chapel -title: The Chapel Programming Language -title1: The Chapel -title2: Programming Language ---- - - - -Welcome to the Chapel page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Chapel](/projects/baklava/chapel) -- [Fizz Buzz in Chapel](/projects/fizz-buzz/chapel) -- [Hello World in Chapel](/projects/hello-world/chapel) \ No newline at end of file diff --git a/docs/languages/clojure/index.md b/docs/languages/clojure/index.md deleted file mode 100644 index 9e8a267411..0000000000 --- a/docs/languages/clojure/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -date: 2018-12-22 -featured-image: programming-languages.jpg -last-modified: 2025-01-15 -layout: default -tags: -- clojure -title: The Clojure Programming Language -title1: The Clojure -title2: Programming Language ---- - - - -Welcome to the Clojure page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 6 articles: - -- [Baklava in Clojure](/projects/baklava/clojure) -- [Bubble Sort in Clojure](/projects/bubble-sort/clojure) -- [Capitalize in Clojure](/projects/capitalize/clojure) -- [Fizz Buzz in Clojure](/projects/fizz-buzz/clojure) -- [Hello World in Clojure](/projects/hello-world/clojure) -- [Reverse String in Clojure](/projects/reverse-string/clojure) \ No newline at end of file diff --git a/docs/languages/cobol/index.md b/docs/languages/cobol/index.md deleted file mode 100644 index 15b89ad2d7..0000000000 --- a/docs/languages/cobol/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2021-10-08 -featured-image: programming-languages.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -title: The COBOL Programming Language -title1: The COBOL Programming -title2: Language ---- - - - -Welcome to the COBOL page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in COBOL](/projects/baklava/cobol) -- [Base64 Encode Decode in COBOL](/projects/base64-encode-decode/cobol) -- [Binary Search in COBOL](/projects/binary-search/cobol) -- [Bubble Sort in COBOL](/projects/bubble-sort/cobol) -- [Capitalize in COBOL](/projects/capitalize/cobol) -- [Convex Hull in COBOL](/projects/convex-hull/cobol) -- [Depth First Search in COBOL](/projects/depth-first-search/cobol) -- [Dijkstra in COBOL](/projects/dijkstra/cobol) -- [Duplicate Character Counter in COBOL](/projects/duplicate-character-counter/cobol) -- [Even Odd in COBOL](/projects/even-odd/cobol) -- [Factorial in COBOL](/projects/factorial/cobol) -- [Fibonacci in COBOL](/projects/fibonacci/cobol) -- [File Input Output in COBOL](/projects/file-input-output/cobol) -- [Fizz Buzz in COBOL](/projects/fizz-buzz/cobol) -- [Fraction Math in COBOL](/projects/fraction-math/cobol) -- [Hello World in COBOL](/projects/hello-world/cobol) -- [Insertion Sort in COBOL](/projects/insertion-sort/cobol) -- [Job Sequencing in COBOL](/projects/job-sequencing/cobol) -- [Josephus Problem in COBOL](/projects/josephus-problem/cobol) -- [Linear Search in COBOL](/projects/linear-search/cobol) -- [Longest Common Subsequence in COBOL](/projects/longest-common-subsequence/cobol) -- [Longest Palindromic Substring in COBOL](/projects/longest-palindromic-substring/cobol) -- [Longest Word in COBOL](/projects/longest-word/cobol) -- [Maximum Array Rotation in COBOL](/projects/maximum-array-rotation/cobol) -- [Maximum Subarray in COBOL](/projects/maximum-subarray/cobol) -- [Merge Sort in COBOL](/projects/merge-sort/cobol) -- [Minimum Spanning Tree in COBOL](/projects/minimum-spanning-tree/cobol) -- [Palindromic Number in COBOL](/projects/palindromic-number/cobol) -- [Prime Number in COBOL](/projects/prime-number/cobol) -- [Quick Sort in COBOL](/projects/quick-sort/cobol) -- [Quine in COBOL](/projects/quine/cobol) -- [Remove All Whitespace in COBOL](/projects/remove-all-whitespace/cobol) -- [Reverse String in COBOL](/projects/reverse-string/cobol) -- [Roman Numeral in COBOL](/projects/roman-numeral/cobol) -- [Rot13 in COBOL](/projects/rot13/cobol) -- [Selection Sort in COBOL](/projects/selection-sort/cobol) -- [Transpose Matrix in COBOL](/projects/transpose-matrix/cobol) -- [Zeckendorf in COBOL](/projects/zeckendorf/cobol) \ No newline at end of file diff --git a/docs/languages/coffeescript/index.md b/docs/languages/coffeescript/index.md deleted file mode 100644 index 71b9b8ac8a..0000000000 --- a/docs/languages/coffeescript/index.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -date: 2018-12-30 -featured-image: programming-languages.jpg -last-modified: 2025-11-02 -layout: default -tags: -- coffeescript -title: The CoffeeScript Programming Language -title1: The CoffeeScript -title2: Programming Language ---- - - - -Welcome to the CoffeeScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 10 articles: - -- [Baklava in CoffeeScript](/projects/baklava/coffeescript) -- [Capitalize in CoffeeScript](/projects/capitalize/coffeescript) -- [Even Odd in CoffeeScript](/projects/even-odd/coffeescript) -- [Factorial in CoffeeScript](/projects/factorial/coffeescript) -- [Fizz Buzz in CoffeeScript](/projects/fizz-buzz/coffeescript) -- [Hello World in CoffeeScript](/projects/hello-world/coffeescript) -- [Longest Word in CoffeeScript](/projects/longest-word/coffeescript) -- [Quine in CoffeeScript](/projects/quine/coffeescript) -- [Remove All Whitespace in CoffeeScript](/projects/remove-all-whitespace/coffeescript) -- [Reverse String in CoffeeScript](/projects/reverse-string/coffeescript) \ No newline at end of file diff --git a/docs/languages/commodore-basic/index.md b/docs/languages/commodore-basic/index.md deleted file mode 100644 index 50f676d9d8..0000000000 --- a/docs/languages/commodore-basic/index.md +++ /dev/null @@ -1,289 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-13 -featured-image: programming-languages.jpg -last-modified: 2026-01-31 -layout: default -tags: -- commodore-basic -title: The Commodore BASIC Programming Language -title1: The Commodore BASIC -title2: Programming Language ---- - - - -Welcome to the Commodore BASIC page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- rzuckerm - -## Description - -### Introduction - -According to [Wikipedia][1], Commodore BASIC is a dialect of the [BASIC][2] -programming language developed for Commodore's 8-bit home computers. It is -based on [Microsoft BASIC][3], which was developed by Microsoft founders -Bill Gates and Paul Allen. In 1977, Commodore licensed Microsoft BASIC for -a [one-time fee of $25,000][4]. - -BASIC was the first language I ever learned back in High School. Although I -never owned a Commodore computer, Commodore BASIC is very similar to what I -learned. - -### Line Numbers - -Like other dialects of BASIC at the time, programs were entered using -[line numbers][5]. The line numbers determine the order of statements in the -program. If an existing line number is used, the code at that line number is -overwritten. If a line number with nothing after it is used, the code at that -line number is deleted. Code can be inserted between existing lines by -using a line number that is between two existing line number. For example, - -```basic -10 PRINT "Hello" -20 PRINT "Goodbyte" -15 PRINT "Something else" -20 PRINT "Goodbye" -30 PRINT "All Done" -30 -``` - -This would result in the following code (this can be seen using the [LIST][6] -command, which shows the current program): - -```basic -10 PRINT "Hello" -15 PRINT "Something else" -20 PRINT "Goodbye" -``` - -- Line 10 and 20 are added to the program. -- Line 15 is inserted between lines 10 and 20. -- Line 20 is changed from `PRINT "Goodbyte"` to `PRINT "Goodbye"`. -- Line 30 is added and then deleted. - -Line were typically numbered in increments of 10 so that lines could be easily -inserted. - -### Statements - -Statements are only allowed to be 80 characters long. Multiple statements can -be chained together using `:`. For example, "Hello" and "World" can be -displayed on separate lines like this: - -```basic -10 PRINT "Hello": PRINT "World" -``` - -All keywords are capitalized. - -### Variables - -There are [three types of variables][7]: - -- Real - 32-bit single-precision floating point value ranging from about - +/-2.9E-38 to +/-1.7E+38. This is the default variable type. It has no - suffix -- e.g., `N`. -- Integer - 16-bit value ranging from -32768 to 32767. Integer variables are - denoted with a `%` suffix -- e.g., `A%`. -- String - A sequence of 0 to 255 characters. String variables are denoted - with a `$` suffix -- e.g., `S$`. - -All three types support [arrays][14]. - -All variables are global. There are some system variables: - -- [ST/STATUS][8] - The status of the last file I/O operation -- [TI/TIME][9] - Timer which starts at 0 when the program starts and - increments every 1/60 of a second. -- [TI$/TIME$][10] - The current time in hours, minutes, and seconds as a - string -- e.g., `"134725"` corresponds to 13:47:25 in 24-hour time. - -Although [variable names][11] can be longer than two characters, only the first -two characters matter -- e.g., `ABC` is the same as `AB`. No part of a -variable name can contain a keyword. For example, `AIF3` is not allowed since -it contains the `IF` keyword. - -### Control Flow - -Like other BASICs of the time, Commodore BASIC is a completely unstructured -language. Therefore, it uses (gasp!) [GOTO][12] statements to unconditionally -jump to another part of the program. - -The [IF][13] statement is used to execute a piece of code conditionally. It -can also be used in conjunction with `GOTO` to jump to another part of the program. -For example: - -```basic -50 IF A < 5 THEN B = 7: GOTO 70 -60 B = 8 -70 PRINT "A ="; A; ", B ="; B -``` - -If the value of `A` is less than 5, the value of `B` is set to 7, and the code -jumps to line 70. Otherwise, the value of `B` is set to 8. At line 70, the -value of `A` and `B` are displayed. - -The [FOR][15] statement can be used to set up loops, where a variable is set -up to go over specified range and increment. For example, this displays the -number 1 to 10: - -```basic -100 FOR I = 1 TO 10 -110 PRINT I -120 NEXT I -``` - -The value of `I` runs from 1 to 10. The [NEXT][16] keyword determines the end -of the loop. The [STEP][17] keyword can be used to set the increment for the -loop. For example, this displays even numbers from 10 down to 0: - -```basic -100 FOR I = 10 TO 0 STEP -2 -110 PRINT I -120 NEXT I -``` - -Subroutines are supported via the [GOSUB][18] statement. This pushes the line -number of the next instruction to be executed on to the stack and jumps to -the specified line number. The [RETURN][19] statement is used to return -control back to the caller. It pops the line number off the stack and jumps -to that line number. For example: - -```basic -150 A = 1: B = 7: GOSUB 1000 -160 PRINT "The sum from"; A; "to"; B; "is"; S -170 ... -1000 S = 0 -1010 FOR I = A TO B -1020 S = S + I -1030 NEXT I -1040 RETURN -``` - -At line 150, `A` is set to 1, and `B` is set to 7. Line number 160 is pushed on -to the stack, and the program jumps to line 1000. The code a line 1000 through -1030 sets the value of `S` to the sum of `A` through `B` inclusive. At line -1040, the `RETURN` statement pops 160 from the stack and jumps to that line -number. At line 160 the value of `A`, `B`, and `S` are displayed: - -``` -The sum from 1 to 7 is 28 -``` - -Finally, the [END][20] statement can be used to stop the execution of the -program. It is typically used in the middle of a program. For the above -example, if line 170 were an `END` statement the program would exit instead -of falling through to line 1000. - -### Further Reading - -This is just an overview of the Commodore BASIC language. If you want a more -in-depth look at this language, see the [Commodore BASIC Wiki][21]. If you'd -like to try out this language, then clone the [cbmbasic][22] GitHub -repository, change to the directory where the repository was cloned, and run -the `make` command to build the code. For example: - -```bash -git clone git@github.com:mist64/cbmbasic.git -cd cbmbasic -make -``` - -The output will be called `cbmbasic`. If you just run `cbmbasic` with no -arguments, you should see something like this: - -``` - **** COMMODORE 64 BASIC V2 **** - - 64K RAM SYSTEM 38911 BASIC BYTES FREE - -READY. -``` - -This will take you into the BASIC interpreter where you can enter a program. -You can also run a BASIC program using `cbmbasic` followed by the path to -the program. For example: - -```bash -cbmbasic hello-world.bas -``` - -[1]: https://en.wikipedia.org/wiki/Commodore_BASIC -[2]: https://en.wikipedia.org/wiki/BASIC -[3]: https://en.wikipedia.org/wiki/Microsoft_BASIC -[4]: https://www.c64-wiki.com/wiki/Microsoft#Commodore_BASIC -[5]: https://www.c64-wiki.com/wiki/BASIC#Entering_a_BASIC_program -[6]: https://www.c64-wiki.com/wiki/LIST -[7]: https://www.c64-wiki.com/wiki/Variable#Variables_in_BASIC -[8]: https://www.c64-wiki.com/wiki/STATUS -[9]: https://www.c64-wiki.com/wiki/TIME -[10]: https://www.c64-wiki.com/wiki/TIME$ -[11]: https://www.c64-wiki.com/wiki/Variable#Names_of_Variables -[12]: https://www.c64-wiki.com/wiki/GOTO -[13]: https://www.c64-wiki.com/wiki/IF -[14]: https://www.c64-wiki.com/wiki/Array -[15]: https://www.c64-wiki.com/wiki/FOR -[16]: https://www.c64-wiki.com/wiki/NEXT -[17]: https://www.c64-wiki.com/wiki/STEP -[18]: https://www.c64-wiki.com/wiki/GOSUB -[19]: https://www.c64-wiki.com/wiki/RETURN -[20]: https://www.c64-wiki.com/wiki/END -[21]: https://www.c64-wiki.com/wiki/BASIC -[22]: https://github.com/mist64/cbmbasic - - -## Articles - -There are 38 articles: - -- [Baklava in Commodore BASIC](/projects/baklava/commodore-basic) -- [Base64 Encode Decode in Commodore BASIC](/projects/base64-encode-decode/commodore-basic) -- [Binary Search in Commodore BASIC](/projects/binary-search/commodore-basic) -- [Bubble Sort in Commodore BASIC](/projects/bubble-sort/commodore-basic) -- [Capitalize in Commodore BASIC](/projects/capitalize/commodore-basic) -- [Convex Hull in Commodore BASIC](/projects/convex-hull/commodore-basic) -- [Depth First Search in Commodore BASIC](/projects/depth-first-search/commodore-basic) -- [Dijkstra in Commodore BASIC](/projects/dijkstra/commodore-basic) -- [Duplicate Character Counter in Commodore BASIC](/projects/duplicate-character-counter/commodore-basic) -- [Even Odd in Commodore BASIC](/projects/even-odd/commodore-basic) -- [Factorial in Commodore BASIC](/projects/factorial/commodore-basic) -- [Fibonacci in Commodore BASIC](/projects/fibonacci/commodore-basic) -- [File Input Output in Commodore BASIC](/projects/file-input-output/commodore-basic) -- [Fizz Buzz in Commodore BASIC](/projects/fizz-buzz/commodore-basic) -- [Fraction Math in Commodore BASIC](/projects/fraction-math/commodore-basic) -- [Hello World in Commodore BASIC](/projects/hello-world/commodore-basic) -- [Insertion Sort in Commodore BASIC](/projects/insertion-sort/commodore-basic) -- [Job Sequencing in Commodore BASIC](/projects/job-sequencing/commodore-basic) -- [Josephus Problem in Commodore BASIC](/projects/josephus-problem/commodore-basic) -- [Linear Search in Commodore BASIC](/projects/linear-search/commodore-basic) -- [Longest Common Subsequence in Commodore BASIC](/projects/longest-common-subsequence/commodore-basic) -- [Longest Palindromic Substring in Commodore BASIC](/projects/longest-palindromic-substring/commodore-basic) -- [Longest Word in Commodore BASIC](/projects/longest-word/commodore-basic) -- [Maximum Array Rotation in Commodore BASIC](/projects/maximum-array-rotation/commodore-basic) -- [Maximum Subarray in Commodore BASIC](/projects/maximum-subarray/commodore-basic) -- [Merge Sort in Commodore BASIC](/projects/merge-sort/commodore-basic) -- [Minimum Spanning Tree in Commodore BASIC](/projects/minimum-spanning-tree/commodore-basic) -- [Palindromic Number in Commodore BASIC](/projects/palindromic-number/commodore-basic) -- [Prime Number in Commodore BASIC](/projects/prime-number/commodore-basic) -- [Quick Sort in Commodore BASIC](/projects/quick-sort/commodore-basic) -- [Quine in Commodore BASIC](/projects/quine/commodore-basic) -- [Remove All Whitespace in Commodore BASIC](/projects/remove-all-whitespace/commodore-basic) -- [Reverse String in Commodore BASIC](/projects/reverse-string/commodore-basic) -- [Roman Numeral in Commodore BASIC](/projects/roman-numeral/commodore-basic) -- [Rot13 in Commodore BASIC](/projects/rot13/commodore-basic) -- [Selection Sort in Commodore BASIC](/projects/selection-sort/commodore-basic) -- [Transpose Matrix in Commodore BASIC](/projects/transpose-matrix/commodore-basic) -- [Zeckendorf in Commodore BASIC](/projects/zeckendorf/commodore-basic) \ No newline at end of file diff --git a/docs/languages/crystal/index.md b/docs/languages/crystal/index.md deleted file mode 100644 index 7d83ec874f..0000000000 --- a/docs/languages/crystal/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-22 -featured-image: programming-languages.jpg -last-modified: 2025-02-16 -layout: default -tags: -- crystal -title: The Crystal Programming Language -title1: The Crystal -title2: Programming Language ---- - - - -Welcome to the Crystal page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Like [Julia][1], [Crystal][2] is another open-source language with a nice Wikipedia -page, so we'll be using that to get some language background. - -According to [Wikipedia][2], Crystal is a general-purpose language that first -appeared in 2014. As of today, Crystal is self-hosted meaning the compiler -is written in an earlier version of Crystal. - -That said, Crystal was inspired by [Ruby][3] which is the language Crystal was -originally written in. However, as previously mentioned, Crystal is a compiled -language, so many of the dynamic features of Ruby no longer exist. - -Despite the lack of dynamic features, Crystal leverages strong type inference -to allow for implicit typing. As a result, the language looks like a high-level -scripting language. However, the language's efficiency is much closer to -lower-level languages like C. - -[1]: https://en.wikipedia.org/wiki/Julia_(programming_language) -[2]: https://en.wikipedia.org/wiki/Crystal_(programming_language) -[3]: https://en.wikipedia.org/wiki/Ruby_(programming_language) - - -## Articles - -There are 4 articles: - -- [Baklava in Crystal](/projects/baklava/crystal) -- [Factorial in Crystal](/projects/factorial/crystal) -- [Fizz Buzz in Crystal](/projects/fizz-buzz/crystal) -- [Hello World in Crystal](/projects/hello-world/crystal) \ No newline at end of file diff --git a/docs/languages/cyclone/index.md b/docs/languages/cyclone/index.md deleted file mode 100644 index 743a818213..0000000000 --- a/docs/languages/cyclone/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2020-12-02 -featured-image: programming-languages.jpg -last-modified: 2025-01-17 -layout: default -tags: -- cyclone -title: The Cyclone Programming Language -title1: The Cyclone -title2: Programming Language ---- - - - -Welcome to the Cyclone page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Cyclone](/projects/baklava/cyclone) -- [Hello World in Cyclone](/projects/hello-world/cyclone) \ No newline at end of file diff --git a/docs/languages/cython/index.md b/docs/languages/cython/index.md deleted file mode 100644 index 1ffaa4a0ce..0000000000 --- a/docs/languages/cython/index.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -date: 2025-10-27 -featured-image: programming-languages.jpg -last-modified: 2025-10-31 -layout: default -tags: -- cython -title: The Cython Programming Language -title1: The Cython -title2: Programming Language ---- - - - -Welcome to the Cython page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 4 articles: - -- [Baklava in Cython](/projects/baklava/cython) -- [Fizz Buzz in Cython](/projects/fizz-buzz/cython) -- [Hello World in Cython](/projects/hello-world/cython) -- [Quine in Cython](/projects/quine/cython) \ No newline at end of file diff --git a/docs/languages/d/index.md b/docs/languages/d/index.md deleted file mode 100644 index e79965135c..0000000000 --- a/docs/languages/d/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-05-06 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- d -title: The D Programming Language -title1: The D Programming -title2: Language ---- - - - -Welcome to the D page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -If you haven't heard of [D][1], I'm hardly surprised. After all, it's -not exactly a popular language. In fact, it currently ranks 39th by -popularity on GitHub. For reference, languages ahead of D include -[Visual Basic .NET][2] (31st), [Haskell][3] (21st), [Swift][4] (18th), and [C][5] (8th). -Meanwhile, D sits narrowly ahead of newer languages like [Julia][6] (43rd) -and [Elixir][7] (45th). - -That said, according to [Wikipedia][1], D is still a pretty interesting -language. As you can probably imagine, D is supposed to be an -improvement on C++. Apparently, the designers weren't a fan of the -practical issues surrounding C++ (surprise, surprise!). As a result, -D includes features like design by contract, garbage collection, -associative arrays, array slicing, and lazy evaluation. - -Perhaps the most interesting feature to me has to be the inline -assembler. Apparently, developers can write assembly code directly -in D source code: - -```d -void *pc; -asm -{ - pop EBX ; - mov pc[EBP], EBX ; -} -``` - -By adding an asm block, developers can quickly tap into the hardware -with assembly code. Now, I think that is a pretty cool programming -language feature. - -[1]: https://en.wikipedia.org/wiki/D_(programming_language) -[2]: https://en.wikipedia.org/wiki/Visual_Basic_(.NET) -[3]: https://en.wikipedia.org/wiki/Haskell -[4]: https://en.wikipedia.org/wiki/Swift_(programming_language) -[5]: https://en.wikipedia.org/wiki/C_(programming_language) -[6]: https://en.wikipedia.org/wiki/Julia_(programming_language) -[7]: https://en.wikipedia.org/wiki/Elixir_(programming_language) - - -## Articles - -There are 4 articles: - -- [Baklava in D](/projects/baklava/d) -- [Factorial in D](/projects/factorial/d) -- [Fizz Buzz in D](/projects/fizz-buzz/d) -- [Hello World in D](/projects/hello-world/d) \ No newline at end of file diff --git a/docs/languages/dale/index.md b/docs/languages/dale/index.md deleted file mode 100644 index cfc7a6d4d9..0000000000 --- a/docs/languages/dale/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-10-03 -featured-image: programming-languages.jpg -last-modified: 2025-01-13 -layout: default -tags: -- dale -title: The Dale Programming Language -title1: The Dale Programming -title2: Language ---- - - - -Welcome to the Dale page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Dale](/projects/baklava/dale) -- [Hello World in Dale](/projects/hello-world/dale) \ No newline at end of file diff --git a/docs/languages/dart/index.md b/docs/languages/dart/index.md deleted file mode 100644 index 6d5dbc04c5..0000000000 --- a/docs/languages/dart/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-06-21 -featured-image: programming-languages.jpg -last-modified: 2025-10-05 -layout: default -tags: -- dart -title: The Dart Programming Language -title1: The Dart Programming -title2: Language ---- - - - -Welcome to the Dart page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -[Dart][1] is a general-purpose language that was designed with five goals: - -- Productive - - Dart's syntax is clear and concise, its tooling simple yet powerful. - Sound typing helps you to identify subtle errors early. Dart has - battle-hardened core libraries and an ecosystem of thousands of packages -- Fast - - Dart provides optimizing ahead-of-time compilation to get predictably - high performance and fast startup across mobile devices and the web. -- Portable - - Dart compiles to ARM and x86 code, so that Dart mobile apps can run natively - on iOS, Android, and beyond. For web apps, Dart compiles to JavaScript. -- Approachable - - Dart is familiar to many existing developers, thanks to its unsurprising - object orientation and syntax. If you already know C++, C#, or Java, you can - be productive with Dart in just a few days. -- Reactive - - Dart is well-suited to reactive programming, with support for managing - short-lived objects, such as UI widgets, through Dart's fast object allocation - and generational garbage collector. Dart supports asynchronous programming - through language features and APIs that use Future and Stream objects. - -Since its inception, Dart has gone through different phases as Google tried to -sell its potential to developers. Google has rebuilt it's advertising service -AdSense with Dart. That demonstrate's Google's commitment to Dart by depending -on the language for it's main method of generating revenue. - -The language also has many great features like garbage collection and a strong -typing system (as of Dart 2.0). All of it sits on top of a VM like Java, which -allows there to be less configuration between the test side and the source code. -A programmer can just get started from the get-go! - -[1]: https://en.wikipedia.org/wiki/Dart_(programming_language) - - -## Articles - -There are 17 articles: - -- [Baklava in Dart](/projects/baklava/dart) -- [Bubble Sort in Dart](/projects/bubble-sort/dart) -- [Capitalize in Dart](/projects/capitalize/dart) -- [Duplicate Character Counter in Dart](/projects/duplicate-character-counter/dart) -- [Even Odd in Dart](/projects/even-odd/dart) -- [Factorial in Dart](/projects/factorial/dart) -- [Fibonacci in Dart](/projects/fibonacci/dart) -- [Fizz Buzz in Dart](/projects/fizz-buzz/dart) -- [Hello World in Dart](/projects/hello-world/dart) -- [Longest Word in Dart](/projects/longest-word/dart) -- [Palindromic Number in Dart](/projects/palindromic-number/dart) -- [Prime Number in Dart](/projects/prime-number/dart) -- [Quick Sort in Dart](/projects/quick-sort/dart) -- [Remove All Whitespace in Dart](/projects/remove-all-whitespace/dart) -- [Reverse String in Dart](/projects/reverse-string/dart) -- [Roman Numeral in Dart](/projects/roman-numeral/dart) -- [Rot13 in Dart](/projects/rot13/dart) \ No newline at end of file diff --git a/docs/languages/dg/index.md b/docs/languages/dg/index.md deleted file mode 100644 index d48bc7f6b9..0000000000 --- a/docs/languages/dg/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -date: 2018-10-03 -featured-image: programming-languages.jpg -last-modified: 2025-01-13 -layout: default -tags: -- dg -title: The Dg Programming Language -title1: The Dg Programming -title2: Language ---- - - - -Welcome to the Dg page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 6 articles: - -- [Baklava in Dg](/projects/baklava/dg) -- [File Input Output in Dg](/projects/file-input-output/dg) -- [Fizz Buzz in Dg](/projects/fizz-buzz/dg) -- [Hello World in Dg](/projects/hello-world/dg) -- [Quine in Dg](/projects/quine/dg) -- [Reverse String in Dg](/projects/reverse-string/dg) \ No newline at end of file diff --git a/docs/languages/discus/index.md b/docs/languages/discus/index.md deleted file mode 100644 index c83d685a90..0000000000 --- a/docs/languages/discus/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2021-05-24 -featured-image: programming-languages.jpg -last-modified: 2025-01-14 -layout: default -tags: -- discus -title: The Discus Programming Language -title1: The Discus -title2: Programming Language ---- - - - -Welcome to the Discus page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Discus](/projects/baklava/discus) -- [Hello World in Discus](/projects/hello-world/discus) \ No newline at end of file diff --git a/docs/languages/dusk/index.md b/docs/languages/dusk/index.md deleted file mode 100644 index 473f5d5045..0000000000 --- a/docs/languages/dusk/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-12-30 -featured-image: programming-languages.jpg -last-modified: 2025-01-14 -layout: default -tags: -- dusk -title: The Dusk Programming Language -title1: The Dusk Programming -title2: Language ---- - - - -Welcome to the Dusk page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Dusk](/projects/baklava/dusk) -- [Hello World in Dusk](/projects/hello-world/dusk) \ No newline at end of file diff --git a/docs/languages/egison/index.md b/docs/languages/egison/index.md deleted file mode 100644 index df88d71000..0000000000 --- a/docs/languages/egison/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2024-04-15 -featured-image: programming-languages.jpg -last-modified: 2025-01-08 -layout: default -tags: -- egison -title: The Egison Programming Language -title1: The Egison -title2: Programming Language ---- - - - -Welcome to the Egison page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Egison](/projects/baklava/egison) -- [Hello World in Egison](/projects/hello-world/egison) \ No newline at end of file diff --git a/docs/languages/eiffel/index.md b/docs/languages/eiffel/index.md deleted file mode 100644 index 84ee2f2335..0000000000 --- a/docs/languages/eiffel/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2021-05-25 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- eiffel -title: The Eiffel Programming Language -title1: The Eiffel -title2: Programming Language ---- - - - -Welcome to the Eiffel page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Eiffel](/projects/baklava/eiffel) -- [Fizz Buzz in Eiffel](/projects/fizz-buzz/eiffel) -- [Hello World in Eiffel](/projects/hello-world/eiffel) \ No newline at end of file diff --git a/docs/languages/elena/index.md b/docs/languages/elena/index.md deleted file mode 100644 index f2193028c2..0000000000 --- a/docs/languages/elena/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-12-16 -featured-image: programming-languages.jpg -last-modified: 2025-09-25 -layout: default -tags: -- elena -title: The Elena Programming Language -title1: The Elena Programming -title2: Language ---- - - - -Welcome to the Elena page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Elena](/projects/baklava/elena) -- [Hello World in Elena](/projects/hello-world/elena) \ No newline at end of file diff --git a/docs/languages/elixir/index.md b/docs/languages/elixir/index.md deleted file mode 100644 index 320d978a02..0000000000 --- a/docs/languages/elixir/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2019-04-25 -featured-image: programming-languages.jpg -last-modified: 2023-05-15 -layout: default -tags: -- elixir -title: The Elixir Programming Language -title1: The Elixir -title2: Programming Language ---- - - - -Welcome to the Elixir page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -[Elixir][1] is yet another general-purpose language with functional tendencies. -That said, Elixir is quite a bit different from some of our recent -languages. For starters, Elixir runs on the Erlang virtual machine -known as BEAM. This means that Elixir actually compiles down to bytecode -much like Java. - -In terms of features, Elixir has a lot to offer. For instance, Elixir -has support for macros which modify the abstract syntax tree. You may -recall that Rust has the same feature. - -In addition, Elixir offers Python-like doc strings which leverage Markdown. -This is a great feature for automatically generating documentation. - -Another cool feature of Elixir is exactly what I found interesting about -Scala: everything is an expression. In other words, everything evaluates -to a value. - -Finally, my favorite feature of Elixir has to be pattern matching. In -Elixir, we can match patterns using the same operator most languages use -for assignment: `=`. For example: - -```elixir -myVal = 5 -5 = myVal # A valid match -6 = myVal # (MatchError) no match of right hand side value: 5 -``` - -In this example, we assign myVal a value of 5. Or in Elixir terminology, -we actually bind a value of 5 to myVal through pattern matching. Then, we -compare 5 to myVal which is a valid match. With that in mind, it's clear -why we get an error when we try to match 6 to myVal. - -Of course, pattern matching gets much more fun than that. We can also use -pattern matching to destructure other data types: - -```elixir -{x, y, z} = {:hi, 117, "some string"} -x # :hi -y # 117 -z # "some string" -``` - -In addition, there are several other ways pattern matching can be used, but -we have to get to our implementation of Hello World in Elixir. - -[1]: https://en.wikipedia.org/wiki/Elixir_(programming_language) - - -## Articles - -There are 8 articles: - -- [Baklava in Elixir](/projects/baklava/elixir) -- [Bubble Sort in Elixir](/projects/bubble-sort/elixir) -- [Capitalize in Elixir](/projects/capitalize/elixir) -- [Even Odd in Elixir](/projects/even-odd/elixir) -- [Factorial in Elixir](/projects/factorial/elixir) -- [Fizz Buzz in Elixir](/projects/fizz-buzz/elixir) -- [Hello World in Elixir](/projects/hello-world/elixir) -- [Longest Common Subsequence in Elixir](/projects/longest-common-subsequence/elixir) \ No newline at end of file diff --git a/docs/languages/elvish/index.md b/docs/languages/elvish/index.md deleted file mode 100644 index 42c28b8d33..0000000000 --- a/docs/languages/elvish/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -date: 2021-05-25 -featured-image: programming-languages.jpg -last-modified: 2025-01-18 -layout: default -tags: -- elvish -title: The Elvish Programming Language -title1: The Elvish -title2: Programming Language ---- - - - -Welcome to the Elvish page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 14 articles: - -- [Baklava in Elvish](/projects/baklava/elvish) -- [Capitalize in Elvish](/projects/capitalize/elvish) -- [Even Odd in Elvish](/projects/even-odd/elvish) -- [Factorial in Elvish](/projects/factorial/elvish) -- [Fibonacci in Elvish](/projects/fibonacci/elvish) -- [File Input Output in Elvish](/projects/file-input-output/elvish) -- [Fizz Buzz in Elvish](/projects/fizz-buzz/elvish) -- [Hello World in Elvish](/projects/hello-world/elvish) -- [Linear Search in Elvish](/projects/linear-search/elvish) -- [Palindromic Number in Elvish](/projects/palindromic-number/elvish) -- [Prime Number in Elvish](/projects/prime-number/elvish) -- [Remove All Whitespace in Elvish](/projects/remove-all-whitespace/elvish) -- [Reverse String in Elvish](/projects/reverse-string/elvish) -- [Rot13 in Elvish](/projects/rot13/elvish) \ No newline at end of file diff --git a/docs/languages/emojicode/index.md b/docs/languages/emojicode/index.md deleted file mode 100644 index 8b6fc5a98b..0000000000 --- a/docs/languages/emojicode/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-05-05 -featured-image: programming-languages.jpg -last-modified: 2025-01-13 -layout: default -tags: -- emojicode -title: The Emojicode Programming Language -title1: The Emojicode -title2: Programming Language ---- - - - -Welcome to the Emojicode page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Emojicode](/projects/baklava/emojicode) -- [Hello World in Emojicode](/projects/hello-world/emojicode) \ No newline at end of file diff --git a/docs/languages/erlang/index.md b/docs/languages/erlang/index.md deleted file mode 100644 index 609881eb16..0000000000 --- a/docs/languages/erlang/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -date: 2018-08-08 -featured-image: programming-languages.jpg -last-modified: 2023-11-21 -layout: default -tags: -- erlang -title: The Erlang Programming Language -title1: The Erlang -title2: Programming Language ---- - - - -Welcome to the Erlang page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 6 articles: - -- [Baklava in Erlang](/projects/baklava/erlang) -- [Bubble Sort in Erlang](/projects/bubble-sort/erlang) -- [Factorial in Erlang](/projects/factorial/erlang) -- [Fizz Buzz in Erlang](/projects/fizz-buzz/erlang) -- [Hello World in Erlang](/projects/hello-world/erlang) -- [Reverse String in Erlang](/projects/reverse-string/erlang) \ No newline at end of file diff --git a/docs/languages/eta/index.md b/docs/languages/eta/index.md deleted file mode 100644 index edded62501..0000000000 --- a/docs/languages/eta/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2021-05-25 -featured-image: programming-languages.jpg -last-modified: 2025-01-13 -layout: default -tags: -- eta -title: The Eta Programming Language -title1: The Eta Programming -title2: Language ---- - - - -Welcome to the Eta page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Eta](/projects/baklava/eta) -- [Hello World in Eta](/projects/hello-world/eta) \ No newline at end of file diff --git a/docs/languages/euphoria/index.md b/docs/languages/euphoria/index.md deleted file mode 100644 index 77f83ba306..0000000000 --- a/docs/languages/euphoria/index.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-14 -featured-image: programming-languages.jpg -last-modified: 2026-03-07 -layout: default -tags: -- euphoria -title: The Euphoria Programming Language -title1: The Euphoria -title2: Programming Language ---- - - - -Welcome to the Euphoria page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- rzuckerm - -## Description - -[According to OpenEuphoria](https://openeuphoria.org/), Euphoria is an imperative -interpretive programming language has the following features: - -* A flexible memory manager unit that is capable of dynamically growing and shrinking - memory usage -* A high-performance interpreter that is supposed to be faster the other interpretive - languages like Python and Perl -* It is capable of being compiled to improve performance via a - [Euphoria to C Translator](https://openeuphoria.org/docs/e2c.html#_606_euphoriatoctranslator) -* It has run-time checking for out-of-bounds subscripts, bad passed parameters for - library routines, and a full English description of the run-time issues, providing - a full call-stack-trace and variable values -* It is hardware independent from word lengths and endianness -* It provide a full source-level debugging -* It has a built-in code editor -* It runs on a number of platforms like Windows, various Linux flavors, and MacOS -* It is not an object oriented language, so it has no concept of classes -* Simple data types - -There are only four different data types: - -* `object` - Base data type -* `atom` - A 31-bit signed integer or 64-bit floating point number depending upon the - value stored -* `integer` - A 31-bit in signed integer -* `sequence` - A list of values. This list can be comprised of `atom`s or other - `sequence`s - -According to [Wikipedia](https://en.wikipedia.org/wiki/Euphoria_(programming_language)), -there is no actual `string` data type. Instead a `string` is just a `sequence` -of `atom`s. For example: -``` -"ABC" -``` - -is actually this: -``` -{65, 66, 67} -``` - -[User-specified data types](https://openeuphoria.org/docs/lang_decl.html#_123_userdefinedtypes) -can be done based on these four data types. The way this is done is to declare a type -function that validates the input value. For example, if you wanted to define an -`hour` type that only allowed integers from 0 to 23, you would do this: - -```euphoria -type hour(integer x) - return x >= 0 and x <= 23 -end type -``` - -Keywords in Euphoria are rather simple. For each type of keyword that does control flow or -declares a `function` or `procedure` (more on that later), there is a corresponding `end` -keyword that declares the end of that structure. For example: - -```euphoria -if x = 42 -then - do_something_cool(x) -end if -``` - -Euphoria makes the distinction between functions and procedures. Functions returns -values, whereas procedures do not (think of it like a `void` function in C). -For example: - -```euphoria -function foo(integer bar) - return bar + 100 -end function -``` - -The above function `foo` just returns the value of `bar` plus 100. Here's an example -of a procedure: - -```euphoria -procedure baz(sequence s) - fputs(1, s & '\n') -end procedure -``` - -The above procedure `baz` just outputs a string with a newline to standard out. - -Parameter passing in Euphoria is rather unique. According to -[Wikipedia](https://en.wikipedia.org/wiki/Euphoria_(programming_language)#Parameter_passing): - -> Arguments to routines are always passed by value; there is no pass-by-reference facility. - Parameters are allowed to be modified locally (i.e., within the callee) which is implemented - very efficiently as sequences have automatic copy-on-write semantics. In other words, when you - pass a sequence to a routine, initially only a reference to it is passed, but at the point the - routine modifies this sequence parameter the sequence is copied and the routine updates only a - copy of the original. - -If you'd like more information about this language, please see the -[OpenEuphoria manual](https://openeuphoria.org/docs/index.html). - - -## Articles - -There are 38 articles: - -- [Baklava in Euphoria](/projects/baklava/euphoria) -- [Base64 Encode Decode in Euphoria](/projects/base64-encode-decode/euphoria) -- [Binary Search in Euphoria](/projects/binary-search/euphoria) -- [Bubble Sort in Euphoria](/projects/bubble-sort/euphoria) -- [Capitalize in Euphoria](/projects/capitalize/euphoria) -- [Convex Hull in Euphoria](/projects/convex-hull/euphoria) -- [Depth First Search in Euphoria](/projects/depth-first-search/euphoria) -- [Dijkstra in Euphoria](/projects/dijkstra/euphoria) -- [Duplicate Character Counter in Euphoria](/projects/duplicate-character-counter/euphoria) -- [Even Odd in Euphoria](/projects/even-odd/euphoria) -- [Factorial in Euphoria](/projects/factorial/euphoria) -- [Fibonacci in Euphoria](/projects/fibonacci/euphoria) -- [File Input Output in Euphoria](/projects/file-input-output/euphoria) -- [Fizz Buzz in Euphoria](/projects/fizz-buzz/euphoria) -- [Fraction Math in Euphoria](/projects/fraction-math/euphoria) -- [Hello World in Euphoria](/projects/hello-world/euphoria) -- [Insertion Sort in Euphoria](/projects/insertion-sort/euphoria) -- [Job Sequencing in Euphoria](/projects/job-sequencing/euphoria) -- [Josephus Problem in Euphoria](/projects/josephus-problem/euphoria) -- [Linear Search in Euphoria](/projects/linear-search/euphoria) -- [Longest Common Subsequence in Euphoria](/projects/longest-common-subsequence/euphoria) -- [Longest Palindromic Substring in Euphoria](/projects/longest-palindromic-substring/euphoria) -- [Longest Word in Euphoria](/projects/longest-word/euphoria) -- [Maximum Array Rotation in Euphoria](/projects/maximum-array-rotation/euphoria) -- [Maximum Subarray in Euphoria](/projects/maximum-subarray/euphoria) -- [Merge Sort in Euphoria](/projects/merge-sort/euphoria) -- [Minimum Spanning Tree in Euphoria](/projects/minimum-spanning-tree/euphoria) -- [Palindromic Number in Euphoria](/projects/palindromic-number/euphoria) -- [Prime Number in Euphoria](/projects/prime-number/euphoria) -- [Quick Sort in Euphoria](/projects/quick-sort/euphoria) -- [Quine in Euphoria](/projects/quine/euphoria) -- [Remove All Whitespace in Euphoria](/projects/remove-all-whitespace/euphoria) -- [Reverse String in Euphoria](/projects/reverse-string/euphoria) -- [Roman Numeral in Euphoria](/projects/roman-numeral/euphoria) -- [Rot13 in Euphoria](/projects/rot13/euphoria) -- [Selection Sort in Euphoria](/projects/selection-sort/euphoria) -- [Transpose Matrix in Euphoria](/projects/transpose-matrix/euphoria) -- [Zeckendorf in Euphoria](/projects/zeckendorf/euphoria) \ No newline at end of file diff --git a/docs/languages/f-sharp/index.md b/docs/languages/f-sharp/index.md deleted file mode 100644 index 801b3b4021..0000000000 --- a/docs/languages/f-sharp/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2018-04-27 -featured-image: programming-languages.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -title: The F# Programming Language -title1: The F# Programming -title2: Language ---- - - - -Welcome to the F# page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in F#](/projects/baklava/f-sharp) -- [Base64 Encode Decode in F#](/projects/base64-encode-decode/f-sharp) -- [Binary Search in F#](/projects/binary-search/f-sharp) -- [Bubble Sort in F#](/projects/bubble-sort/f-sharp) -- [Capitalize in F#](/projects/capitalize/f-sharp) -- [Convex Hull in F#](/projects/convex-hull/f-sharp) -- [Depth First Search in F#](/projects/depth-first-search/f-sharp) -- [Dijkstra in F#](/projects/dijkstra/f-sharp) -- [Duplicate Character Counter in F#](/projects/duplicate-character-counter/f-sharp) -- [Even Odd in F#](/projects/even-odd/f-sharp) -- [Factorial in F#](/projects/factorial/f-sharp) -- [Fibonacci in F#](/projects/fibonacci/f-sharp) -- [File Input Output in F#](/projects/file-input-output/f-sharp) -- [Fizz Buzz in F#](/projects/fizz-buzz/f-sharp) -- [Fraction Math in F#](/projects/fraction-math/f-sharp) -- [Hello World in F#](/projects/hello-world/f-sharp) -- [Insertion Sort in F#](/projects/insertion-sort/f-sharp) -- [Job Sequencing in F#](/projects/job-sequencing/f-sharp) -- [Josephus Problem in F#](/projects/josephus-problem/f-sharp) -- [Linear Search in F#](/projects/linear-search/f-sharp) -- [Longest Common Subsequence in F#](/projects/longest-common-subsequence/f-sharp) -- [Longest Palindromic Substring in F#](/projects/longest-palindromic-substring/f-sharp) -- [Longest Word in F#](/projects/longest-word/f-sharp) -- [Maximum Array Rotation in F#](/projects/maximum-array-rotation/f-sharp) -- [Maximum Subarray in F#](/projects/maximum-subarray/f-sharp) -- [Merge Sort in F#](/projects/merge-sort/f-sharp) -- [Minimum Spanning Tree in F#](/projects/minimum-spanning-tree/f-sharp) -- [Palindromic Number in F#](/projects/palindromic-number/f-sharp) -- [Prime Number in F#](/projects/prime-number/f-sharp) -- [Quick Sort in F#](/projects/quick-sort/f-sharp) -- [Quine in F#](/projects/quine/f-sharp) -- [Remove All Whitespace in F#](/projects/remove-all-whitespace/f-sharp) -- [Reverse String in F#](/projects/reverse-string/f-sharp) -- [Roman Numeral in F#](/projects/roman-numeral/f-sharp) -- [Rot13 in F#](/projects/rot13/f-sharp) -- [Selection Sort in F#](/projects/selection-sort/f-sharp) -- [Transpose Matrix in F#](/projects/transpose-matrix/f-sharp) -- [Zeckendorf in F#](/projects/zeckendorf/f-sharp) \ No newline at end of file diff --git a/docs/languages/f-star/index.md b/docs/languages/f-star/index.md deleted file mode 100644 index 29e8a9620d..0000000000 --- a/docs/languages/f-star/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2021-05-24 -featured-image: programming-languages.jpg -last-modified: 2025-01-06 -layout: default -tags: -- f-star -title: The F* Programming Language -title1: The F* Programming -title2: Language ---- - - - -Welcome to the F\* page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in F\*](/projects/baklava/f-star) -- [Hello World in F\*](/projects/hello-world/f-star) \ No newline at end of file diff --git a/docs/languages/factor/index.md b/docs/languages/factor/index.md deleted file mode 100644 index 173009ae87..0000000000 --- a/docs/languages/factor/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-05-03 -featured-image: programming-languages.jpg -last-modified: 2025-01-06 -layout: default -tags: -- factor -title: The Factor Programming Language -title1: The Factor -title2: Programming Language ---- - - - -Welcome to the Factor page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Factor](/projects/baklava/factor) -- [Hello World in Factor](/projects/hello-world/factor) \ No newline at end of file diff --git a/docs/languages/felix/index.md b/docs/languages/felix/index.md deleted file mode 100644 index 0711e39e0c..0000000000 --- a/docs/languages/felix/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-04-29 -featured-image: programming-languages.jpg -last-modified: 2025-01-06 -layout: default -tags: -- felix -title: The Felix Programming Language -title1: The Felix Programming -title2: Language ---- - - - -Welcome to the Felix page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Felix](/projects/baklava/felix) -- [Hello World in Felix](/projects/hello-world/felix) \ No newline at end of file diff --git a/docs/languages/fennel/index.md b/docs/languages/fennel/index.md deleted file mode 100644 index 174aaa024a..0000000000 --- a/docs/languages/fennel/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-12-30 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- fennel -title: The Fennel Programming Language -title1: The Fennel -title2: Programming Language ---- - - - -Welcome to the Fennel page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Fennel](/projects/baklava/fennel) -- [Fizz Buzz in Fennel](/projects/fizz-buzz/fennel) -- [Hello World in Fennel](/projects/hello-world/fennel) \ No newline at end of file diff --git a/docs/languages/ferret/index.md b/docs/languages/ferret/index.md deleted file mode 100644 index 06c50c09dc..0000000000 --- a/docs/languages/ferret/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-10-09 -featured-image: programming-languages.jpg -last-modified: 2025-01-06 -layout: default -tags: -- ferret -title: The Ferret Programming Language -title1: The Ferret -title2: Programming Language ---- - - - -Welcome to the Ferret page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Ferret](/projects/baklava/ferret) -- [Hello World in Ferret](/projects/hello-world/ferret) \ No newline at end of file diff --git a/docs/languages/fetlang/index.md b/docs/languages/fetlang/index.md deleted file mode 100644 index c1e6563b00..0000000000 --- a/docs/languages/fetlang/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-05-03 -featured-image: programming-languages.jpg -last-modified: 2025-01-13 -layout: default -tags: -- fetlang -title: The Fetlang Programming Language -title1: The Fetlang -title2: Programming Language ---- - - - -Welcome to the Fetlang page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Fetlang](/projects/baklava/fetlang) -- [Fizz Buzz in Fetlang](/projects/fizz-buzz/fetlang) -- [Hello World in Fetlang](/projects/hello-world/fetlang) \ No newline at end of file diff --git a/docs/languages/flix/index.md b/docs/languages/flix/index.md deleted file mode 100644 index 3f65c545ff..0000000000 --- a/docs/languages/flix/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2025-01-04 -featured-image: programming-languages.jpg -last-modified: 2025-01-06 -layout: default -tags: -- flix -title: The Flix Programming Language -title1: The Flix Programming -title2: Language ---- - - - -Welcome to the Flix page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Flix](/projects/baklava/flix) -- [Hello World in Flix](/projects/hello-world/flix) \ No newline at end of file diff --git a/docs/languages/formality/index.md b/docs/languages/formality/index.md deleted file mode 100644 index 94d6b51f1f..0000000000 --- a/docs/languages/formality/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-12-16 -featured-image: programming-languages.jpg -last-modified: 2025-01-06 -layout: default -tags: -- formality -title: The Formality Programming Language -title1: The Formality -title2: Programming Language ---- - - - -Welcome to the Formality page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Formality](/projects/baklava/formality) -- [Hello World in Formality](/projects/hello-world/formality) \ No newline at end of file diff --git a/docs/languages/forth/index.md b/docs/languages/forth/index.md deleted file mode 100644 index d4a42f8a7c..0000000000 --- a/docs/languages/forth/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2023-11-16 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- forth -title: The Forth Programming Language -title1: The Forth Programming -title2: Language ---- - - - -Welcome to the Forth page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Forth](/projects/baklava/forth) -- [Fizz Buzz in Forth](/projects/fizz-buzz/forth) -- [Hello World in Forth](/projects/hello-world/forth) \ No newline at end of file diff --git a/docs/languages/fortran/index.md b/docs/languages/fortran/index.md deleted file mode 100644 index 0dd6cab25c..0000000000 --- a/docs/languages/fortran/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -date: 2020-10-01 -featured-image: programming-languages.jpg -last-modified: 2025-11-12 -layout: default -tags: -- fortran -title: The Fortran Programming Language -title1: The Fortran -title2: Programming Language ---- - - - -Welcome to the Fortran page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 13 articles: - -- [Baklava in Fortran](/projects/baklava/fortran) -- [Binary Search in Fortran](/projects/binary-search/fortran) -- [Bubble Sort in Fortran](/projects/bubble-sort/fortran) -- [Capitalize in Fortran](/projects/capitalize/fortran) -- [Even Odd in Fortran](/projects/even-odd/fortran) -- [Factorial in Fortran](/projects/factorial/fortran) -- [Fibonacci in Fortran](/projects/fibonacci/fortran) -- [Fizz Buzz in Fortran](/projects/fizz-buzz/fortran) -- [Hello World in Fortran](/projects/hello-world/fortran) -- [Insertion Sort in Fortran](/projects/insertion-sort/fortran) -- [Linear Search in Fortran](/projects/linear-search/fortran) -- [Prime Number in Fortran](/projects/prime-number/fortran) -- [Reverse String in Fortran](/projects/reverse-string/fortran) \ No newline at end of file diff --git a/docs/languages/frege/index.md b/docs/languages/frege/index.md deleted file mode 100644 index 283bcd6344..0000000000 --- a/docs/languages/frege/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-11-14 -featured-image: programming-languages.jpg -last-modified: 2025-01-06 -layout: default -tags: -- frege -title: The Frege Programming Language -title1: The Frege Programming -title2: Language ---- - - - -Welcome to the Frege page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Frege](/projects/baklava/frege) -- [Hello World in Frege](/projects/hello-world/frege) \ No newline at end of file diff --git a/docs/languages/gerbil/index.md b/docs/languages/gerbil/index.md deleted file mode 100644 index 19803cb990..0000000000 --- a/docs/languages/gerbil/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-08-07 -featured-image: programming-languages.jpg -last-modified: 2025-01-01 -layout: default -tags: -- gerbil -title: The Gerbil Programming Language -title1: The Gerbil -title2: Programming Language ---- - - - -Welcome to the Gerbil page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Gerbil](/projects/baklava/gerbil) -- [Hello World in Gerbil](/projects/hello-world/gerbil) \ No newline at end of file diff --git a/docs/languages/gluon/index.md b/docs/languages/gluon/index.md deleted file mode 100644 index cfe89ff978..0000000000 --- a/docs/languages/gluon/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-12-30 -featured-image: programming-languages.jpg -last-modified: 2025-01-01 -layout: default -tags: -- gluon -title: The Gluon Programming Language -title1: The Gluon Programming -title2: Language ---- - - - -Welcome to the Gluon page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Gluon](/projects/baklava/gluon) -- [Hello World in Gluon](/projects/hello-world/gluon) \ No newline at end of file diff --git a/docs/languages/gnu-make/index.md b/docs/languages/gnu-make/index.md deleted file mode 100644 index 41a12c8861..0000000000 --- a/docs/languages/gnu-make/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-07-11 -featured-image: programming-languages.jpg -last-modified: 2025-10-05 -layout: default -tags: -- gnu-make -title: The GNU Make Programming Language -title1: The GNU Make -title2: Programming Language ---- - - - -Welcome to the GNU Make page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- rzuckerm - -## Description - -According to [Wikipedia][1], `make` is an automated tool for building software. -It was created in 1976 by [Stuart Freedman][2] for [Unix][3] systems, and it is -still used today on Unix and Unix-like systems (such as [Linux][4] and -[MacOS][5]). For such systems, [GNU make][6] is the most prevelant. - -In general, make gets it instructions on what to build based on a Makefile. -The syntax for a Makefile is like this: - -```make -target1 [target2 ...]: dependency1 [dependency2 ...] - command1 - command2 - ... -``` - -The "target" is what is being built, "dependencies" are what the target -depends upon, and "commands" are what is executed when the target is built. -It should be noted `make` is a whitespace-sensitive language. Before each -command, is a tab character. It you try to use spaces, you'll get this error: - -``` -*** missing separator. Stop. -``` - -The way `make` works is that a target will be built if it does not exist -or it is older that its dependencies. - -Here's an example of file called `Makefile` (which is the default filename -that `make` looks for): - -```make -hello: hello.c - cc hello.c -o hello -``` - -It build a single C program called `hello.c` into a executable called `hello`. -The command perform this build is this: - -```bash -make hello -``` - -If `hello` does not exist, or if `hello.c` was modified after `hello` was -built, the `cc` command is executed the builds the code. If the `make` command -is run again, it will indicate `'hello' is up to date`. - -In addition to being a build system, GNU make also has a number of other -useful features: - -* [Variables][7] that can be used for everything from simple assignment - to defining user-defined functions in the form of macros. -* [Built-in functions][8] for manipulating text. -* [Conditionals][9] that can be used to ignore or include certain portions - of a Makefile. - -Although GNU make is not really intended as a programming language, these -features allow it to behave as if it were. It can even similate control -flow with certain built-in functions like these: - -* [foreach][10] -* [if][11] -* [call][12] - -Loops can be simulated using macros that invoke themselves recursively. - -[1]: https://en.wikipedia.org/wiki/Make_(software) -[2]: https://en.wikipedia.org/wiki/Stuart_Feldman -[3]: https://en.wikipedia.org/wiki/Unix -[4]: https://en.wikipedia.org/wiki/Linux -[5]: https://en.wikipedia.org/wiki/MacOS -[6]: https://www.gnu.org/software/make/ -[7]: https://www.gnu.org/software/make/manual/html_node/Using-Variables.html -[8]: https://www.gnu.org/software/make/manual/html_node/Functions.html -[9]: https://www.gnu.org/software/make/manual/html_node/Conditionals.html -[10]: https://www.gnu.org/software/make/manual/html_node/Foreach-Function.html -[11]: https://www.gnu.org/software/make/manual/html_node/Conditional-Functions.html#index-if-1 -[12]: https://www.gnu.org/software/make/manual/html_node/Call-Function.html - - -## Articles - -There are 9 articles: - -- [Baklava in GNU Make](/projects/baklava/gnu-make) -- [Capitalize in GNU Make](/projects/capitalize/gnu-make) -- [Even Odd in GNU Make](/projects/even-odd/gnu-make) -- [File Input Output in GNU Make](/projects/file-input-output/gnu-make) -- [Fizz Buzz in GNU Make](/projects/fizz-buzz/gnu-make) -- [Hello World in GNU Make](/projects/hello-world/gnu-make) -- [Prime Number in GNU Make](/projects/prime-number/gnu-make) -- [Quine in GNU Make](/projects/quine/gnu-make) -- [Remove All Whitespace in GNU Make](/projects/remove-all-whitespace/gnu-make) \ No newline at end of file diff --git a/docs/languages/go/index.md b/docs/languages/go/index.md deleted file mode 100644 index 7e7018227a..0000000000 --- a/docs/languages/go/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2018-03-25 -featured-image: programming-languages.jpg -last-modified: 2026-05-07 -layout: default -tags: -- go -title: The Go Programming Language -title1: The Go Programming -title2: Language ---- - - - -Welcome to the Go page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in Go](/projects/baklava/go) -- [Base64 Encode Decode in Go](/projects/base64-encode-decode/go) -- [Binary Search in Go](/projects/binary-search/go) -- [Bubble Sort in Go](/projects/bubble-sort/go) -- [Capitalize in Go](/projects/capitalize/go) -- [Convex Hull in Go](/projects/convex-hull/go) -- [Depth First Search in Go](/projects/depth-first-search/go) -- [Dijkstra in Go](/projects/dijkstra/go) -- [Duplicate Character Counter in Go](/projects/duplicate-character-counter/go) -- [Even Odd in Go](/projects/even-odd/go) -- [Factorial in Go](/projects/factorial/go) -- [Fibonacci in Go](/projects/fibonacci/go) -- [File Input Output in Go](/projects/file-input-output/go) -- [Fizz Buzz in Go](/projects/fizz-buzz/go) -- [Fraction Math in Go](/projects/fraction-math/go) -- [Hello World in Go](/projects/hello-world/go) -- [Insertion Sort in Go](/projects/insertion-sort/go) -- [Job Sequencing in Go](/projects/job-sequencing/go) -- [Josephus Problem in Go](/projects/josephus-problem/go) -- [Linear Search in Go](/projects/linear-search/go) -- [Longest Common Subsequence in Go](/projects/longest-common-subsequence/go) -- [Longest Palindromic Substring in Go](/projects/longest-palindromic-substring/go) -- [Longest Word in Go](/projects/longest-word/go) -- [Maximum Array Rotation in Go](/projects/maximum-array-rotation/go) -- [Maximum Subarray in Go](/projects/maximum-subarray/go) -- [Merge Sort in Go](/projects/merge-sort/go) -- [Minimum Spanning Tree in Go](/projects/minimum-spanning-tree/go) -- [Palindromic Number in Go](/projects/palindromic-number/go) -- [Prime Number in Go](/projects/prime-number/go) -- [Quick Sort in Go](/projects/quick-sort/go) -- [Quine in Go](/projects/quine/go) -- [Remove All Whitespace in Go](/projects/remove-all-whitespace/go) -- [Reverse String in Go](/projects/reverse-string/go) -- [Roman Numeral in Go](/projects/roman-numeral/go) -- [Rot13 in Go](/projects/rot13/go) -- [Selection Sort in Go](/projects/selection-sort/go) -- [Transpose Matrix in Go](/projects/transpose-matrix/go) -- [Zeckendorf in Go](/projects/zeckendorf/go) \ No newline at end of file diff --git a/docs/languages/goby/index.md b/docs/languages/goby/index.md deleted file mode 100644 index 555ef2fa72..0000000000 --- a/docs/languages/goby/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-04-20 -featured-image: programming-languages.jpg -last-modified: 2025-10-30 -layout: default -tags: -- goby -title: The Goby Programming Language -title1: The Goby Programming -title2: Language ---- - - - -Welcome to the Goby page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski - -## Description - -[According to the GitHub project](https://github.com/goby-lang/goby), -Goby, formerly known as Rooby, is a Ruby-like language written in Go. -The goal of the language is to provide a small environment for building -microservices and API servers. - -Beyond that, the project didn't have much to offer in terms of -use cases or samples. That said, the official website does give a few -examples of language features including: - -- Concurrency Support -- Builtin Multi-threaded Server -- Plugin System - -For anyone who would like to give the language a try, Goby can be installed -and ran in REPL mode with the following commands: - -```shell -brew tap goby-lang/goby -brew install goby -goby -i -``` - -Alternatively, you can try running all the sample code snippets using -the samplerunner script included in the repo: - -```shell -./samplerunner.sh run -l goby -``` - -Feel free to browse some of the articles in the following section to see -the language in action. - - -## Articles - -There are 3 articles: - -- [Baklava in Goby](/projects/baklava/goby) -- [Fizz Buzz in Goby](/projects/fizz-buzz/goby) -- [Hello World in Goby](/projects/hello-world/goby) \ No newline at end of file diff --git a/docs/languages/golo/index.md b/docs/languages/golo/index.md deleted file mode 100644 index a6387ff9af..0000000000 --- a/docs/languages/golo/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-05-24 -featured-image: programming-languages.jpg -last-modified: 2025-01-01 -layout: default -tags: -- golo -title: The Golo Programming Language -title1: The Golo Programming -title2: Language ---- - - - -Welcome to the Golo page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Golo](/projects/baklava/golo) -- [Hello World in Golo](/projects/hello-world/golo) \ No newline at end of file diff --git a/docs/languages/gosu/index.md b/docs/languages/gosu/index.md deleted file mode 100644 index 37fce973ef..0000000000 --- a/docs/languages/gosu/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2020-11-03 -featured-image: programming-languages.jpg -last-modified: 2025-10-30 -layout: default -tags: -- gosu -title: The Gosu Programming Language -title1: The Gosu Programming -title2: Language ---- - - - -Welcome to the Gosu page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Gosu](/projects/baklava/gosu) -- [Fizz Buzz in Gosu](/projects/fizz-buzz/gosu) -- [Hello World in Gosu](/projects/hello-world/gosu) \ No newline at end of file diff --git a/docs/languages/grain/index.md b/docs/languages/grain/index.md deleted file mode 100644 index 693cc4fc53..0000000000 --- a/docs/languages/grain/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2024-12-31 -featured-image: programming-languages.jpg -last-modified: 2025-01-01 -layout: default -tags: -- grain -title: The Grain Programming Language -title1: The Grain Programming -title2: Language ---- - - - -Welcome to the Grain page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Grain](/projects/baklava/grain) -- [Hello World in Grain](/projects/hello-world/grain) \ No newline at end of file diff --git a/docs/languages/granule/index.md b/docs/languages/granule/index.md deleted file mode 100644 index ec4a6b62b2..0000000000 --- a/docs/languages/granule/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2022-12-06 -featured-image: programming-languages.jpg -last-modified: 2025-01-01 -layout: default -tags: -- granule -title: The Granule Programming Language -title1: The Granule -title2: Programming Language ---- - - - -Welcome to the Granule page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Granule](/projects/baklava/granule) -- [Hello World in Granule](/projects/hello-world/granule) \ No newline at end of file diff --git a/docs/languages/gravity/index.md b/docs/languages/gravity/index.md deleted file mode 100644 index 1c9827dbe3..0000000000 --- a/docs/languages/gravity/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-04-24 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- gravity -title: The Gravity Programming Language -title1: The Gravity -title2: Programming Language ---- - - - -Welcome to the Gravity page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Gravity](/projects/baklava/gravity) -- [Fizz Buzz in Gravity](/projects/fizz-buzz/gravity) -- [Hello World in Gravity](/projects/hello-world/gravity) \ No newline at end of file diff --git a/docs/languages/groovy/index.md b/docs/languages/groovy/index.md deleted file mode 100644 index d9d791e222..0000000000 --- a/docs/languages/groovy/index.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -date: 2018-04-19 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- groovy -title: The Groovy Programming Language -title1: The Groovy -title2: Programming Language ---- - - - -Welcome to the Groovy page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 9 articles: - -- [Baklava in Groovy](/projects/baklava/groovy) -- [Capitalize in Groovy](/projects/capitalize/groovy) -- [Even Odd in Groovy](/projects/even-odd/groovy) -- [Factorial in Groovy](/projects/factorial/groovy) -- [Fibonacci in Groovy](/projects/fibonacci/groovy) -- [Fizz Buzz in Groovy](/projects/fizz-buzz/groovy) -- [Hello World in Groovy](/projects/hello-world/groovy) -- [Merge Sort in Groovy](/projects/merge-sort/groovy) -- [Reverse String in Groovy](/projects/reverse-string/groovy) \ No newline at end of file diff --git a/docs/languages/hack/index.md b/docs/languages/hack/index.md deleted file mode 100644 index 261ead7868..0000000000 --- a/docs/languages/hack/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2019-05-07 -featured-image: programming-languages.jpg -last-modified: 2025-01-01 -layout: default -tags: -- hack -title: The Hack Programming Language -title1: The Hack Programming -title2: Language ---- - - - -Welcome to the Hack page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -According to [Wikipedia][1], Hack is a dialect of PHP used by Facebook. -Beyond that, Wikipedia was really only able to tell me that the -open source language was released in 2014. So for once, I had to -dig into the documentation. - -Apparently, the most important features of Hack are: - -- Generics -- Nullable Types -- Type Annotations -- Collections -- Lambdas - -Now, I think the most interesting feature has to be the type annotations. -That's because Hack is actually dynamically typed like [Python][2]. - -However, if you've used Python, then you know that it has a relatively -new type hinting feature. Typing hinting allows you to arbitrarily -enforce static type checking in your code. I say arbitrarily because -no one is forcing you to use type hints. - -At any rate, Hack has essentially the same feature, but it's restricted -to parameters, class variables, and return values. For example: - -```hack -function foo(int $x): int { - return $x * 2; -} -``` - -Here we've defined some function foo which takes an integer parameter and -returns an integer. Of course, nothing is stopping us from removing those -annotations: - -```hack -function bar($x) { - return $x * 2; -} -``` - -Now, this function would run exactly the same except we wouldn't discover -any type issues until runtime. - -So, what kind of typing system does Hack have? Is it static? How about -dynamic? Well, there's actually a new term for the kind of type system that -languages like Hack and Python have. It's called gradual typing, and it allows -users to specify exactly when they want static or dynamic typing. - -Once again, I think I've explored a topic a bit too deeply, so I'll stop there. - -[1]: https://en.wikipedia.org/wiki/Hack_(programming_language) -[2]: https://en.wikipedia.org/wiki/Python_(programming_language) - - -## Articles - -There are 2 articles: - -- [Baklava in Hack](/projects/baklava/hack) -- [Hello World in Hack](/projects/hello-world/hack) \ No newline at end of file diff --git a/docs/languages/haskell/index.md b/docs/languages/haskell/index.md deleted file mode 100644 index de0f7a97ca..0000000000 --- a/docs/languages/haskell/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-08 -featured-image: programming-languages.jpg -last-modified: 2026-05-23 -layout: default -tags: -- haskell -title: The Haskell Programming Language -title1: The Haskell -title2: Programming Language ---- - - - -Welcome to the Haskell page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -With sixteen of these tutorials already out of the way, it will probably -come as no surprise that I took to [Wikipedia][1] to learn more about Haskell. - -As stated already, Haskell is a general-purpose functional programming -language that first appeared in 1990. Despite its relatively old age, -Haskell is still maintained. In fact, the latest standard was developed -back in 2010. By 2020, a new update should be available. - -In terms of features, Haskell supports strong, static typing, pattern -matching, lazy evaluation, and even list comprehensions. To be honest, -this is the first time I'm hearing about lazy evaluation, so I figured -I'd dig into that a bit. - -As it turns out, lazy evaluation is a technique which defers computation -of a functions input until the value is needed. In other words, expressions -are only evaluated when they are needed. If my explanation is bad, take a -look at the article I linked above. It covers the concept in great depth. - -At any rate, I think that's plenty of background for now. - -[1]: https://en.wikipedia.org/wiki/Haskell - - -## Articles - -There are 37 articles: - -- [Baklava in Haskell](/projects/baklava/haskell) -- [Base64 Encode Decode in Haskell](/projects/base64-encode-decode/haskell) -- [Binary Search in Haskell](/projects/binary-search/haskell) -- [Bubble Sort in Haskell](/projects/bubble-sort/haskell) -- [Capitalize in Haskell](/projects/capitalize/haskell) -- [Convex Hull in Haskell](/projects/convex-hull/haskell) -- [Depth First Search in Haskell](/projects/depth-first-search/haskell) -- [Duplicate Character Counter in Haskell](/projects/duplicate-character-counter/haskell) -- [Even Odd in Haskell](/projects/even-odd/haskell) -- [Factorial in Haskell](/projects/factorial/haskell) -- [Fibonacci in Haskell](/projects/fibonacci/haskell) -- [File Input Output in Haskell](/projects/file-input-output/haskell) -- [Fizz Buzz in Haskell](/projects/fizz-buzz/haskell) -- [Fraction Math in Haskell](/projects/fraction-math/haskell) -- [Hello World in Haskell](/projects/hello-world/haskell) -- [Insertion Sort in Haskell](/projects/insertion-sort/haskell) -- [Job Sequencing in Haskell](/projects/job-sequencing/haskell) -- [Josephus Problem in Haskell](/projects/josephus-problem/haskell) -- [Linear Search in Haskell](/projects/linear-search/haskell) -- [Longest Common Subsequence in Haskell](/projects/longest-common-subsequence/haskell) -- [Longest Palindromic Substring in Haskell](/projects/longest-palindromic-substring/haskell) -- [Longest Word in Haskell](/projects/longest-word/haskell) -- [Maximum Array Rotation in Haskell](/projects/maximum-array-rotation/haskell) -- [Maximum Subarray in Haskell](/projects/maximum-subarray/haskell) -- [Merge Sort in Haskell](/projects/merge-sort/haskell) -- [Minimum Spanning Tree in Haskell](/projects/minimum-spanning-tree/haskell) -- [Palindromic Number in Haskell](/projects/palindromic-number/haskell) -- [Prime Number in Haskell](/projects/prime-number/haskell) -- [Quick Sort in Haskell](/projects/quick-sort/haskell) -- [Quine in Haskell](/projects/quine/haskell) -- [Remove All Whitespace in Haskell](/projects/remove-all-whitespace/haskell) -- [Reverse String in Haskell](/projects/reverse-string/haskell) -- [Roman Numeral in Haskell](/projects/roman-numeral/haskell) -- [Rot13 in Haskell](/projects/rot13/haskell) -- [Selection Sort in Haskell](/projects/selection-sort/haskell) -- [Transpose Matrix in Haskell](/projects/transpose-matrix/haskell) -- [Zeckendorf in Haskell](/projects/zeckendorf/haskell) \ No newline at end of file diff --git a/docs/languages/haxe/index.md b/docs/languages/haxe/index.md deleted file mode 100644 index 3dd242b2a5..0000000000 --- a/docs/languages/haxe/index.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -date: 2021-08-12 -featured-image: programming-languages.jpg -last-modified: 2025-10-31 -layout: default -tags: -- haxe -title: The Haxe Programming Language -title1: The Haxe Programming -title2: Language ---- - - - -Welcome to the Haxe page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 4 articles: - -- [Baklava in Haxe](/projects/baklava/haxe) -- [Fizz Buzz in Haxe](/projects/fizz-buzz/haxe) -- [Hello World in Haxe](/projects/hello-world/haxe) -- [Merge Sort in Haxe](/projects/merge-sort/haxe) \ No newline at end of file diff --git a/docs/languages/hobbes/index.md b/docs/languages/hobbes/index.md deleted file mode 100644 index 99d3f9eb8a..0000000000 --- a/docs/languages/hobbes/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-11-18 -featured-image: programming-languages.jpg -last-modified: 2025-01-01 -layout: default -tags: -- hobbes -title: The Hobbes Programming Language -title1: The Hobbes -title2: Programming Language ---- - - - -Welcome to the Hobbes page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Hobbes](/projects/baklava/hobbes) -- [Hello World in Hobbes](/projects/hello-world/hobbes) \ No newline at end of file diff --git a/docs/languages/idris/index.md b/docs/languages/idris/index.md deleted file mode 100644 index 55fb4ee812..0000000000 --- a/docs/languages/idris/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-11-21 -featured-image: programming-languages.jpg -last-modified: 2025-01-01 -layout: default -tags: -- idris -title: The Idris Programming Language -title1: The Idris Programming -title2: Language ---- - - - -Welcome to the Idris page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Idris](/projects/baklava/idris) -- [Hello World in Idris](/projects/hello-world/idris) \ No newline at end of file diff --git a/docs/languages/index.md b/docs/languages/index.md deleted file mode 100644 index 41b03e0e7c..0000000000 --- a/docs/languages/index.md +++ /dev/null @@ -1,1345 +0,0 @@ ---- -date: 2018-03-15 -featured-image: programming-languages.jpg -last-modified: 2026-05-23 -layout: default -title: Programming Languages -title1: Programming -title2: Languages ---- - -Welcome to the Languages page! Here, you'll find a list of all of the languages represented in the collection. At this time, there are 158 languages, of which 157 are tested, 1 is untestable, and 1642 code snippets. - -## Language Breakdown - -Here are the percentages for each language in the collection: - -
-Click here to expand or collapse... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ALGOL 608.97%
ALGOL 684.87%
Commodore BASIC4.81%
m44.31%
Euphoria4.24%
Beef4.09%
COBOL3.97%
Pascal3.47%
C++3.13%
C3.08%
Ada3.07%
Rust3.04%
Visual Basic2.86%
PHP2.78%
Java2.73%
x86-642.65%
F#2.55%
AWK2.42%
Mathematica2.14%
Swift2.08%
PowerShell2.02%
TypeScript1.86%
C#1.83%
Tcl1.82%
JavaScript1.82%
Go1.70%
Haskell1.67%
Python1.45%
Kotlin0.96%
Ruby0.96%
Objective-C0.75%
Fortran0.66%
GNU Make0.62%
Brainfuck0.57%
Bash0.52%
Dart0.47%
Unicat0.45%
Octave0.45%
Perl0.44%
Lua0.44%
OCaml0.40%
Elixir0.29%
Julia0.28%
Erlang0.28%
Scala0.28%
TI-BASIC0.27%
R0.26%
Lisp0.26%
Modula-20.24%
Odin0.22%
Groovy0.20%
Fetlang0.19%
Elvish0.17%
Wren0.17%
TeX0.15%
Clojure0.13%
Haxe0.12%
Zig0.12%
CoffeeScript0.12%
Whitespace0.10%
Nim0.09%
V0.09%
LOLCODE0.07%
Rexx0.07%
Mirth0.07%
Red0.07%
Agda0.06%
MoonScript0.06%
D0.06%
Eiffel0.06%
BAIK0.06%
Racket0.06%
Cython0.05%
Dg0.05%
Pyret0.05%
Batch0.05%
Solidity0.04%
Emojicode0.04%
Crystal0.04%
Malbolge0.04%
Factor0.04%
Piet0.04%
Prolog0.04%
Pony0.04%
Boo0.04%
Forth0.04%
Verve0.04%
PureScript0.04%
Granule0.04%
Smalltalk0.04%
Dale0.04%
Vimscript0.04%
Pineapple0.04%
Never0.04%
ArkScript0.04%
Cyclone0.03%
C20.03%
MojiScript0.03%
Ballerina0.03%
Gluon0.03%
Opa0.03%
Wyvern0.03%
Verilog0.03%
Wu0.03%
F*0.03%
Gravity0.03%
Ferret0.03%
Scheme0.03%
Pinecone0.03%
Befunge0.02%
Hobbes0.02%
Kitten0.02%
Lucee0.02%
Formality0.02%
Sather0.02%
C*0.02%
Grain0.02%
Frege0.02%
Discus0.02%
Bracmat0.02%
Lobster0.02%
Eta0.02%
Egison0.02%
Shen0.02%
Owl Lisp0.02%
Goby0.02%
Elena0.02%
Idris0.02%
Lily0.02%
Io0.02%
Orc0.02%
Yoix0.02%
Gerbil0.02%
Gosu0.02%
Koka0.02%
Little0.02%
Terra0.02%
Fennel0.02%
Nit0.02%
Spry0.02%
Chapel0.02%
PicoLisp0.02%
ChaiScript0.02%
Raku0.02%
Solisp0.02%
Janet0.02%
Hack0.02%
Flix0.02%
Latte0.02%
Dusk0.01%
LiveScript0.01%
Golo0.01%
Carp0.01%
Scilab0.01%
Felix0.01%
Ring0.01%
Phix0.01%
Quackery0.01%
-
- -## Language Collections by Letter - -To help you navigate the collection, the following languages are organized alphabetically and grouped by first letter. To go to a particular letter, just click one of the links below. - - - -To return here, just click the « [Return to Top](#language-collections-by-letter) » link. - -### A - -The 'A' collection contains 6 languages, of which 6 are tested, and 143 code snippets. - -- [Ada](/languages/ada) (25 code snippets) -- [Agda](/languages/agda) (2 code snippets) -- [ALGOL 60](/languages/algol60) (37 code snippets) -- [ALGOL 68](/languages/algol68) (38 code snippets) -- [ArkScript](/languages/arkscript) (3 code snippets) -- [AWK](/languages/awk) (38 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### B - -The 'B' collection contains 9 languages, of which 9 are tested, and 79 code snippets. - -- [BAIK](/languages/baik) (2 code snippets) -- [Ballerina](/languages/ballerina) (3 code snippets) -- [Bash](/languages/bash) (15 code snippets) -- [Batch](/languages/batch) (3 code snippets) -- [Beef](/languages/beef) (38 code snippets) -- [Befunge](/languages/befunge) (4 code snippets) -- [Boo](/languages/boo) (4 code snippets) -- [Bracmat](/languages/bracmat) (2 code snippets) -- [Brainfuck](/languages/brainfuck) (8 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### C - -The 'C' collection contains 15 languages, of which 15 are tested, and 228 code snippets. - -- [C](/languages/c) (38 code snippets) -- [C#](/languages/c-sharp) (38 code snippets) -- [C\*](/languages/c-star) (3 code snippets) -- [C++](/languages/c-plus-plus) (38 code snippets) -- [C2](/languages/c2) (2 code snippets) -- [Carp](/languages/carp) (2 code snippets) -- [ChaiScript](/languages/chaiscript) (2 code snippets) -- [Chapel](/languages/chapel) (3 code snippets) -- [Clojure](/languages/clojure) (6 code snippets) -- [COBOL](/languages/cobol) (38 code snippets) -- [CoffeeScript](/languages/coffeescript) (10 code snippets) -- [Commodore BASIC](/languages/commodore-basic) (38 code snippets) -- [Crystal](/languages/crystal) (4 code snippets) -- [Cyclone](/languages/cyclone) (2 code snippets) -- [Cython](/languages/cython) (4 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### D - -The 'D' collection contains 6 languages, of which 6 are tested, and 33 code snippets. - -- [D](/languages/d) (4 code snippets) -- [Dale](/languages/dale) (2 code snippets) -- [Dart](/languages/dart) (17 code snippets) -- [Dg](/languages/dg) (6 code snippets) -- [Discus](/languages/discus) (2 code snippets) -- [Dusk](/languages/dusk) (2 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### E - -The 'E' collection contains 9 languages, of which 9 are tested, and 77 code snippets. - -- [Egison](/languages/egison) (2 code snippets) -- [Eiffel](/languages/eiffel) (3 code snippets) -- [Elena](/languages/elena) (2 code snippets) -- [Elixir](/languages/elixir) (8 code snippets) -- [Elvish](/languages/elvish) (14 code snippets) -- [Emojicode](/languages/emojicode) (2 code snippets) -- [Erlang](/languages/erlang) (6 code snippets) -- [Eta](/languages/eta) (2 code snippets) -- [Euphoria](/languages/euphoria) (38 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### F - -The 'F' collection contains 12 languages, of which 12 are tested, and 74 code snippets. - -- [F#](/languages/f-sharp) (38 code snippets) -- [F\*](/languages/f-star) (2 code snippets) -- [Factor](/languages/factor) (2 code snippets) -- [Felix](/languages/felix) (2 code snippets) -- [Fennel](/languages/fennel) (3 code snippets) -- [Ferret](/languages/ferret) (2 code snippets) -- [Fetlang](/languages/fetlang) (3 code snippets) -- [Flix](/languages/flix) (2 code snippets) -- [Formality](/languages/formality) (2 code snippets) -- [Forth](/languages/forth) (3 code snippets) -- [Fortran](/languages/fortran) (13 code snippets) -- [Frege](/languages/frege) (2 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### G - -The 'G' collection contains 11 languages, of which 11 are tested, and 75 code snippets. - -- [Gerbil](/languages/gerbil) (2 code snippets) -- [Gluon](/languages/gluon) (2 code snippets) -- [GNU Make](/languages/gnu-make) (9 code snippets) -- [Go](/languages/go) (38 code snippets) -- [Goby](/languages/goby) (3 code snippets) -- [Golo](/languages/golo) (2 code snippets) -- [Gosu](/languages/gosu) (3 code snippets) -- [Grain](/languages/grain) (2 code snippets) -- [Granule](/languages/granule) (2 code snippets) -- [Gravity](/languages/gravity) (3 code snippets) -- [Groovy](/languages/groovy) (9 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### H - -The 'H' collection contains 4 languages, of which 4 are tested, and 45 code snippets. - -- [Hack](/languages/hack) (2 code snippets) -- [Haskell](/languages/haskell) (37 code snippets) -- [Haxe](/languages/haxe) (4 code snippets) -- [Hobbes](/languages/hobbes) (2 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### I - -The 'I' collection contains 2 languages, of which 2 are tested, and 5 code snippets. - -- [Idris](/languages/idris) (2 code snippets) -- [Io](/languages/io) (3 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### J - -The 'J' collection contains 4 languages, of which 4 are tested, and 94 code snippets. - -- [Janet](/languages/janet) (3 code snippets) -- [Java](/languages/java) (38 code snippets) -- [JavaScript](/languages/javascript) (38 code snippets) -- [Julia](/languages/julia) (15 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### K - -The 'K' collection contains 3 languages, of which 3 are tested, and 29 code snippets. - -- [Kitten](/languages/kitten) (2 code snippets) -- [Koka](/languages/koka) (2 code snippets) -- [Kotlin](/languages/kotlin) (25 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### L - -The 'L' collection contains 9 languages, of which 9 are tested, and 43 code snippets. - -- [Latte](/languages/latte) (2 code snippets) -- [Lily](/languages/lily) (2 code snippets) -- [Lisp](/languages/lisp) (10 code snippets) -- [Little](/languages/little) (2 code snippets) -- [LiveScript](/languages/livescript) (3 code snippets) -- [Lobster](/languages/lobster) (3 code snippets) -- [LOLCODE](/languages/lolcode) (3 code snippets) -- [Lua](/languages/lua) (16 code snippets) -- [Lucee](/languages/lucee) (2 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### M - -The 'M' collection contains 7 languages, of which 6 are tested, 1 is untestable, and 88 code snippets. - -- [m4](/languages/m4) (36 code snippets) -- [Malbolge](/languages/malbolge) (2 code snippets) -- [Mathematica](/languages/mathematica) (38 code snippets, [untestabled](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/m/mathematica/untestable.yml)) -- [Mirth](/languages/mirth) (2 code snippets) -- [Modula-2](/languages/modula2) (3 code snippets) -- [MojiScript](/languages/mojiscript) (2 code snippets) -- [MoonScript](/languages/moonscript) (5 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### N - -The 'N' collection contains 3 languages, of which 3 are tested, and 12 code snippets. - -- [Never](/languages/never) (3 code snippets) -- [Nim](/languages/nim) (6 code snippets) -- [Nit](/languages/nit) (3 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### O - -The 'O' collection contains 7 languages, of which 7 are tested, and 53 code snippets. - -- [Objective-C](/languages/objective-c) (11 code snippets) -- [OCaml](/languages/ocaml) (13 code snippets) -- [Octave](/languages/octave) (14 code snippets) -- [Odin](/languages/odin) (9 code snippets) -- [Opa](/languages/opa) (2 code snippets) -- [Orc](/languages/orc) (2 code snippets) -- [Owl Lisp](/languages/owl-lisp) (2 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### P - -The 'P' collection contains 14 languages, of which 14 are tested, and 198 code snippets. - -- [Pascal](/languages/pascal) (38 code snippets) -- [Perl](/languages/perl) (21 code snippets) -- [Phix](/languages/phix) (2 code snippets) -- [PHP](/languages/php) (38 code snippets) -- [PicoLisp](/languages/picolisp) (3 code snippets) -- [Piet](/languages/piet) (2 code snippets) -- [Pineapple](/languages/pineapple) (3 code snippets) -- [Pinecone](/languages/pinecone) (3 code snippets) -- [Pony](/languages/pony) (3 code snippets) -- [PowerShell](/languages/powershell) (38 code snippets) -- [Prolog](/languages/prolog) (3 code snippets) -- [PureScript](/languages/purescript) (2 code snippets) -- [Pyret](/languages/pyret) (4 code snippets) -- [Python](/languages/python) (38 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### Q - -The 'Q' collection contains 1 language, of which 1 is tested, and 2 code snippets. - -- [Quackery](/languages/quackery) (2 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### R - -The 'R' collection contains 8 languages, of which 8 are tested, and 109 code snippets. - -- [R](/languages/r) (14 code snippets) -- [Racket](/languages/racket) (4 code snippets) -- [Raku](/languages/raku) (3 code snippets) -- [Red](/languages/red) (4 code snippets) -- [Rexx](/languages/rexx) (6 code snippets) -- [Ring](/languages/ring) (2 code snippets) -- [Ruby](/languages/ruby) (38 code snippets) -- [Rust](/languages/rust) (38 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### S - -The 'S' collection contains 10 languages, of which 10 are tested, and 69 code snippets. - -- [Sather](/languages/sather) (2 code snippets) -- [Scala](/languages/scala) (12 code snippets) -- [Scheme](/languages/scheme) (3 code snippets) -- [Scilab](/languages/scilab) (2 code snippets) -- [Shen](/languages/shen) (2 code snippets) -- [Smalltalk](/languages/smalltalk) (3 code snippets) -- [Solidity](/languages/solidity) (2 code snippets) -- [Solisp](/languages/solisp) (3 code snippets) -- [Spry](/languages/spry) (2 code snippets) -- [Swift](/languages/swift) (38 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### T - -The 'T' collection contains 5 languages, of which 5 are tested, and 95 code snippets. - -- [Tcl](/languages/tcl) (38 code snippets) -- [Terra](/languages/terra) (2 code snippets) -- [TeX](/languages/tex) (3 code snippets) -- [TI-BASIC](/languages/ti-basic) (14 code snippets) -- [TypeScript](/languages/typescript) (38 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### U - -The 'U' collection contains 1 language, of which 1 is tested, and 4 code snippets. - -- [Unicat](/languages/unicat) (4 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### V - -The 'V' collection contains 5 languages, of which 5 are tested, and 54 code snippets. - -- [V](/languages/v) (7 code snippets) -- [Verilog](/languages/verilog) (2 code snippets) -- [Verve](/languages/verve) (3 code snippets) -- [Vimscript](/languages/vimscript) (4 code snippets) -- [Visual Basic](/languages/visual-basic) (38 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### W - -The 'W' collection contains 4 languages, of which 4 are tested, and 20 code snippets. - -- [Whitespace](/languages/whitespace) (4 code snippets) -- [Wren](/languages/wren) (11 code snippets) -- [Wu](/languages/wu) (3 code snippets) -- [Wyvern](/languages/wyvern) (2 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### X - -The 'X' collection contains 1 language, of which 1 is tested, and 7 code snippets. - -- [x86-64](/languages/x86-64) (7 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### Y - -The 'Y' collection contains 1 language, of which 1 is tested, and 2 code snippets. - -- [Yoix](/languages/yoix) (2 code snippets) - -« [Return to Top](#language-collections-by-letter) » - -### Z - -The 'Z' collection contains 1 language, of which 1 is tested, and 4 code snippets. - -- [Zig](/languages/zig) (4 code snippets) - -« [Return to Top](#language-collections-by-letter) » \ No newline at end of file diff --git a/docs/languages/io/index.md b/docs/languages/io/index.md deleted file mode 100644 index be01969f05..0000000000 --- a/docs/languages/io/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2021-05-24 -featured-image: programming-languages.jpg -last-modified: 2025-01-12 -layout: default -tags: -- io -title: The Io Programming Language -title1: The Io Programming -title2: Language ---- - - - -Welcome to the Io page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Io](/projects/baklava/io) -- [Fizz Buzz in Io](/projects/fizz-buzz/io) -- [Hello World in Io](/projects/hello-world/io) \ No newline at end of file diff --git a/docs/languages/janet/index.md b/docs/languages/janet/index.md deleted file mode 100644 index 19431a0940..0000000000 --- a/docs/languages/janet/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2019-10-02 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- janet -title: The Janet Programming Language -title1: The Janet Programming -title2: Language ---- - - - -Welcome to the Janet page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Janet](/projects/baklava/janet) -- [Fizz Buzz in Janet](/projects/fizz-buzz/janet) -- [Hello World in Janet](/projects/hello-world/janet) \ No newline at end of file diff --git a/docs/languages/java/index.md b/docs/languages/java/index.md deleted file mode 100644 index 10ab813ba0..0000000000 --- a/docs/languages/java/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -- Stuart Irwin -date: 2018-03-15 -featured-image: programming-languages.jpg -last-modified: 2026-04-10 -layout: default -tags: -- java -title: The Java Programming Language -title1: The Java Programming -title2: Language ---- - - - -Welcome to the Java page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman -- Stuart Irwin - -## Description - -[Java][1] is a general-purpose language that was designed with -portability in mind. In other words, compile once and run anywhere. Originally called -Oak, Java was developed in 1991 where the syntax was largely influenced by [C][2]/[C++][3]. - -Today, Java exists as one of the most popular languages in the industry with uses -that range from database management to app development. Since its inception, Java has -gone through nine iterations and two companies: [Sun Microsystems][4] and [Oracle Corporation][4], -the current owners. - -As a language, Java has received several [complaints][6]. For instance, many developers -despise Java for its verbosity and performance. That said, the language has many -great features like garbage collection which offset some of these complaints. - -### Features - -- Object-Oriented -- Static Typing - -[1]: https://en.wikipedia.org/wiki/Java_(programming_language) -[2]: https://en.wikipedia.org/wiki/C_(programming_language) -[3]: https://en.wikipedia.org/wiki/C%2B%2B -[4]: https://en.wikipedia.org/wiki/Sun_Microsystems -[5]: https://en.wikipedia.org/wiki/Oracle_Corporation -[6]: https://en.wikipedia.org/wiki/Criticism_of_Java - - -## Articles - -There are 38 articles: - -- [Baklava in Java](/projects/baklava/java) -- [Base64 Encode Decode in Java](/projects/base64-encode-decode/java) -- [Binary Search in Java](/projects/binary-search/java) -- [Bubble Sort in Java](/projects/bubble-sort/java) -- [Capitalize in Java](/projects/capitalize/java) -- [Convex Hull in Java](/projects/convex-hull/java) -- [Depth First Search in Java](/projects/depth-first-search/java) -- [Dijkstra in Java](/projects/dijkstra/java) -- [Duplicate Character Counter in Java](/projects/duplicate-character-counter/java) -- [Even Odd in Java](/projects/even-odd/java) -- [Factorial in Java](/projects/factorial/java) -- [Fibonacci in Java](/projects/fibonacci/java) -- [File Input Output in Java](/projects/file-input-output/java) -- [Fizz Buzz in Java](/projects/fizz-buzz/java) -- [Fraction Math in Java](/projects/fraction-math/java) -- [Hello World in Java](/projects/hello-world/java) -- [Insertion Sort in Java](/projects/insertion-sort/java) -- [Job Sequencing in Java](/projects/job-sequencing/java) -- [Josephus Problem in Java](/projects/josephus-problem/java) -- [Linear Search in Java](/projects/linear-search/java) -- [Longest Common Subsequence in Java](/projects/longest-common-subsequence/java) -- [Longest Palindromic Substring in Java](/projects/longest-palindromic-substring/java) -- [Longest Word in Java](/projects/longest-word/java) -- [Maximum Array Rotation in Java](/projects/maximum-array-rotation/java) -- [Maximum Subarray in Java](/projects/maximum-subarray/java) -- [Merge Sort in Java](/projects/merge-sort/java) -- [Minimum Spanning Tree in Java](/projects/minimum-spanning-tree/java) -- [Palindromic Number in Java](/projects/palindromic-number/java) -- [Prime Number in Java](/projects/prime-number/java) -- [Quick Sort in Java](/projects/quick-sort/java) -- [Quine in Java](/projects/quine/java) -- [Remove All Whitespace in Java](/projects/remove-all-whitespace/java) -- [Reverse String in Java](/projects/reverse-string/java) -- [Roman Numeral in Java](/projects/roman-numeral/java) -- [Rot13 in Java](/projects/rot13/java) -- [Selection Sort in Java](/projects/selection-sort/java) -- [Transpose Matrix in Java](/projects/transpose-matrix/java) -- [Zeckendorf in Java](/projects/zeckendorf/java) \ No newline at end of file diff --git a/docs/languages/javascript/index.md b/docs/languages/javascript/index.md deleted file mode 100644 index 9a9e2cea6e..0000000000 --- a/docs/languages/javascript/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2018-05-06 -featured-image: programming-languages.jpg -last-modified: 2026-05-06 -layout: default -tags: -- javascript -title: The JavaScript Programming Language -title1: The JavaScript -title2: Programming Language ---- - - - -Welcome to the JavaScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in JavaScript](/projects/baklava/javascript) -- [Base64 Encode Decode in JavaScript](/projects/base64-encode-decode/javascript) -- [Binary Search in JavaScript](/projects/binary-search/javascript) -- [Bubble Sort in JavaScript](/projects/bubble-sort/javascript) -- [Capitalize in JavaScript](/projects/capitalize/javascript) -- [Convex Hull in JavaScript](/projects/convex-hull/javascript) -- [Depth First Search in JavaScript](/projects/depth-first-search/javascript) -- [Dijkstra in JavaScript](/projects/dijkstra/javascript) -- [Duplicate Character Counter in JavaScript](/projects/duplicate-character-counter/javascript) -- [Even Odd in JavaScript](/projects/even-odd/javascript) -- [Factorial in JavaScript](/projects/factorial/javascript) -- [Fibonacci in JavaScript](/projects/fibonacci/javascript) -- [File Input Output in JavaScript](/projects/file-input-output/javascript) -- [Fizz Buzz in JavaScript](/projects/fizz-buzz/javascript) -- [Fraction Math in JavaScript](/projects/fraction-math/javascript) -- [Hello World in JavaScript](/projects/hello-world/javascript) -- [Insertion Sort in JavaScript](/projects/insertion-sort/javascript) -- [Job Sequencing in JavaScript](/projects/job-sequencing/javascript) -- [Josephus Problem in JavaScript](/projects/josephus-problem/javascript) -- [Linear Search in JavaScript](/projects/linear-search/javascript) -- [Longest Common Subsequence in JavaScript](/projects/longest-common-subsequence/javascript) -- [Longest Palindromic Substring in JavaScript](/projects/longest-palindromic-substring/javascript) -- [Longest Word in JavaScript](/projects/longest-word/javascript) -- [Maximum Array Rotation in JavaScript](/projects/maximum-array-rotation/javascript) -- [Maximum Subarray in JavaScript](/projects/maximum-subarray/javascript) -- [Merge Sort in JavaScript](/projects/merge-sort/javascript) -- [Minimum Spanning Tree in JavaScript](/projects/minimum-spanning-tree/javascript) -- [Palindromic Number in JavaScript](/projects/palindromic-number/javascript) -- [Prime Number in JavaScript](/projects/prime-number/javascript) -- [Quick Sort in JavaScript](/projects/quick-sort/javascript) -- [Quine in JavaScript](/projects/quine/javascript) -- [Remove All Whitespace in JavaScript](/projects/remove-all-whitespace/javascript) -- [Reverse String in JavaScript](/projects/reverse-string/javascript) -- [Roman Numeral in JavaScript](/projects/roman-numeral/javascript) -- [Rot13 in JavaScript](/projects/rot13/javascript) -- [Selection Sort in JavaScript](/projects/selection-sort/javascript) -- [Transpose Matrix in JavaScript](/projects/transpose-matrix/javascript) -- [Zeckendorf in JavaScript](/projects/zeckendorf/javascript) \ No newline at end of file diff --git a/docs/languages/julia/index.md b/docs/languages/julia/index.md deleted file mode 100644 index c0d57eed8e..0000000000 --- a/docs/languages/julia/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-11 -featured-image: programming-languages.jpg -last-modified: 2025-02-13 -layout: default -tags: -- julia -title: The Julia Programming Language -title1: The Julia Programming -title2: Language ---- - - - -Welcome to the Julia page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Despite being a relatively new language, Julia has a [Wikipedia[1] page. -As a result, I won't have to dig too much to learn about the language. - -At any rate, Julia is a computational science language which fills a -niche similar to [Python][2] and [R][3]. In fact, like Python, Julia can be -used for general-purpose programming. - -One of Julia's interesting features is multiple dispatch, something that -is lacking in Python. Roughly speaking, multiple dispatch allows a user -to define multiple functions with the same name but different combinations -of arguments. - -In addition, Julia is capable of calling [C][4] and Python functions directly. -Personally, I think that's a fun little feature considering Julia is -compiled at runtime. So, it gets C-like performance as well, perfect for -numerical analysis. - -Finally, Julia has metaprogramming features, so the language can be -modified as needed by the user. If Julia ever takes off, we can probably -expect several different dialects of it to emerge. - -[1]: https://en.wikipedia.org/wiki/Julia_(programming_language) -[2]: https://en.wikipedia.org/wiki/Python_(programming_language) -[3]: https://en.wikipedia.org/wiki/R_(programming_language) -[4]: https://en.wikipedia.org/wiki/C_(programming_language) - - -## Articles - -There are 15 articles: - -- [Baklava in Julia](/projects/baklava/julia) -- [Bubble Sort in Julia](/projects/bubble-sort/julia) -- [Capitalize in Julia](/projects/capitalize/julia) -- [Even Odd in Julia](/projects/even-odd/julia) -- [Factorial in Julia](/projects/factorial/julia) -- [Fibonacci in Julia](/projects/fibonacci/julia) -- [File Input Output in Julia](/projects/file-input-output/julia) -- [Fizz Buzz in Julia](/projects/fizz-buzz/julia) -- [Hello World in Julia](/projects/hello-world/julia) -- [Longest Word in Julia](/projects/longest-word/julia) -- [Palindromic Number in Julia](/projects/palindromic-number/julia) -- [Prime Number in Julia](/projects/prime-number/julia) -- [Remove All Whitespace in Julia](/projects/remove-all-whitespace/julia) -- [Reverse String in Julia](/projects/reverse-string/julia) -- [Selection Sort in Julia](/projects/selection-sort/julia) \ No newline at end of file diff --git a/docs/languages/kitten/index.md b/docs/languages/kitten/index.md deleted file mode 100644 index 5f375eb90c..0000000000 --- a/docs/languages/kitten/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-05-03 -featured-image: programming-languages.jpg -last-modified: 2024-12-31 -layout: default -tags: -- kitten -title: The Kitten Programming Language -title1: The Kitten -title2: Programming Language ---- - - - -Welcome to the Kitten page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Kitten](/projects/baklava/kitten) -- [Hello World in Kitten](/projects/hello-world/kitten) \ No newline at end of file diff --git a/docs/languages/koka/index.md b/docs/languages/koka/index.md deleted file mode 100644 index fe0d017c25..0000000000 --- a/docs/languages/koka/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-11-09 -featured-image: programming-languages.jpg -last-modified: 2024-12-31 -layout: default -tags: -- koka -title: The Koka Programming Language -title1: The Koka Programming -title2: Language ---- - - - -Welcome to the Koka page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Koka is a function-oriented programming language created by Microsoft researcher -[Daan Leijen][1]. Leijan created Koka to separate pure values from side-effecting -computations. According to [Wikipedia][2], a function or expression is said to have a -side effect if it modifies some state outside of its local environment. - -In addition, Koka has many features that help programmers easily change their data -types and code organization correctly while having a small language core with a -familiar JavaScript-like syntax. - -Fun Fact: the word 'Koka' (or 効果) means "effect" or "effective" in Japanese. - -[1]: https://www.microsoft.com/en-us/research/people/daan/ -[2]: https://en.wikipedia.org/wiki/Side_effect_(computer_science) - - -## Articles - -There are 2 articles: - -- [Baklava in Koka](/projects/baklava/koka) -- [Hello World in Koka](/projects/hello-world/koka) \ No newline at end of file diff --git a/docs/languages/kotlin/index.md b/docs/languages/kotlin/index.md deleted file mode 100644 index e6a57e64ba..0000000000 --- a/docs/languages/kotlin/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-10 -featured-image: programming-languages.jpg -last-modified: 2025-10-07 -layout: default -tags: -- kotlin -title: The Kotlin Programming Language -title1: The Kotlin -title2: Programming Language ---- - - - -Welcome to the Kotlin page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Since Kotlin is a bit more popular than most of the newer languages, it -actually has a Wikipedia page. So, we'll use that to learn more. - -According to [Wikipedia][1], Kotlin is a programming language that runs on -the [Java Virtual Machine][2]. In other words, Kotlin compiles down to Java -bytecode. In fact, developers have the option to decide which version -of Java bytecode they want. In addition to the JVM, Kotlin can also -compile down to JavaScript. - -In terms of features, Kotlin offers an aggressive form of type inference. -In other words, the language supports static type checking on implicit -types. Of course, the benefit is a far less verbose syntax than Java. - -Of course, I think my favorite feature is extension methods. In Kotlin, -we can take a class that already exists and tack on our own methods -without creating an extension class. For instance, Wikipedia shares -the following snippet: - -```kotlin -fun String.lastChar(): Char = this.get(this.length - 1) -``` - -In this example, the lastChar method is added to the String class. How cool is that? - -[1]: https://en.wikipedia.org/wiki/Kotlin_(programming_language) -[2]: https://en.wikipedia.org/wiki/Java_virtual_machine - - -## Articles - -There are 25 articles: - -- [Baklava in Kotlin](/projects/baklava/kotlin) -- [Binary Search in Kotlin](/projects/binary-search/kotlin) -- [Bubble Sort in Kotlin](/projects/bubble-sort/kotlin) -- [Capitalize in Kotlin](/projects/capitalize/kotlin) -- [Duplicate Character Counter in Kotlin](/projects/duplicate-character-counter/kotlin) -- [Even Odd in Kotlin](/projects/even-odd/kotlin) -- [Factorial in Kotlin](/projects/factorial/kotlin) -- [Fibonacci in Kotlin](/projects/fibonacci/kotlin) -- [File Input Output in Kotlin](/projects/file-input-output/kotlin) -- [Fizz Buzz in Kotlin](/projects/fizz-buzz/kotlin) -- [Hello World in Kotlin](/projects/hello-world/kotlin) -- [Insertion Sort in Kotlin](/projects/insertion-sort/kotlin) -- [Job Sequencing in Kotlin](/projects/job-sequencing/kotlin) -- [Linear Search in Kotlin](/projects/linear-search/kotlin) -- [Longest Common Subsequence in Kotlin](/projects/longest-common-subsequence/kotlin) -- [Longest Word in Kotlin](/projects/longest-word/kotlin) -- [Merge Sort in Kotlin](/projects/merge-sort/kotlin) -- [Palindromic Number in Kotlin](/projects/palindromic-number/kotlin) -- [Prime Number in Kotlin](/projects/prime-number/kotlin) -- [Quick Sort in Kotlin](/projects/quick-sort/kotlin) -- [Quine in Kotlin](/projects/quine/kotlin) -- [Remove All Whitespace in Kotlin](/projects/remove-all-whitespace/kotlin) -- [Reverse String in Kotlin](/projects/reverse-string/kotlin) -- [Rot13 in Kotlin](/projects/rot13/kotlin) -- [Selection Sort in Kotlin](/projects/selection-sort/kotlin) \ No newline at end of file diff --git a/docs/languages/latte/index.md b/docs/languages/latte/index.md deleted file mode 100644 index 00797c10f2..0000000000 --- a/docs/languages/latte/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2021-05-24 -featured-image: programming-languages.jpg -last-modified: 2024-12-30 -layout: default -tags: -- latte -title: The Latte Programming Language -title1: The Latte Programming -title2: Language ---- - - - -Welcome to the Latte page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Latte](/projects/baklava/latte) -- [Hello World in Latte](/projects/hello-world/latte) \ No newline at end of file diff --git a/docs/languages/lily/index.md b/docs/languages/lily/index.md deleted file mode 100644 index 2f186ccf8e..0000000000 --- a/docs/languages/lily/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-04-22 -featured-image: programming-languages.jpg -last-modified: 2024-12-27 -layout: default -tags: -- lily -title: The Lily Programming Language -title1: The Lily Programming -title2: Language ---- - - - -Welcome to the Lily page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Lily](/projects/baklava/lily) -- [Hello World in Lily](/projects/hello-world/lily) \ No newline at end of file diff --git a/docs/languages/lisp/index.md b/docs/languages/lisp/index.md deleted file mode 100644 index c05190de79..0000000000 --- a/docs/languages/lisp/index.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-08 -featured-image: programming-languages.jpg -last-modified: 2023-05-15 -layout: default -tags: -- lisp -title: The Lisp Programming Language -title1: The Lisp Programming -title2: Language ---- - - - -Welcome to the Lisp page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -According to [Wikipedia][1], Lisp is actually a family of languages. In other -words, Lisp has many dialects. For the purposes of this exercise, we'll be -using Common Lisp. - -That said, let's talk about Lisp in general. As it turns out, Lisp, a language -developed in 1958, is the second oldest high-level programming language. The -only older language is [Fortran][2]. Since its inception, the language has split -into several dialects. Perhaps some of the most notable dialects are Scheme, -Common Lisp, and Clojure. - -## Features - -Lisp includes several interesting features that are more fun to show rather -than tell. - -### Expressions - -In terms of features, Lisp differs wildly from the languages we've already covered. -For example, all data in Lisp is represented with expressions, in particular, symbolic -expressions. These expressions are written in prefix notation: - -```lisp -(+ 3 6 11) -``` - -In infix notation, the above expression reads: - -```lisp -(3 + 6 + 11) -``` - -So, the expected result is 20. - -### Lists - -In addition, Lisp is heavily list based. In fact, Lisp is short for List Processor, -so it should be no surprise that lists play an important role in the language. - -Implementing a list in Lisp is rather simple: - -```lisp -(list 1 5 2 1) -``` - -Here. we've generated a list of four elements: 1, 5, 2, and 1. In fact, we can even -nest lists using the prefix notation: - -```lisp -(list 1 (list 5 2) 1) -``` - -The resulting list would look like the following: - -```lisp -(1 (5 2) 1) -``` - -Keep this syntax in mind when we get to functions. - -### Lambda Expressions - -Have you ever played with lambda expressions in other languages like Java or Python? -Well, Lisp has them too: - -```lisp -(lambda (arg) (* arg 2)) -``` - -In this lambda expression, we simply multiply an argument by 2. If we wanted to use the -expression, we would have to pass a value to it: - -```lisp -((lambda (arg) (* arg 2)) 10) -``` - -If this is confusing, remember that everything is in prefix notation, so this code might -look something like the following in a language like Python: - -```lisp -foo = lambda n: n * 2 -foo(10) -``` - -Notice, however, that we have a named function in the Python example and an anonymous -function in the Lisp example. Don't worry though. Lisp has named functions as well. - -### Functions - -In Lisp, a named function is essentially a lambda expression that is stored in a symbol: - -```lisp -(defun foo (arg) (* arg 2)) -``` - -In this example, we've created the exact same lambda expression, but we've stored it in -a function called foo. We can then call foo from anywhere in our program: - -```lisp -(foo 10) -``` - -How cool is that? I think I'm starting to like Lisp. Of course, we haven't even gotten to -implement Hello World in Lisp, so we should probably get to that. - -[1]: https://en.wikipedia.org/wiki/Lisp_(programming_language) -[2]: https://en.wikipedia.org/wiki/Fortran - - -## Articles - -There are 10 articles: - -- [Baklava in Lisp](/projects/baklava/lisp) -- [Capitalize in Lisp](/projects/capitalize/lisp) -- [Even Odd in Lisp](/projects/even-odd/lisp) -- [Factorial in Lisp](/projects/factorial/lisp) -- [Fibonacci in Lisp](/projects/fibonacci/lisp) -- [Fizz Buzz in Lisp](/projects/fizz-buzz/lisp) -- [Hello World in Lisp](/projects/hello-world/lisp) -- [Prime Number in Lisp](/projects/prime-number/lisp) -- [Quick Sort in Lisp](/projects/quick-sort/lisp) -- [Reverse String in Lisp](/projects/reverse-string/lisp) \ No newline at end of file diff --git a/docs/languages/little/index.md b/docs/languages/little/index.md deleted file mode 100644 index ed9380fadb..0000000000 --- a/docs/languages/little/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-08-23 -featured-image: programming-languages.jpg -last-modified: 2024-12-27 -layout: default -tags: -- little -title: The Little Programming Language -title1: The Little -title2: Programming Language ---- - - - -Welcome to the Little page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Little](/projects/baklava/little) -- [Hello World in Little](/projects/hello-world/little) \ No newline at end of file diff --git a/docs/languages/livescript/index.md b/docs/languages/livescript/index.md deleted file mode 100644 index 03020ae46d..0000000000 --- a/docs/languages/livescript/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2023-08-14 -featured-image: programming-languages.jpg -last-modified: 2025-10-29 -layout: default -tags: -- livescript -title: The LiveScript Programming Language -title1: The LiveScript -title2: Programming Language ---- - - - -Welcome to the LiveScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in LiveScript](/projects/baklava/livescript) -- [Fizz Buzz in LiveScript](/projects/fizz-buzz/livescript) -- [Hello World in LiveScript](/projects/hello-world/livescript) \ No newline at end of file diff --git a/docs/languages/lobster/index.md b/docs/languages/lobster/index.md deleted file mode 100644 index 767a90a253..0000000000 --- a/docs/languages/lobster/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2023-08-14 -featured-image: programming-languages.jpg -last-modified: 2025-10-24 -layout: default -tags: -- lobster -title: The Lobster Programming Language -title1: The Lobster -title2: Programming Language ---- - - - -Welcome to the Lobster page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Lobster](/projects/baklava/lobster) -- [Fizz Buzz in Lobster](/projects/fizz-buzz/lobster) -- [Hello World in Lobster](/projects/hello-world/lobster) \ No newline at end of file diff --git a/docs/languages/lolcode/index.md b/docs/languages/lolcode/index.md deleted file mode 100644 index 0d9566c6a1..0000000000 --- a/docs/languages/lolcode/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-05-11 -featured-image: programming-languages.jpg -last-modified: 2024-12-27 -layout: default -tags: -- lolcode -title: The LOLCODE Programming Language -title1: The LOLCODE -title2: Programming Language ---- - - - -Welcome to the LOLCODE page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in LOLCODE](/projects/baklava/lolcode) -- [Fizz Buzz in LOLCODE](/projects/fizz-buzz/lolcode) -- [Hello World in LOLCODE](/projects/hello-world/lolcode) \ No newline at end of file diff --git a/docs/languages/lua/index.md b/docs/languages/lua/index.md deleted file mode 100644 index 2fd0186684..0000000000 --- a/docs/languages/lua/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-19 -featured-image: programming-languages.jpg -last-modified: 2025-10-29 -layout: default -tags: -- lua -title: The Lua Programming Language -title1: The Lua Programming -title2: Language ---- - - - -Welcome to the Lua page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -As usual, I'm not super familiar with the language we're working with today, -so let's consult [Wikipedia][1]. - -Like many of the languages we've touched on already, Lua is a scripting language. -Unlike many of the scripting languages we've covered, Lua is extremely lightweight, -so it shines in embedded applications. - -Perhaps the oddest featured of Lua is the fact that it's compiled, but this is -not readily apparent to the user. That's because the compilation occurs at -run-time where the bytecode is then interpreted. However, it's possible to -precompile Lua to save a few CPU cycles during runtime. - -Because Lua is built for embedded applications, it has its own C API which can -be used to write Lua code in C. Personally, I don't find the API to be that -user-friendly, but it does eliminate the need for reference management, so I -can't really complain. - -Due to its lightweight and embedded nature, Lua has also found a home in the -gaming community. How have I never used it? - -[1]: https://en.wikipedia.org/wiki/Lua_(programming_language) - - -## Articles - -There are 16 articles: - -- [Baklava in Lua](/projects/baklava/lua) -- [Bubble Sort in Lua](/projects/bubble-sort/lua) -- [Capitalize in Lua](/projects/capitalize/lua) -- [Duplicate Character Counter in Lua](/projects/duplicate-character-counter/lua) -- [Even Odd in Lua](/projects/even-odd/lua) -- [Factorial in Lua](/projects/factorial/lua) -- [Fibonacci in Lua](/projects/fibonacci/lua) -- [File Input Output in Lua](/projects/file-input-output/lua) -- [Fizz Buzz in Lua](/projects/fizz-buzz/lua) -- [Hello World in Lua](/projects/hello-world/lua) -- [Linear Search in Lua](/projects/linear-search/lua) -- [Longest Word in Lua](/projects/longest-word/lua) -- [Prime Number in Lua](/projects/prime-number/lua) -- [Reverse String in Lua](/projects/reverse-string/lua) -- [Roman Numeral in Lua](/projects/roman-numeral/lua) -- [Rot13 in Lua](/projects/rot13/lua) \ No newline at end of file diff --git a/docs/languages/lucee/index.md b/docs/languages/lucee/index.md deleted file mode 100644 index ca4149d54c..0000000000 --- a/docs/languages/lucee/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2019-10-02 -featured-image: programming-languages.jpg -last-modified: 2024-12-27 -layout: default -tags: -- lucee -title: The Lucee Programming Language -title1: The Lucee Programming -title2: Language ---- - - - -Welcome to the Lucee page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Lucee](/projects/baklava/lucee) -- [Hello World in Lucee](/projects/hello-world/lucee) \ No newline at end of file diff --git a/docs/languages/m4/index.md b/docs/languages/m4/index.md deleted file mode 100644 index 621a8fa4a6..0000000000 --- a/docs/languages/m4/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -date: 2025-08-04 -featured-image: programming-languages.jpg -last-modified: 2026-03-07 -layout: default -tags: -- m4 -title: The m4 Programming Language -title1: The m4 Programming -title2: Language ---- - - - -Welcome to the m4 page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 36 articles: - -- [Baklava in m4](/projects/baklava/m4) -- [Binary Search in m4](/projects/binary-search/m4) -- [Bubble Sort in m4](/projects/bubble-sort/m4) -- [Capitalize in m4](/projects/capitalize/m4) -- [Convex Hull in m4](/projects/convex-hull/m4) -- [Depth First Search in m4](/projects/depth-first-search/m4) -- [Dijkstra in m4](/projects/dijkstra/m4) -- [Duplicate Character Counter in m4](/projects/duplicate-character-counter/m4) -- [Even Odd in m4](/projects/even-odd/m4) -- [Factorial in m4](/projects/factorial/m4) -- [Fibonacci in m4](/projects/fibonacci/m4) -- [Fizz Buzz in m4](/projects/fizz-buzz/m4) -- [Fraction Math in m4](/projects/fraction-math/m4) -- [Hello World in m4](/projects/hello-world/m4) -- [Insertion Sort in m4](/projects/insertion-sort/m4) -- [Job Sequencing in m4](/projects/job-sequencing/m4) -- [Josephus Problem in m4](/projects/josephus-problem/m4) -- [Linear Search in m4](/projects/linear-search/m4) -- [Longest Common Subsequence in m4](/projects/longest-common-subsequence/m4) -- [Longest Palindromic Substring in m4](/projects/longest-palindromic-substring/m4) -- [Longest Word in m4](/projects/longest-word/m4) -- [Maximum Array Rotation in m4](/projects/maximum-array-rotation/m4) -- [Maximum Subarray in m4](/projects/maximum-subarray/m4) -- [Merge Sort in m4](/projects/merge-sort/m4) -- [Minimum Spanning Tree in m4](/projects/minimum-spanning-tree/m4) -- [Palindromic Number in m4](/projects/palindromic-number/m4) -- [Prime Number in m4](/projects/prime-number/m4) -- [Quick Sort in m4](/projects/quick-sort/m4) -- [Quine in m4](/projects/quine/m4) -- [Remove All Whitespace in m4](/projects/remove-all-whitespace/m4) -- [Reverse String in m4](/projects/reverse-string/m4) -- [Roman Numeral in m4](/projects/roman-numeral/m4) -- [Rot13 in m4](/projects/rot13/m4) -- [Selection Sort in m4](/projects/selection-sort/m4) -- [Transpose Matrix in m4](/projects/transpose-matrix/m4) -- [Zeckendorf in m4](/projects/zeckendorf/m4) \ No newline at end of file diff --git a/docs/languages/malbolge/index.md b/docs/languages/malbolge/index.md deleted file mode 100644 index 2f45940158..0000000000 --- a/docs/languages/malbolge/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2024-10-23 -featured-image: programming-languages.jpg -last-modified: 2024-10-23 -layout: default -tags: -- malbolge -title: The Malbolge Programming Language -title1: The Malbolge -title2: Programming Language ---- - - - -Welcome to the Malbolge page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Malbolge](/projects/baklava/malbolge) -- [Hello World in Malbolge](/projects/hello-world/malbolge) \ No newline at end of file diff --git a/docs/languages/mathematica/index.md b/docs/languages/mathematica/index.md deleted file mode 100644 index 6a6ba05643..0000000000 --- a/docs/languages/mathematica/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2021-05-25 -featured-image: programming-languages.jpg -last-modified: 2026-04-30 -layout: default -tags: -- mathematica -title: The Mathematica Programming Language -title1: The Mathematica -title2: Programming Language ---- - - - -Welcome to the Mathematica page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in Mathematica](/projects/baklava/mathematica) -- [Base64 Encode Decode in Mathematica](/projects/base64-encode-decode/mathematica) -- [Binary Search in Mathematica](/projects/binary-search/mathematica) -- [Bubble Sort in Mathematica](/projects/bubble-sort/mathematica) -- [Capitalize in Mathematica](/projects/capitalize/mathematica) -- [Convex Hull in Mathematica](/projects/convex-hull/mathematica) -- [Depth First Search in Mathematica](/projects/depth-first-search/mathematica) -- [Dijkstra in Mathematica](/projects/dijkstra/mathematica) -- [Duplicate Character Counter in Mathematica](/projects/duplicate-character-counter/mathematica) -- [Even Odd in Mathematica](/projects/even-odd/mathematica) -- [Factorial in Mathematica](/projects/factorial/mathematica) -- [Fibonacci in Mathematica](/projects/fibonacci/mathematica) -- [File Input Output in Mathematica](/projects/file-input-output/mathematica) -- [Fizz Buzz in Mathematica](/projects/fizz-buzz/mathematica) -- [Fraction Math in Mathematica](/projects/fraction-math/mathematica) -- [Hello World in Mathematica](/projects/hello-world/mathematica) -- [Insertion Sort in Mathematica](/projects/insertion-sort/mathematica) -- [Job Sequencing in Mathematica](/projects/job-sequencing/mathematica) -- [Josephus Problem in Mathematica](/projects/josephus-problem/mathematica) -- [Linear Search in Mathematica](/projects/linear-search/mathematica) -- [Longest Common Subsequence in Mathematica](/projects/longest-common-subsequence/mathematica) -- [Longest Palindromic Substring in Mathematica](/projects/longest-palindromic-substring/mathematica) -- [Longest Word in Mathematica](/projects/longest-word/mathematica) -- [Maximum Array Rotation in Mathematica](/projects/maximum-array-rotation/mathematica) -- [Maximum Subarray in Mathematica](/projects/maximum-subarray/mathematica) -- [Merge Sort in Mathematica](/projects/merge-sort/mathematica) -- [Minimum Spanning Tree in Mathematica](/projects/minimum-spanning-tree/mathematica) -- [Palindromic Number in Mathematica](/projects/palindromic-number/mathematica) -- [Prime Number in Mathematica](/projects/prime-number/mathematica) -- [Quick Sort in Mathematica](/projects/quick-sort/mathematica) -- [Quine in Mathematica](/projects/quine/mathematica) -- [Remove All Whitespace in Mathematica](/projects/remove-all-whitespace/mathematica) -- [Reverse String in Mathematica](/projects/reverse-string/mathematica) -- [Roman Numeral in Mathematica](/projects/roman-numeral/mathematica) -- [Rot13 in Mathematica](/projects/rot13/mathematica) -- [Selection Sort in Mathematica](/projects/selection-sort/mathematica) -- [Transpose Matrix in Mathematica](/projects/transpose-matrix/mathematica) -- [Zeckendorf in Mathematica](/projects/zeckendorf/mathematica) \ No newline at end of file diff --git a/docs/languages/mirth/index.md b/docs/languages/mirth/index.md deleted file mode 100644 index a2866c2d24..0000000000 --- a/docs/languages/mirth/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-11-18 -featured-image: programming-languages.jpg -last-modified: 2025-01-25 -layout: default -tags: -- mirth -title: The Mirth Programming Language -title1: The Mirth Programming -title2: Language ---- - - - -Welcome to the Mirth page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Mirth](/projects/baklava/mirth) -- [Hello World in Mirth](/projects/hello-world/mirth) \ No newline at end of file diff --git a/docs/languages/modula2/index.md b/docs/languages/modula2/index.md deleted file mode 100644 index ac47af6cef..0000000000 --- a/docs/languages/modula2/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2023-08-14 -featured-image: programming-languages.jpg -last-modified: 2026-05-07 -layout: default -tags: -- modula2 -title: The Modula-2 Programming Language -title1: The Modula-2 -title2: Programming Language ---- - - - -Welcome to the Modula-2 page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Modula-2](/projects/baklava/modula2) -- [Fraction Math in Modula-2](/projects/fraction-math/modula2) -- [Hello World in Modula-2](/projects/hello-world/modula2) \ No newline at end of file diff --git a/docs/languages/mojiscript/index.md b/docs/languages/mojiscript/index.md deleted file mode 100644 index 2a3eca9b8c..0000000000 --- a/docs/languages/mojiscript/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-10-15 -featured-image: programming-languages.jpg -last-modified: 2024-12-30 -layout: default -tags: -- mojiscript -title: The MojiScript Programming Language -title1: The MojiScript -title2: Programming Language ---- - - - -Welcome to the MojiScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in MojiScript](/projects/baklava/mojiscript) -- [Hello World in MojiScript](/projects/hello-world/mojiscript) \ No newline at end of file diff --git a/docs/languages/moonscript/index.md b/docs/languages/moonscript/index.md deleted file mode 100644 index 44732becaa..0000000000 --- a/docs/languages/moonscript/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-08-28 -featured-image: programming-languages.jpg -last-modified: 2025-02-17 -layout: default -tags: -- moonscript -title: The MoonScript Programming Language -title1: The MoonScript -title2: Programming Language ---- - - - -Welcome to the MoonScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -According to [MoonScript.org][1], MoonScript is a dynamic scripting language that -compiles into Lua. What is Lua? Lua is a powerful, efficient, lightweight, -embeddable scripting language. It supports procedural programming, object-oriented -programming, functional programming, data-driven programming, and data description. - -Back to MoonScript, it gives you the full power of Lua while providing a clean -easy syntax without the keyword noise typically seen in a Lua script. MoonScript -can either be compiled into Lua, or it can be dynamically compiled and run using -the moonloader. - -How did MoonScript start you may ask? Well, its author [Leaf Corcoran][2] built -MoonScript, started building games with MoonScript, added them to [itch.io][3], an -online platform for indie games which is also built with MoonScript, then -generalized the code base to a general purpose web framework with both -MoonScript and Lua APIs called Lapis. - -[1]: https://moonscript.org/ -[2]: https://www.gamedeveloper.com/business/q-a-itch-io-interview-with-leaf-corcoran -[3]: https://itch.io/ - - -## Articles - -There are 5 articles: - -- [Baklava in MoonScript](/projects/baklava/moonscript) -- [Fibonacci in MoonScript](/projects/fibonacci/moonscript) -- [Fizz Buzz in MoonScript](/projects/fizz-buzz/moonscript) -- [Hello World in MoonScript](/projects/hello-world/moonscript) -- [Reverse String in MoonScript](/projects/reverse-string/moonscript) \ No newline at end of file diff --git a/docs/languages/never/index.md b/docs/languages/never/index.md deleted file mode 100644 index bbefc4a995..0000000000 --- a/docs/languages/never/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-09-20 -featured-image: programming-languages.jpg -last-modified: 2024-12-23 -layout: default -tags: -- never -title: The Never Programming Language -title1: The Never Programming -title2: Language ---- - - - -Welcome to the Never page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Never](/projects/baklava/never) -- [Hello World in Never](/projects/hello-world/never) -- [Reverse String in Never](/projects/reverse-string/never) \ No newline at end of file diff --git a/docs/languages/nim/index.md b/docs/languages/nim/index.md deleted file mode 100644 index 37d5583ed0..0000000000 --- a/docs/languages/nim/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -date: 2019-10-16 -featured-image: programming-languages.jpg -last-modified: 2025-10-29 -layout: default -tags: -- nim -title: The Nim Programming Language -title1: The Nim Programming -title2: Language ---- - - - -Welcome to the Nim page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 6 articles: - -- [Baklava in Nim](/projects/baklava/nim) -- [Factorial in Nim](/projects/factorial/nim) -- [Fibonacci in Nim](/projects/fibonacci/nim) -- [Fizz Buzz in Nim](/projects/fizz-buzz/nim) -- [Hello World in Nim](/projects/hello-world/nim) -- [Reverse String in Nim](/projects/reverse-string/nim) \ No newline at end of file diff --git a/docs/languages/nit/index.md b/docs/languages/nit/index.md deleted file mode 100644 index 92e3cdd842..0000000000 --- a/docs/languages/nit/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2021-05-25 -featured-image: programming-languages.jpg -last-modified: 2025-10-30 -layout: default -tags: -- nit -title: The Nit Programming Language -title1: The Nit Programming -title2: Language ---- - - - -Welcome to the Nit page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Nit](/projects/baklava/nit) -- [Hello World in Nit](/projects/hello-world/nit) -- [Reverse String in Nit](/projects/reverse-string/nit) \ No newline at end of file diff --git a/docs/languages/objective-c/index.md b/docs/languages/objective-c/index.md deleted file mode 100644 index 6f76ce9405..0000000000 --- a/docs/languages/objective-c/index.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -date: 2018-03-21 -featured-image: programming-languages.jpg -last-modified: 2026-04-30 -layout: default -tags: -- objective-c -title: The Objective-C Programming Language -title1: The Objective-C -title2: Programming Language ---- - - - -Welcome to the Objective-C page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 11 articles: - -- [Baklava in Objective-C](/projects/baklava/objective-c) -- [Capitalize in Objective-C](/projects/capitalize/objective-c) -- [Even Odd in Objective-C](/projects/even-odd/objective-c) -- [Factorial in Objective-C](/projects/factorial/objective-c) -- [Fibonacci in Objective-C](/projects/fibonacci/objective-c) -- [File Input Output in Objective-C](/projects/file-input-output/objective-c) -- [Fizz Buzz in Objective-C](/projects/fizz-buzz/objective-c) -- [Hello World in Objective-C](/projects/hello-world/objective-c) -- [Merge Sort in Objective-C](/projects/merge-sort/objective-c) -- [Quick Sort in Objective-C](/projects/quick-sort/objective-c) -- [Reverse String in Objective-C](/projects/reverse-string/objective-c) \ No newline at end of file diff --git a/docs/languages/ocaml/index.md b/docs/languages/ocaml/index.md deleted file mode 100644 index 1c701f9977..0000000000 --- a/docs/languages/ocaml/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -date: 2018-10-17 -featured-image: programming-languages.jpg -last-modified: 2026-05-23 -layout: default -tags: -- ocaml -title: The OCaml Programming Language -title1: The OCaml Programming -title2: Language ---- - - - -Welcome to the OCaml page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 13 articles: - -- [Baklava in OCaml](/projects/baklava/ocaml) -- [Capitalize in OCaml](/projects/capitalize/ocaml) -- [Duplicate Character Counter in OCaml](/projects/duplicate-character-counter/ocaml) -- [Factorial in OCaml](/projects/factorial/ocaml) -- [Fibonacci in OCaml](/projects/fibonacci/ocaml) -- [File Input Output in OCaml](/projects/file-input-output/ocaml) -- [Fizz Buzz in OCaml](/projects/fizz-buzz/ocaml) -- [Hello World in OCaml](/projects/hello-world/ocaml) -- [Linear Search in OCaml](/projects/linear-search/ocaml) -- [Merge Sort in OCaml](/projects/merge-sort/ocaml) -- [Palindromic Number in OCaml](/projects/palindromic-number/ocaml) -- [Prime Number in OCaml](/projects/prime-number/ocaml) -- [Reverse String in OCaml](/projects/reverse-string/ocaml) \ No newline at end of file diff --git a/docs/languages/octave/index.md b/docs/languages/octave/index.md deleted file mode 100644 index 49df72b5d6..0000000000 --- a/docs/languages/octave/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- rzuckerm -date: 2018-04-11 -featured-image: programming-languages.jpg -last-modified: 2024-12-23 -layout: default -tags: -- octave -title: The Octave Programming Language -title1: The Octave -title2: Programming Language ---- - - - -Welcome to the Octave page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- rzuckerm - -## Description - -Although this article is about the Octave programming language, let's first discuss -it's roots: a language called MATLAB. - -[MATLAB][1] (short for MATrix LABoratory) is a high-level programming language initially -released in 1984. It markets itself as an easy-to-pick-up tool for scientists, -engineers, and economists to do some serious number crunching. - -The development of MATLAB started in the 1970's when a computer science professor, -Cleve Moler, developed the language, so his students could use snippets of code -for solving linear systems and obtaining eigenvalues/eigenvectors (LINPACK and -EISPACK respectively) without having to learn Fortran. Moler's creation was -immediately popular for its ease-of-use, interactivity and expandability and -sports over 3 million users world-wide. - -The main downside of MATLAB is that it is a paid application, and a rather pricey one at -that. At the time of this writing (2023), [the price][7] ranges from $99 (perpetual for -student edition) to over $900 (per year for standard edition). An alternative to MATLAB is a -language called [Octave][2], which claims to be "mostly compatible with MATLAB". Unlike -MATLAB, Octave is completely free, and it is open source, available from the -[GNU Octave GitHub repository][6]. It is published by the [Free Source Foundation][3] -under the [GNU Public License (GPL)][4]. - -Octave was conceived by James B. Rawlings of the University of Wisconsin-Madison and -John G. Ekerdt of the University of Texas around 1988 as a means of solving certain chemistry -problems. Seeing that was too limited, they decided to create a more flexible tool which -eventually became Octave. This was also developed with the same goals as MATLAB, as a means of -solving scientific and engineer problems without having to use Fortran. Development started -around 1992, and the first official release was around 1994. - -You may be wondering why it is called "Octave", which sounds more like something -associated with music. The name comes from [Octave Levenspiel][5], one of the author's -chemistry professors, who published a textbook on chemical reactions. - -[1]: https://en.wikipedia.org/wiki/MATLAB -[2]: https://octave.org/about -[3]: https://www.fsf.org/ -[4]: https://www.gnu.org/copyleft/gpl.html -[5]: https://en.wikipedia.org/wiki/Octave_Levenspiel -[6]: https://github.com/gnu-octave/octave -[7]: https://www.mathworks.com/pricing-licensing.html - - -## Articles - -There are 14 articles: - -- [Baklava in Octave](/projects/baklava/octave) -- [Bubble Sort in Octave](/projects/bubble-sort/octave) -- [Capitalize in Octave](/projects/capitalize/octave) -- [Even Odd in Octave](/projects/even-odd/octave) -- [Factorial in Octave](/projects/factorial/octave) -- [Fibonacci in Octave](/projects/fibonacci/octave) -- [File Input Output in Octave](/projects/file-input-output/octave) -- [Fizz Buzz in Octave](/projects/fizz-buzz/octave) -- [Hello World in Octave](/projects/hello-world/octave) -- [Insertion Sort in Octave](/projects/insertion-sort/octave) -- [Merge Sort in Octave](/projects/merge-sort/octave) -- [Prime Number in Octave](/projects/prime-number/octave) -- [Reverse String in Octave](/projects/reverse-string/octave) -- [Selection Sort in Octave](/projects/selection-sort/octave) \ No newline at end of file diff --git a/docs/languages/odin/index.md b/docs/languages/odin/index.md deleted file mode 100644 index ba04635f2b..0000000000 --- a/docs/languages/odin/index.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -date: 2018-06-15 -featured-image: programming-languages.jpg -last-modified: 2025-10-30 -layout: default -tags: -- odin -title: The Odin Programming Language -title1: The Odin Programming -title2: Language ---- - - - -Welcome to the Odin page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 9 articles: - -- [Baklava in Odin](/projects/baklava/odin) -- [Even Odd in Odin](/projects/even-odd/odin) -- [Fibonacci in Odin](/projects/fibonacci/odin) -- [File Input Output in Odin](/projects/file-input-output/odin) -- [Fizz Buzz in Odin](/projects/fizz-buzz/odin) -- [Hello World in Odin](/projects/hello-world/odin) -- [Longest Word in Odin](/projects/longest-word/odin) -- [Prime Number in Odin](/projects/prime-number/odin) -- [Reverse String in Odin](/projects/reverse-string/odin) \ No newline at end of file diff --git a/docs/languages/opa/index.md b/docs/languages/opa/index.md deleted file mode 100644 index 73f1d277aa..0000000000 --- a/docs/languages/opa/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-07-16 -featured-image: programming-languages.jpg -last-modified: 2025-01-22 -layout: default -tags: -- opa -title: The Opa Programming Language -title1: The Opa Programming -title2: Language ---- - - - -Welcome to the Opa page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -[Opa][1] is sadly a short-lived language, created in 2011 by the company [MLState][2]. -It's strongly focused on webapps, as it lets you write server-side and client-side -code, side by side. The client-code is compiled into [JavaScript][3], and the server-code, -into [Node.js][4]. All using strong, static typing. Pretty nifty. - -In version 0.9.0, it natively supported [MongoDB][5], as if it had an [ORM][6] built in. -In 1.1.0, this support was extended to [PostgreSQL][7] too. - -It reminds me a bit of [React/JSX][9], as it's wholeheartedly designed for interoperability -with HTML. It's actually a first-class citizen. Blurring the line between client -and server code is something that I'm really fond of. - -The problem is that, having had only 2 years of activity, the "user experience" -is really bad. Setting up the environment is... problematic, to say the least. It -requires installing [Node.js][4] and [OCaml][9], with dependencies of each one sprinkled in. -Which in turn need dependencies. Some of which have to be compiled from source. -In a time where installing a language (or anything really) should not take more -than 2 or 3 commands (`apt update && apt install -y Stuff-0.1.1-dev`), this was a -paaaain!! - -Luckily, there's this cute technology called containers. - -[1]: https://en.wikipedia.org/wiki/Opa_(programming_language) -[2]: https://www.crunchbase.com/organization/mlstate -[3]: https://en.wikipedia.org/wiki/JavaScript -[4]: https://en.wikipedia.org/wiki/Node.js -[5]: https://en.wikipedia.org/wiki/MongoDB -[6]: https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping -[7]: https://en.wikipedia.org/wiki/PostgreSQL -[8]: https://legacy.reactjs.org/docs/introducing-jsx.html -[9]: https://en.wikipedia.org/wiki/OCaml - - -## Articles - -There are 2 articles: - -- [Baklava in Opa](/projects/baklava/opa) -- [Hello World in Opa](/projects/hello-world/opa) \ No newline at end of file diff --git a/docs/languages/orc/index.md b/docs/languages/orc/index.md deleted file mode 100644 index 419a3e4164..0000000000 --- a/docs/languages/orc/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-08-28 -featured-image: programming-languages.jpg -last-modified: 2024-12-23 -layout: default -tags: -- orc -title: The Orc Programming Language -title1: The Orc Programming -title2: Language ---- - - - -Welcome to the Orc page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Orc](/projects/baklava/orc) -- [Hello World in Orc](/projects/hello-world/orc) \ No newline at end of file diff --git a/docs/languages/owl-lisp/index.md b/docs/languages/owl-lisp/index.md deleted file mode 100644 index 02c469256a..0000000000 --- a/docs/languages/owl-lisp/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-06-29 -featured-image: programming-languages.jpg -last-modified: 2024-12-23 -layout: default -tags: -- owl-lisp -title: The Owl Lisp Programming Language -title1: The Owl Lisp -title2: Programming Language ---- - - - -Welcome to the Owl Lisp page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Owl Lisp](/projects/baklava/owl-lisp) -- [Hello World in Owl Lisp](/projects/hello-world/owl-lisp) \ No newline at end of file diff --git a/docs/languages/pascal/index.md b/docs/languages/pascal/index.md deleted file mode 100644 index 5154974337..0000000000 --- a/docs/languages/pascal/index.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-10 -featured-image: programming-languages.jpg -last-modified: 2026-04-11 -layout: default -tags: -- pascal -title: The Pascal Programming Language -title1: The Pascal -title2: Programming Language ---- - - - -Welcome to the Pascal page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -According to [Wikipedia][1], Pascal is an imperative and procedural language which -first appeared in 1970. Pascal's creator, [Niklaus Wirth][2], designed the language -with compiler and runtime efficiency in mind. In addition, Wirth drew much of -the inspiration for [Pascal][1] from the [ALGOL family][3] of languages. - -That said, Pascal isn't simply an ALGOL clone. In fact, Pascal includes many -additions to ALGOL such as mechanisms for defining custom datatypes. Likewise, -the language includes several additional features like enumerations, subranges, -and records. - -As an added bonus, Pascal is a strongly typed language. This forces the user to -explicitly write conversions between types, so errors can be caught at compile -time. Unfortunately, I've read that [Pascal has a loophole in the type system][4]. I -just haven't found any articles describing it. If you know, let me know in the -comments. - -Before we get into Hello World, I want to look a bit deeper at sets because I find -them interesting. In Pascal, we can define a set as follows: - -```pascal -var - Set1 : set of 5..20; - Set2 : set of 'f'..'m'; -``` - -With Pascal being such an old language, I find it interesting how intuitive the set -syntax is. In fact, I can't think of many industrial languages that have such a nice -syntax for setting up lists or sets. In fact, here's how you would generate a list of -numbers in a few languages: - -```java -// Java 8+ -int[] range = IntStream.rangeClosed(5, 20).toArray(); -``` - -```python -# Python 3 -list(range(5, 20)) -``` - -```javascript -// JavaScript -var list = []; -for (var i = 5; i <= 20; i++) { - list.push(i); -} -``` - -```c# -// C# -int[] values = Enumerable.Range(5, 15).ToArray(); -``` - -That Pascal set syntax is great. In fact, it even allows us to do fun things like -check values in some range: - -```pascal -if i in [5..20] then -``` - -At any rate, I think we've played around enough - -[1]: https://en.wikipedia.org/wiki/Pascal_(programming_language) -[2]: https://en.wikipedia.org/wiki/Niklaus_Wirth -[3]: https://en.wikipedia.org/wiki/ALGOL -[4]: https://www.lysator.liu.se/c/bwk-on-pascal.html - - -## Articles - -There are 38 articles: - -- [Baklava in Pascal](/projects/baklava/pascal) -- [Base64 Encode Decode in Pascal](/projects/base64-encode-decode/pascal) -- [Binary Search in Pascal](/projects/binary-search/pascal) -- [Bubble Sort in Pascal](/projects/bubble-sort/pascal) -- [Capitalize in Pascal](/projects/capitalize/pascal) -- [Convex Hull in Pascal](/projects/convex-hull/pascal) -- [Depth First Search in Pascal](/projects/depth-first-search/pascal) -- [Dijkstra in Pascal](/projects/dijkstra/pascal) -- [Duplicate Character Counter in Pascal](/projects/duplicate-character-counter/pascal) -- [Even Odd in Pascal](/projects/even-odd/pascal) -- [Factorial in Pascal](/projects/factorial/pascal) -- [Fibonacci in Pascal](/projects/fibonacci/pascal) -- [File Input Output in Pascal](/projects/file-input-output/pascal) -- [Fizz Buzz in Pascal](/projects/fizz-buzz/pascal) -- [Fraction Math in Pascal](/projects/fraction-math/pascal) -- [Hello World in Pascal](/projects/hello-world/pascal) -- [Insertion Sort in Pascal](/projects/insertion-sort/pascal) -- [Job Sequencing in Pascal](/projects/job-sequencing/pascal) -- [Josephus Problem in Pascal](/projects/josephus-problem/pascal) -- [Linear Search in Pascal](/projects/linear-search/pascal) -- [Longest Common Subsequence in Pascal](/projects/longest-common-subsequence/pascal) -- [Longest Palindromic Substring in Pascal](/projects/longest-palindromic-substring/pascal) -- [Longest Word in Pascal](/projects/longest-word/pascal) -- [Maximum Array Rotation in Pascal](/projects/maximum-array-rotation/pascal) -- [Maximum Subarray in Pascal](/projects/maximum-subarray/pascal) -- [Merge Sort in Pascal](/projects/merge-sort/pascal) -- [Minimum Spanning Tree in Pascal](/projects/minimum-spanning-tree/pascal) -- [Palindromic Number in Pascal](/projects/palindromic-number/pascal) -- [Prime Number in Pascal](/projects/prime-number/pascal) -- [Quick Sort in Pascal](/projects/quick-sort/pascal) -- [Quine in Pascal](/projects/quine/pascal) -- [Remove All Whitespace in Pascal](/projects/remove-all-whitespace/pascal) -- [Reverse String in Pascal](/projects/reverse-string/pascal) -- [Roman Numeral in Pascal](/projects/roman-numeral/pascal) -- [Rot13 in Pascal](/projects/rot13/pascal) -- [Selection Sort in Pascal](/projects/selection-sort/pascal) -- [Transpose Matrix in Pascal](/projects/transpose-matrix/pascal) -- [Zeckendorf in Pascal](/projects/zeckendorf/pascal) \ No newline at end of file diff --git a/docs/languages/perl/index.md b/docs/languages/perl/index.md deleted file mode 100644 index 23f7d944a1..0000000000 --- a/docs/languages/perl/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-08 -featured-image: programming-languages.jpg -last-modified: 2026-05-14 -layout: default -tags: -- perl -title: The Perl Programming Language -title1: The Perl Programming -title2: Language ---- - - - -Welcome to the Perl page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Just like normal, I took to [Wikipedia][1] to learn more about Perl. - -As it turns out, Perl is actually a family of languages sort of like [Lisp][2]. -However, Perl is mainly divided into two branches: Perl 5 and Perl 6. As you -can probably imagine, Perl 5 will be the language we'll be using for this -exercise. Perl 6 is actually a major deviation from the traditional language, -so I'll probably do a separate tutorial entirely for that language. - -At any rate, Perl is a multi-paradigm language, so we'll be diverging a bit -from our functional trend in this tutorial. Instead, we'll be working with a -language that resembles languages like [Python][3] or [C][4]. - -In terms of features, Perl is a mixed bag, literally. That's because Perl draws -its inspiration from several other languages including [C][4], [Lisp][2], and [AWK][5]. As a -result, Perl supports associative arrays, lists, regular expressions, and first- -class functions. In fact, modern Perl even support object-oriented programming. - -As a fun tidbit, Perl differs dramatically from Python in terms of complexity. -In fact, the creators of Perl live by the slogan "there's more than one way to -do it." In contrary, the creators of Python prefer that "there should be one, -and preferably only one, obvious way to do it" - -[1]: https://en.wikipedia.org/wiki/Perl -[2]: https://en.wikipedia.org/wiki/Lisp_(programming_language) -[3]: https://en.wikipedia.org/wiki/Python_(programming_language) -[4]: https://en.wikipedia.org/wiki/C_(programming_language) -[5]: https://en.wikipedia.org/wiki/AWK - - -## Articles - -There are 21 articles: - -- [Baklava in Perl](/projects/baklava/perl) -- [Binary Search in Perl](/projects/binary-search/perl) -- [Bubble Sort in Perl](/projects/bubble-sort/perl) -- [Capitalize in Perl](/projects/capitalize/perl) -- [Even Odd in Perl](/projects/even-odd/perl) -- [Factorial in Perl](/projects/factorial/perl) -- [Fibonacci in Perl](/projects/fibonacci/perl) -- [File Input Output in Perl](/projects/file-input-output/perl) -- [Fizz Buzz in Perl](/projects/fizz-buzz/perl) -- [Hello World in Perl](/projects/hello-world/perl) -- [Insertion Sort in Perl](/projects/insertion-sort/perl) -- [Linear Search in Perl](/projects/linear-search/perl) -- [Longest Word in Perl](/projects/longest-word/perl) -- [Merge Sort in Perl](/projects/merge-sort/perl) -- [Palindromic Number in Perl](/projects/palindromic-number/perl) -- [Prime Number in Perl](/projects/prime-number/perl) -- [Quick Sort in Perl](/projects/quick-sort/perl) -- [Quine in Perl](/projects/quine/perl) -- [Reverse String in Perl](/projects/reverse-string/perl) -- [Rot13 in Perl](/projects/rot13/perl) -- [Selection Sort in Perl](/projects/selection-sort/perl) \ No newline at end of file diff --git a/docs/languages/phix/index.md b/docs/languages/phix/index.md deleted file mode 100644 index 7a399ad418..0000000000 --- a/docs/languages/phix/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- rzuckerm -date: 2021-05-07 -featured-image: programming-languages.jpg -last-modified: 2023-04-18 -layout: default -tags: -- phix -title: The Phix Programming Language -title1: The Phix Programming -title2: Language ---- - - - -Welcome to the Phix page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- rzuckerm - -## Description - -According to the [Phix Official Site][1], the aims of Phix are as follows: - -* Create programs that are easy to write and maintain. -* Make it easier to find the location of compile-time and run-time errors - (the official site says "bugs", but I think this is the actually intent). -* Allow programmers to focus on solutions instead of solving the solution. -* Create programs that are easy to read and understand. - -Phix was created by [Pete Lomax][2]. Phix is largely based on [Euphoria][5] -and is almost [completely compatible][6] with Euphoria. Pete has this to say -as to [why he created this language][1]: - -> Phix was born out of frustration at waiting 18 months for a new release, only -to find the problem was still there. - -You may be wondering as to the reason for this name. According to the -[Phix Official Site][1]: - -> Phix is Pete’s Self Hosted Hybrid Interpreter/Compiler. pshhic was not the -best of acronyms, plus phiX is the name of the first ever manmade lifeform -artifically created from scratch in a laboratory, which seems rather appropriate -for a self-hosted compiler - -Phix has the same four data types as Euphoria: - -* `object` - Base data type -* `atom` - A 31-bit signed integer or 64-bit floating point number depending upon the - value stored. This is actually called `number` in the [official documentation][4], - but `atom` is still accepted. -* `integer` - A 31-bit in signed integer -* `sequence` - A list of values. This list can be comprised of `atom`s (`number`s) or - other `sequence`s - -However, it adds a [fifth data type][4]: - -* `string` - A `sequence` of characters or raw binary data - -Unlike Euphoria, Phix provides [short-circuited ternary operators][7]. For -example, the [iif function][8] in Euphoria will evaluate both the true and false -expressions and select the appropriate value. In other words, this code in -Euphoria will call both `foo` and `bar` and then return the value to `x` -depending upon whether `x` is non-zero or not: - -```euphoria -integer foo_or_bar = iff(x, foo(), bar()) -``` - -In Phix, this can be written like this: - -```phix -integer foo_or_bar = iff(x ? foo() : bar()) -``` - -Only if `x` is non-zero will `foo` be called; otherwise, `bar` will be called. - -Here's a short summary of some of the other language features that Phix offers -over Euphoria (just to name a few): - -* [Data structures][9] -* [Classes][10] -* [Exception handling][11] -* [Associative arrays][12] - -I'll have to admit, at first I just dismissed Phix as a knock-off of Euphoria, -but after doing some more research, I have to admit this Phix is definitely -worth further study! - -If you'd like more information about this language, please see the -[Phix documentation][3]. - -[1]: http://phix.x10.mx/ -[2]: https://github.com/petelomax/Phix -[3]: http://phix.x10.mx/docs/html/phix.htm -[4]: http://phix.x10.mx/docs/html/language.htm -[5]: https://en.wikipedia.org/wiki/Euphoria_(programming_language) -[6]: http://phix.x10.mx/docs/html/eucompat.htm -[7]: http://phix.x10.mx/docs/html/iff.htm -[8]: https://openeuphoria.org/docs/std_utils.html#_2216_iif -[9]: http://phix.x10.mx/docs/html/struct.htm -[10]: http://phix.x10.mx/docs/html/class.htm -[11]: http://phix.x10.mx/docs/html/try.htm -[12]: http://phix.x10.mx/docs/html/dict.htm - - -## Articles - -There are 2 articles: - -- [Baklava in Phix](/projects/baklava/phix) -- [Hello World in Phix](/projects/hello-world/phix) \ No newline at end of file diff --git a/docs/languages/php/index.md b/docs/languages/php/index.md deleted file mode 100644 index 7f878e5879..0000000000 --- a/docs/languages/php/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2018-03-31 -featured-image: programming-languages.jpg -last-modified: 2026-03-07 -layout: default -tags: -- php -title: The PHP Programming Language -title1: The PHP Programming -title2: Language ---- - - - -Welcome to the PHP page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in PHP](/projects/baklava/php) -- [Base64 Encode Decode in PHP](/projects/base64-encode-decode/php) -- [Binary Search in PHP](/projects/binary-search/php) -- [Bubble Sort in PHP](/projects/bubble-sort/php) -- [Capitalize in PHP](/projects/capitalize/php) -- [Convex Hull in PHP](/projects/convex-hull/php) -- [Depth First Search in PHP](/projects/depth-first-search/php) -- [Dijkstra in PHP](/projects/dijkstra/php) -- [Duplicate Character Counter in PHP](/projects/duplicate-character-counter/php) -- [Even Odd in PHP](/projects/even-odd/php) -- [Factorial in PHP](/projects/factorial/php) -- [Fibonacci in PHP](/projects/fibonacci/php) -- [File Input Output in PHP](/projects/file-input-output/php) -- [Fizz Buzz in PHP](/projects/fizz-buzz/php) -- [Fraction Math in PHP](/projects/fraction-math/php) -- [Hello World in PHP](/projects/hello-world/php) -- [Insertion Sort in PHP](/projects/insertion-sort/php) -- [Job Sequencing in PHP](/projects/job-sequencing/php) -- [Josephus Problem in PHP](/projects/josephus-problem/php) -- [Linear Search in PHP](/projects/linear-search/php) -- [Longest Common Subsequence in PHP](/projects/longest-common-subsequence/php) -- [Longest Palindromic Substring in PHP](/projects/longest-palindromic-substring/php) -- [Longest Word in PHP](/projects/longest-word/php) -- [Maximum Array Rotation in PHP](/projects/maximum-array-rotation/php) -- [Maximum Subarray in PHP](/projects/maximum-subarray/php) -- [Merge Sort in PHP](/projects/merge-sort/php) -- [Minimum Spanning Tree in PHP](/projects/minimum-spanning-tree/php) -- [Palindromic Number in PHP](/projects/palindromic-number/php) -- [Prime Number in PHP](/projects/prime-number/php) -- [Quick Sort in PHP](/projects/quick-sort/php) -- [Quine in PHP](/projects/quine/php) -- [Remove All Whitespace in PHP](/projects/remove-all-whitespace/php) -- [Reverse String in PHP](/projects/reverse-string/php) -- [Roman Numeral in PHP](/projects/roman-numeral/php) -- [Rot13 in PHP](/projects/rot13/php) -- [Selection Sort in PHP](/projects/selection-sort/php) -- [Transpose Matrix in PHP](/projects/transpose-matrix/php) -- [Zeckendorf in PHP](/projects/zeckendorf/php) \ No newline at end of file diff --git a/docs/languages/picolisp/index.md b/docs/languages/picolisp/index.md deleted file mode 100644 index 3ffb08d966..0000000000 --- a/docs/languages/picolisp/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-05-08 -featured-image: programming-languages.jpg -last-modified: 2024-12-21 -layout: default -tags: -- picolisp -title: The PicoLisp Programming Language -title1: The PicoLisp -title2: Programming Language ---- - - - -Welcome to the PicoLisp page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -According to [Wikipedia], PicoLisp is a dialect of [Lisp][2] which was first -developed in 1988 by Alexander Burger. Since then, PicoLisp has seen -some variation including the latest [Java][3] version known as Ersatz PicoLisp. - -In terms of features, PicoLisp is dynamically typed and simple/minimalist, sorry, -info on the language is quite limited. For simplicity, PicoLisp only supports -one internal data type, the cell. Beyond that, PicoLisp supports linked lists -which means the language is an excellent list processor. - -Today, PicoLisp can be found on [GitHub][4] as an open-source project. For more -information, check out the [PicoLisp Official Website][5]. - -[1]: https://en.wikipedia.org/wiki/PicoLisp -[2]: https://en.wikipedia.org/wiki/Lisp_(programming_language) -[3]: https://en.wikipedia.org/wiki/Java_(programming_language) -[4]: https://github.com/picolisp/pil21 -[5]: https://picolisp.com/wiki/?home - - -## Articles - -There are 3 articles: - -- [Baklava in PicoLisp](/projects/baklava/picolisp) -- [Hello World in PicoLisp](/projects/hello-world/picolisp) -- [Reverse String in PicoLisp](/projects/reverse-string/picolisp) \ No newline at end of file diff --git a/docs/languages/piet/index.md b/docs/languages/piet/index.md deleted file mode 100644 index dacdd344f5..0000000000 --- a/docs/languages/piet/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-04-25 -featured-image: programming-languages.jpg -last-modified: 2023-05-02 -layout: default -tags: -- piet -title: The Piet Programming Language -title1: The Piet Programming -title2: Language ---- - - - -Welcome to the Piet page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Piet](/projects/baklava/piet) -- [Hello World in Piet](/projects/hello-world/piet) \ No newline at end of file diff --git a/docs/languages/pineapple/index.md b/docs/languages/pineapple/index.md deleted file mode 100644 index 4730e59ee2..0000000000 --- a/docs/languages/pineapple/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2023-08-19 -featured-image: programming-languages.jpg -last-modified: 2024-11-20 -layout: default -tags: -- pineapple -title: The Pineapple Programming Language -title1: The Pineapple -title2: Programming Language ---- - - - -Welcome to the Pineapple page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Pineapple](/projects/baklava/pineapple) -- [Fizz Buzz in Pineapple](/projects/fizz-buzz/pineapple) -- [Hello World in Pineapple](/projects/hello-world/pineapple) \ No newline at end of file diff --git a/docs/languages/pinecone/index.md b/docs/languages/pinecone/index.md deleted file mode 100644 index bdc2e07f09..0000000000 --- a/docs/languages/pinecone/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2020-10-04 -featured-image: programming-languages.jpg -last-modified: 2024-12-02 -layout: default -tags: -- pinecone -title: The Pinecone Programming Language -title1: The Pinecone -title2: Programming Language ---- - - - -Welcome to the Pinecone page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Pinecone](/projects/baklava/pinecone) -- [Fizz Buzz in Pinecone](/projects/fizz-buzz/pinecone) -- [Hello World in Pinecone](/projects/hello-world/pinecone) \ No newline at end of file diff --git a/docs/languages/pony/index.md b/docs/languages/pony/index.md deleted file mode 100644 index b3b25860f7..0000000000 --- a/docs/languages/pony/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-04-26 -featured-image: programming-languages.jpg -last-modified: 2025-01-19 -layout: default -tags: -- pony -title: The Pony Programming Language -title1: The Pony Programming -title2: Language ---- - - - -Welcome to the Pony page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Pony](/projects/baklava/pony) -- [Fizz Buzz in Pony](/projects/fizz-buzz/pony) -- [Hello World in Pony](/projects/hello-world/pony) \ No newline at end of file diff --git a/docs/languages/powershell/index.md b/docs/languages/powershell/index.md deleted file mode 100644 index 9bb1025bc3..0000000000 --- a/docs/languages/powershell/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-05-28 -featured-image: programming-languages.jpg -last-modified: 2026-03-07 -layout: default -tags: -- powershell -title: The PowerShell Programming Language -title1: The PowerShell -title2: Programming Language ---- - - - -Welcome to the PowerShell page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -PowerShell is the de facto scripting language for managing Windows machines/servers. -[Microsoft][2] has made it quite clear that PowerShell is here to stay and will become -the preferred way to manage Windows servers in the future. - -[Jeffrey Snover][1] is largely credited as the designer behind the language, while -Bruce Payette and James Truher were also on the project, and in an interview in -2017, [Snover explained the motivation behind creating PowerShell][7]: - - I'd been driving a bunch of managing changes, and then I originally took the UNIX - tools and made them available on Windows, and then it just didn't work. Right? - Because there's a core architectural difference between Windows and Linux. On - Linux, everything's an ASCII text file, so anything that can manipulate that is - a managing tool. AWK, grep, sed? Happy days! - - I brought those tools available on Windows, and then they didn't help manage Windows - because in Windows, everything's an API that returns structured data. So, that - didn't help. [...] I came up with this idea of PowerShell, and I said, "Hey, - we can do this better." - -Originally, PowerShell was to be called Monad and it's ideas were published in a -white paper titled [Monad Manifesto][3]. Shortly after releasing the Beta 3 version -Microsoft formally renamed Monad to Windows PowerShell, followed by the release -candidate 1 version. - -PowerShell is now up to version 5.1 for stable builds and the new 6.0 version -which was announced in [2016 is in public beta][8]. The largest change in this version -is it's now open-source and will now be called PowerShell Core as it runs on -[.NET Core][4] as opposed to the [.NET Framework][5] which previous versions use. - -[1]: https://en.wikipedia.org/wiki/Jeffrey_Snover -[2]: https://en.wikipedia.org/wiki/Microsoft -[3]: https://www.jsnover.com/Docs/MonadManifesto.pdf -[4]: https://en.wikipedia.org/wiki/.NET -[5]: https://en.wikipedia.org/wiki/.NET_Framework -[7]: https://evrone.com/jeffrey-snover-interview -[8]: https://arstechnica.com/information-technology/2016/08/powershell-is-microsofts-latest-open-source-release-coming-to-linux-os-x/ - - -## Articles - -There are 38 articles: - -- [Baklava in PowerShell](/projects/baklava/powershell) -- [Base64 Encode Decode in PowerShell](/projects/base64-encode-decode/powershell) -- [Binary Search in PowerShell](/projects/binary-search/powershell) -- [Bubble Sort in PowerShell](/projects/bubble-sort/powershell) -- [Capitalize in PowerShell](/projects/capitalize/powershell) -- [Convex Hull in PowerShell](/projects/convex-hull/powershell) -- [Depth First Search in PowerShell](/projects/depth-first-search/powershell) -- [Dijkstra in PowerShell](/projects/dijkstra/powershell) -- [Duplicate Character Counter in PowerShell](/projects/duplicate-character-counter/powershell) -- [Even Odd in PowerShell](/projects/even-odd/powershell) -- [Factorial in PowerShell](/projects/factorial/powershell) -- [Fibonacci in PowerShell](/projects/fibonacci/powershell) -- [File Input Output in PowerShell](/projects/file-input-output/powershell) -- [Fizz Buzz in PowerShell](/projects/fizz-buzz/powershell) -- [Fraction Math in PowerShell](/projects/fraction-math/powershell) -- [Hello World in PowerShell](/projects/hello-world/powershell) -- [Insertion Sort in PowerShell](/projects/insertion-sort/powershell) -- [Job Sequencing in PowerShell](/projects/job-sequencing/powershell) -- [Josephus Problem in PowerShell](/projects/josephus-problem/powershell) -- [Linear Search in PowerShell](/projects/linear-search/powershell) -- [Longest Common Subsequence in PowerShell](/projects/longest-common-subsequence/powershell) -- [Longest Palindromic Substring in PowerShell](/projects/longest-palindromic-substring/powershell) -- [Longest Word in PowerShell](/projects/longest-word/powershell) -- [Maximum Array Rotation in PowerShell](/projects/maximum-array-rotation/powershell) -- [Maximum Subarray in PowerShell](/projects/maximum-subarray/powershell) -- [Merge Sort in PowerShell](/projects/merge-sort/powershell) -- [Minimum Spanning Tree in PowerShell](/projects/minimum-spanning-tree/powershell) -- [Palindromic Number in PowerShell](/projects/palindromic-number/powershell) -- [Prime Number in PowerShell](/projects/prime-number/powershell) -- [Quick Sort in PowerShell](/projects/quick-sort/powershell) -- [Quine in PowerShell](/projects/quine/powershell) -- [Remove All Whitespace in PowerShell](/projects/remove-all-whitespace/powershell) -- [Reverse String in PowerShell](/projects/reverse-string/powershell) -- [Roman Numeral in PowerShell](/projects/roman-numeral/powershell) -- [Rot13 in PowerShell](/projects/rot13/powershell) -- [Selection Sort in PowerShell](/projects/selection-sort/powershell) -- [Transpose Matrix in PowerShell](/projects/transpose-matrix/powershell) -- [Zeckendorf in PowerShell](/projects/zeckendorf/powershell) \ No newline at end of file diff --git a/docs/languages/prolog/index.md b/docs/languages/prolog/index.md deleted file mode 100644 index 40dd102316..0000000000 --- a/docs/languages/prolog/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2023-06-10 -featured-image: programming-languages.jpg -last-modified: 2024-12-21 -layout: default -tags: -- prolog -title: The Prolog Programming Language -title1: The Prolog -title2: Programming Language ---- - - - -Welcome to the Prolog page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Prolog](/projects/baklava/prolog) -- [Fizz Buzz in Prolog](/projects/fizz-buzz/prolog) -- [Hello World in Prolog](/projects/hello-world/prolog) \ No newline at end of file diff --git a/docs/languages/purescript/index.md b/docs/languages/purescript/index.md deleted file mode 100644 index 025ed5cb61..0000000000 --- a/docs/languages/purescript/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-12-22 -featured-image: programming-languages.jpg -last-modified: 2024-12-23 -layout: default -tags: -- purescript -title: The PureScript Programming Language -title1: The PureScript -title2: Programming Language ---- - - - -Welcome to the PureScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in PureScript](/projects/baklava/purescript) -- [Hello World in PureScript](/projects/hello-world/purescript) \ No newline at end of file diff --git a/docs/languages/pyret/index.md b/docs/languages/pyret/index.md deleted file mode 100644 index cace74c191..0000000000 --- a/docs/languages/pyret/index.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -date: 2018-04-23 -featured-image: programming-languages.jpg -last-modified: 2024-01-01 -layout: default -tags: -- pyret -title: The Pyret Programming Language -title1: The Pyret Programming -title2: Language ---- - - - -Welcome to the Pyret page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 4 articles: - -- [Baklava in Pyret](/projects/baklava/pyret) -- [Even Odd in Pyret](/projects/even-odd/pyret) -- [Fizz Buzz in Pyret](/projects/fizz-buzz/pyret) -- [Hello World in Pyret](/projects/hello-world/pyret) \ No newline at end of file diff --git a/docs/languages/python/index.md b/docs/languages/python/index.md deleted file mode 100644 index 336613f90f..0000000000 --- a/docs/languages/python/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- awoerner92 -- Jeremy Grifski -- Ron Zuckerman -date: 2018-03-15 -featured-image: programming-languages.jpg -last-modified: 2026-01-19 -layout: default -tags: -- python -title: The Python Programming Language -title1: The Python -title2: Programming Language ---- - - - -Welcome to the Python page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- awoerner92 -- Jeremy Grifski -- Ron Zuckerman - -## Description - -In order to learn more about Python, I took to [Wikipedia][1] for some background. - -According to Wikipedia, Python is an interpreted general-purposed language that was created by Guido van Rossum, -a Dutch programmer, in 1991. Apparently, Python was inspired by ABC, an imperative general-purpose language. - -Since 1991, Python has had two major upgrades: Python 2.0 and Python 3.0. In October 2000, Python 2.0 was released. -Over eight years later, Python 3.0 was released. Currently, the community supports both versions of Python. -But, Python 2 is slowly losing support. - -[1]: https://en.wikipedia.org/wiki/Python_(programming_language) - - -## Articles - -There are 38 articles: - -- [Baklava in Python](/projects/baklava/python) -- [Base64 Encode Decode in Python](/projects/base64-encode-decode/python) -- [Binary Search in Python](/projects/binary-search/python) -- [Bubble Sort in Python](/projects/bubble-sort/python) -- [Capitalize in Python](/projects/capitalize/python) -- [Convex Hull in Python](/projects/convex-hull/python) -- [Depth First Search in Python](/projects/depth-first-search/python) -- [Dijkstra in Python](/projects/dijkstra/python) -- [Duplicate Character Counter in Python](/projects/duplicate-character-counter/python) -- [Even Odd in Python](/projects/even-odd/python) -- [Factorial in Python](/projects/factorial/python) -- [Fibonacci in Python](/projects/fibonacci/python) -- [File Input Output in Python](/projects/file-input-output/python) -- [Fizz Buzz in Python](/projects/fizz-buzz/python) -- [Fraction Math in Python](/projects/fraction-math/python) -- [Hello World in Python](/projects/hello-world/python) -- [Insertion Sort in Python](/projects/insertion-sort/python) -- [Job Sequencing in Python](/projects/job-sequencing/python) -- [Josephus Problem in Python](/projects/josephus-problem/python) -- [Linear Search in Python](/projects/linear-search/python) -- [Longest Common Subsequence in Python](/projects/longest-common-subsequence/python) -- [Longest Palindromic Substring in Python](/projects/longest-palindromic-substring/python) -- [Longest Word in Python](/projects/longest-word/python) -- [Maximum Array Rotation in Python](/projects/maximum-array-rotation/python) -- [Maximum Subarray in Python](/projects/maximum-subarray/python) -- [Merge Sort in Python](/projects/merge-sort/python) -- [Minimum Spanning Tree in Python](/projects/minimum-spanning-tree/python) -- [Palindromic Number in Python](/projects/palindromic-number/python) -- [Prime Number in Python](/projects/prime-number/python) -- [Quick Sort in Python](/projects/quick-sort/python) -- [Quine in Python](/projects/quine/python) -- [Remove All Whitespace in Python](/projects/remove-all-whitespace/python) -- [Reverse String in Python](/projects/reverse-string/python) -- [Roman Numeral in Python](/projects/roman-numeral/python) -- [Rot13 in Python](/projects/rot13/python) -- [Selection Sort in Python](/projects/selection-sort/python) -- [Transpose Matrix in Python](/projects/transpose-matrix/python) -- [Zeckendorf in Python](/projects/zeckendorf/python) \ No newline at end of file diff --git a/docs/languages/quackery/index.md b/docs/languages/quackery/index.md deleted file mode 100644 index 132061805b..0000000000 --- a/docs/languages/quackery/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-12-09 -featured-image: programming-languages.jpg -last-modified: 2024-10-23 -layout: default -tags: -- quackery -title: The Quackery Programming Language -title1: The Quackery -title2: Programming Language ---- - - - -Welcome to the Quackery page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Quackery](/projects/baklava/quackery) -- [Hello World in Quackery](/projects/hello-world/quackery) \ No newline at end of file diff --git a/docs/languages/r/index.md b/docs/languages/r/index.md deleted file mode 100644 index 152df00c95..0000000000 --- a/docs/languages/r/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-27 -featured-image: programming-languages.jpg -last-modified: 2026-05-06 -layout: default -tags: -- r -title: The R Programming Language -title1: The R Programming -title2: Language ---- - - - -Welcome to the R page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -R is a language as well as an environment especially suited for statistical -computing, data analysis and data visualization. The first version of this -GNU project was [released in 1995][5]. The last major version 3.0 was released in -2013. - -R enjoys a high popularity in academia and has a large community which both -develops the language and releases new extensions. As a result, [CRAN][1] -emerged as a rich archive of packages extending the base functionality of R. - -In case you are interested in more information on the history and features of R, -take a look at the [R project website][2] from which this short summary -originates. - -[1]: https://en.wikipedia.org/wiki/R_package#Comprehensive_R_Archive_Network_(CRAN) -[2]: https://www.r-project.org/ -[5]: https://en.wikipedia.org/wiki/R_(programming_language)#History - - -## Articles - -There are 14 articles: - -- [Baklava in R](/projects/baklava/r) -- [Capitalize in R](/projects/capitalize/r) -- [Duplicate Character Counter in R](/projects/duplicate-character-counter/r) -- [Even Odd in R](/projects/even-odd/r) -- [Factorial in R](/projects/factorial/r) -- [Fibonacci in R](/projects/fibonacci/r) -- [File Input Output in R](/projects/file-input-output/r) -- [Fizz Buzz in R](/projects/fizz-buzz/r) -- [Hello World in R](/projects/hello-world/r) -- [Longest Word in R](/projects/longest-word/r) -- [Palindromic Number in R](/projects/palindromic-number/r) -- [Prime Number in R](/projects/prime-number/r) -- [Remove All Whitespace in R](/projects/remove-all-whitespace/r) -- [Reverse String in R](/projects/reverse-string/r) \ No newline at end of file diff --git a/docs/languages/racket/index.md b/docs/languages/racket/index.md deleted file mode 100644 index ccc9dd1c53..0000000000 --- a/docs/languages/racket/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-08 -featured-image: programming-languages.jpg -last-modified: 2024-10-19 -layout: default -tags: -- racket -title: The Racket Programming Language -title1: The Racket -title2: Programming Language ---- - - - -Welcome to the Racket page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Well, at this point, Wikipedia has yet to fail me. As usual, I referenced -it to learn a little bit more about today's language. - -Like [Python][1] and [Java][2], [Racket][3] is a general-purpose programming language. -Unfortunately, that's sort of where the similarities stop. After all, -Racket comes from the [Lisp-Scheme family][4], so it resembles a typical -functional programming language. In other words, expect plenty of parentheses. - -What makes Racket different from its [Lisp][5] counterparts is its extensibility. -In other words, the language can be easily modified using macros. Remember -when we learned about macros in [Rust][6]? Same idea. We can use these macros to -control the syntax of Racket. - -Macros alone aren't interesting enough to warrant any excitement. However, -mix macros with a module system, and we get an extremely versatile language. -These modules allow us to import various macros that can be used to control -the dialect of Racket. For instance, if we wanted a statically typed version -of Racket, there's a module for that: typed/racket. - -[1]: https://en.wikipedia.org/wiki/Python_(programming_language) -[2]: https://en.wikipedia.org/wiki/Java_(programming_language) -[3]: https://racket-lang.org/ -[4]: https://en.wikipedia.org/wiki/List_of_Lisp-family_programming_languages -[5]: https://en.wikipedia.org/wiki/Lisp_(programming_language) -[6]: https://en.wikipedia.org/wiki/Rust_(programming_language) - - -## Articles - -There are 4 articles: - -- [Baklava in Racket](/projects/baklava/racket) -- [Fibonacci in Racket](/projects/fibonacci/racket) -- [Fizz Buzz in Racket](/projects/fizz-buzz/racket) -- [Hello World in Racket](/projects/hello-world/racket) \ No newline at end of file diff --git a/docs/languages/raku/index.md b/docs/languages/raku/index.md deleted file mode 100644 index fcc0ee7317..0000000000 --- a/docs/languages/raku/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2020-11-02 -featured-image: programming-languages.jpg -last-modified: 2025-02-17 -layout: default -tags: -- raku -title: The Raku Programming Language -title1: The Raku Programming -title2: Language ---- - - - -Welcome to the Raku page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Raku](/projects/baklava/raku) -- [Fizz Buzz in Raku](/projects/fizz-buzz/raku) -- [Hello World in Raku](/projects/hello-world/raku) \ No newline at end of file diff --git a/docs/languages/red/index.md b/docs/languages/red/index.md deleted file mode 100644 index 35e9d04b12..0000000000 --- a/docs/languages/red/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Johnny Fang -- Ron Zuckerman -date: 2018-04-20 -featured-image: programming-languages.jpg -last-modified: 2025-10-30 -layout: default -tags: -- red -title: The Red Programming Language -title1: The Red Programming -title2: Language ---- - - - -Welcome to the Red page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Johnny Fang -- Ron Zuckerman - -## Description - -According to [Wikipedia][1], Red is a full stack programming language -inspired by Rebol. Of course, Red was designed to eliminate many of the -issues found in Rebol. For example, Red can be used on a much wider array -of tasks from system programming to scripting. - -In terms of features, Red offers strong metaprogramming utilities much -like [Racket][2]. Naturally, these utilities allow for language dialects. -For instance, Red has a language dialect called Red/System which is basically -a C-level version of the language. - -Another cool feature of Red is that it doesn't depend on any third-party -libraries except for the [Rebol2][3] interpreter. Eventually, the developers -plan to bootstrap Red to eliminate all dependencies. - -I suppose I wouldn't be doing Red justice if I didn't mention that the -toolchain can cross-compile to several platforms including [MS-DOS][4], [Windows XP][5], -[Linux][6], [MacOS][7], and [Android][8] (list is non-exhaustive). - -Also, fun fact: the entire Red toolchain is contained in a 1 MB executable. -Now, that's awesome! - -[1]: https://en.wikipedia.org/wiki/Red_(programming_language) -[2]: https://racket-lang.org/ -[3]: https://en.wikipedia.org/wiki/Rebol -[4]: https://en.wikipedia.org/wiki/MS-DOS -[5]: https://en.wikipedia.org/wiki/Windows_XP -[6]: https://en.wikipedia.org/wiki/Linux -[7]: https://en.wikipedia.org/wiki/MacOS -[8]: https://en.wikipedia.org/wiki/Android_(operating_system) - - -## Articles - -There are 4 articles: - -- [Baklava in Red](/projects/baklava/red) -- [Fizz Buzz in Red](/projects/fizz-buzz/red) -- [Hello World in Red](/projects/hello-world/red) -- [Prime Number in Red](/projects/prime-number/red) \ No newline at end of file diff --git a/docs/languages/rexx/index.md b/docs/languages/rexx/index.md deleted file mode 100644 index 258aa708fc..0000000000 --- a/docs/languages/rexx/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -date: 2018-04-19 -featured-image: programming-languages.jpg -last-modified: 2025-11-22 -layout: default -tags: -- rexx -title: The Rexx Programming Language -title1: The Rexx Programming -title2: Language ---- - - - -Welcome to the Rexx page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 6 articles: - -- [Baklava in Rexx](/projects/baklava/rexx) -- [Even Odd in Rexx](/projects/even-odd/rexx) -- [Fizz Buzz in Rexx](/projects/fizz-buzz/rexx) -- [Hello World in Rexx](/projects/hello-world/rexx) -- [Prime Number in Rexx](/projects/prime-number/rexx) -- [Reverse String in Rexx](/projects/reverse-string/rexx) \ No newline at end of file diff --git a/docs/languages/ring/index.md b/docs/languages/ring/index.md deleted file mode 100644 index e2442162b2..0000000000 --- a/docs/languages/ring/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-04-23 -featured-image: programming-languages.jpg -last-modified: 2024-10-01 -layout: default -tags: -- ring -title: The Ring Programming Language -title1: The Ring Programming -title2: Language ---- - - - -Welcome to the Ring page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Ring](/projects/baklava/ring) -- [Hello World in Ring](/projects/hello-world/ring) \ No newline at end of file diff --git a/docs/languages/ruby/index.md b/docs/languages/ruby/index.md deleted file mode 100644 index f55065a032..0000000000 --- a/docs/languages/ruby/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-03-21 -featured-image: programming-languages.jpg -last-modified: 2026-05-14 -layout: default -tags: -- ruby -title: The Ruby Programming Language -title1: The Ruby Programming -title2: Language ---- - - - -Welcome to the Ruby page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -According to [Wikipedia][1], Ruby is a general-purpose language that first appeared back in 1995 in Japan. -Apparently, Ruby is a truly object-oriented language in the sense that almost everything is an object. -In fact, even numbers are objects in Ruby which means they can be subjected to the dot operator. How cool is that? - -Today, the other major industry languages like [Python][2] and [Java][3] are more popular general-purpose languages, -so Ruby often finds its place as a web development language. This is probably due to the Ruby on Rails -framework which helps developers build web applications quickly and easily. - -## Features - -- Everything is an object -- Closures -- Mixins - -[1]: https://en.wikipedia.org/wiki/Ruby_(programming_language) -[2]: https://en.wikipedia.org/wiki/Python_(programming_language) -[3]: https://en.wikipedia.org/wiki/Java_(programming_language) - - -## Articles - -There are 38 articles: - -- [Baklava in Ruby](/projects/baklava/ruby) -- [Base64 Encode Decode in Ruby](/projects/base64-encode-decode/ruby) -- [Binary Search in Ruby](/projects/binary-search/ruby) -- [Bubble Sort in Ruby](/projects/bubble-sort/ruby) -- [Capitalize in Ruby](/projects/capitalize/ruby) -- [Convex Hull in Ruby](/projects/convex-hull/ruby) -- [Depth First Search in Ruby](/projects/depth-first-search/ruby) -- [Dijkstra in Ruby](/projects/dijkstra/ruby) -- [Duplicate Character Counter in Ruby](/projects/duplicate-character-counter/ruby) -- [Even Odd in Ruby](/projects/even-odd/ruby) -- [Factorial in Ruby](/projects/factorial/ruby) -- [Fibonacci in Ruby](/projects/fibonacci/ruby) -- [File Input Output in Ruby](/projects/file-input-output/ruby) -- [Fizz Buzz in Ruby](/projects/fizz-buzz/ruby) -- [Fraction Math in Ruby](/projects/fraction-math/ruby) -- [Hello World in Ruby](/projects/hello-world/ruby) -- [Insertion Sort in Ruby](/projects/insertion-sort/ruby) -- [Job Sequencing in Ruby](/projects/job-sequencing/ruby) -- [Josephus Problem in Ruby](/projects/josephus-problem/ruby) -- [Linear Search in Ruby](/projects/linear-search/ruby) -- [Longest Common Subsequence in Ruby](/projects/longest-common-subsequence/ruby) -- [Longest Palindromic Substring in Ruby](/projects/longest-palindromic-substring/ruby) -- [Longest Word in Ruby](/projects/longest-word/ruby) -- [Maximum Array Rotation in Ruby](/projects/maximum-array-rotation/ruby) -- [Maximum Subarray in Ruby](/projects/maximum-subarray/ruby) -- [Merge Sort in Ruby](/projects/merge-sort/ruby) -- [Minimum Spanning Tree in Ruby](/projects/minimum-spanning-tree/ruby) -- [Palindromic Number in Ruby](/projects/palindromic-number/ruby) -- [Prime Number in Ruby](/projects/prime-number/ruby) -- [Quick Sort in Ruby](/projects/quick-sort/ruby) -- [Quine in Ruby](/projects/quine/ruby) -- [Remove All Whitespace in Ruby](/projects/remove-all-whitespace/ruby) -- [Reverse String in Ruby](/projects/reverse-string/ruby) -- [Roman Numeral in Ruby](/projects/roman-numeral/ruby) -- [Rot13 in Ruby](/projects/rot13/ruby) -- [Selection Sort in Ruby](/projects/selection-sort/ruby) -- [Transpose Matrix in Ruby](/projects/transpose-matrix/ruby) -- [Zeckendorf in Ruby](/projects/zeckendorf/ruby) \ No newline at end of file diff --git a/docs/languages/rust/index.md b/docs/languages/rust/index.md deleted file mode 100644 index a62d87dac8..0000000000 --- a/docs/languages/rust/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Johnny Fang -- Ron Zuckerman -date: 2018-03-31 -featured-image: programming-languages.jpg -last-modified: 2026-03-07 -layout: default -tags: -- rust -title: The Rust Programming Language -title1: The Rust Programming -title2: Language ---- - - - -Welcome to the Rust page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Johnny Fang -- Ron Zuckerman - -## Description - -At this point, it's probably no surprise that I took to [Wikipedia to learn more about Rust][1]. - -According to Wikipedia, Rust is our first systems programming language. Up until now, we've really only played with general-purpose languages, so this is a nice change of pace. That said, __what is a systems programming language?__ - -Again, [according to Wikipedia][2], systems programming languages are designed for system software like device drivers and operating systems. Back when I took a compilers course, the professor used Rust for their example compiler, so I guess that checks out. - -With that said, what else can we find out about Rust? Well, Rust first showed up on the scene back in 2010 as a Mozilla sponsored project. Today, a large portion of the language has been written by the open source community. How cool is that? - -In terms of syntax, Rust resembles languages like [C][3] and [C++][4], but it borrows quite a lot from a general-purpose function programming language called [ML][5]. In addition, the language contains features like memory safety and ownership. - -[1]: https://en.wikipedia.org/wiki/Rust_(programming_language) -[2]: https://en.wikipedia.org/wiki/System_programming_language -[3]: https://en.wikipedia.org/wiki/C_(programming_language) -[4]: https://en.wikipedia.org/wiki/C%2B%2B -[5]: https://en.wikipedia.org/wiki/ML_(programming_language) - - -## Articles - -There are 38 articles: - -- [Baklava in Rust](/projects/baklava/rust) -- [Base64 Encode Decode in Rust](/projects/base64-encode-decode/rust) -- [Binary Search in Rust](/projects/binary-search/rust) -- [Bubble Sort in Rust](/projects/bubble-sort/rust) -- [Capitalize in Rust](/projects/capitalize/rust) -- [Convex Hull in Rust](/projects/convex-hull/rust) -- [Depth First Search in Rust](/projects/depth-first-search/rust) -- [Dijkstra in Rust](/projects/dijkstra/rust) -- [Duplicate Character Counter in Rust](/projects/duplicate-character-counter/rust) -- [Even Odd in Rust](/projects/even-odd/rust) -- [Factorial in Rust](/projects/factorial/rust) -- [Fibonacci in Rust](/projects/fibonacci/rust) -- [File Input Output in Rust](/projects/file-input-output/rust) -- [Fizz Buzz in Rust](/projects/fizz-buzz/rust) -- [Fraction Math in Rust](/projects/fraction-math/rust) -- [Hello World in Rust](/projects/hello-world/rust) -- [Insertion Sort in Rust](/projects/insertion-sort/rust) -- [Job Sequencing in Rust](/projects/job-sequencing/rust) -- [Josephus Problem in Rust](/projects/josephus-problem/rust) -- [Linear Search in Rust](/projects/linear-search/rust) -- [Longest Common Subsequence in Rust](/projects/longest-common-subsequence/rust) -- [Longest Palindromic Substring in Rust](/projects/longest-palindromic-substring/rust) -- [Longest Word in Rust](/projects/longest-word/rust) -- [Maximum Array Rotation in Rust](/projects/maximum-array-rotation/rust) -- [Maximum Subarray in Rust](/projects/maximum-subarray/rust) -- [Merge Sort in Rust](/projects/merge-sort/rust) -- [Minimum Spanning Tree in Rust](/projects/minimum-spanning-tree/rust) -- [Palindromic Number in Rust](/projects/palindromic-number/rust) -- [Prime Number in Rust](/projects/prime-number/rust) -- [Quick Sort in Rust](/projects/quick-sort/rust) -- [Quine in Rust](/projects/quine/rust) -- [Remove All Whitespace in Rust](/projects/remove-all-whitespace/rust) -- [Reverse String in Rust](/projects/reverse-string/rust) -- [Roman Numeral in Rust](/projects/roman-numeral/rust) -- [Rot13 in Rust](/projects/rot13/rust) -- [Selection Sort in Rust](/projects/selection-sort/rust) -- [Transpose Matrix in Rust](/projects/transpose-matrix/rust) -- [Zeckendorf in Rust](/projects/zeckendorf/rust) \ No newline at end of file diff --git a/docs/languages/sather/index.md b/docs/languages/sather/index.md deleted file mode 100644 index b4ce468a7b..0000000000 --- a/docs/languages/sather/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2020-10-02 -featured-image: programming-languages.jpg -last-modified: 2024-10-02 -layout: default -tags: -- sather -title: The Sather Programming Language -title1: The Sather -title2: Programming Language ---- - - - -Welcome to the Sather page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Sather](/projects/baklava/sather) -- [Hello World in Sather](/projects/hello-world/sather) \ No newline at end of file diff --git a/docs/languages/scala/index.md b/docs/languages/scala/index.md deleted file mode 100644 index 1951acbdb6..0000000000 --- a/docs/languages/scala/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2019-03-22 -featured-image: programming-languages.jpg -last-modified: 2026-04-11 -layout: default -tags: -- scala -title: The Scala Programming Language -title1: The Scala Programming -title2: Language ---- - - - -Welcome to the Scala page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -According to [Wikipedia][1], Scala is another general-purpose programming -language. Likewise, Scala is a multi-paradigm language. However, it -does have functional capabilities, so I think it fits nicely into our -recent string of functional languages: Lisp, Scheme, Racket, etc. - -Now, Scala is a relatively new language. In fact, it was released in -2004, almost ten years after the release of Java. I mention Java because -Scala was actually designed to correct many of Java's problems. For -instance, here's a list of some of Scala's features: a unified type -system, syntactic flexibility, functional tendencies, and object-oriented -extensions. - -At this point, I should probably share an example to illustrate some of -these differences, but I think Wikipedia already shares several excellent -examples. In addition, I dug up a couple decent blogs comparing the two -languages: - -- [Scala vs. Java: Differences and Similarities][2] -- [Scala vs. Java: Why Should I Learn Scala?][3] - -Since Scala has functional tendencies, I figured I'd dig into that a bit -too. As it turns out, everything in Scala is an expression. And as a result, -every expression is a function. This means that return statements are not -required and are actually discouraged: - -```scala -val myGrade = if (score >= 70) "Pass" else "Fail" -``` - -For those familiar with [Java][4], this example probably looks odd. Fortunately, -the solution is simple. Just evaluate the if-else expression and store the -expected result in myGrade. If score is 90, then myGrade would store "Pass." -That's pretty cool stuff! - -At any rate, we probably shouldn't dive too much further. After all, we have -yet to implement Hello World in Scala. - -[1]: https://en.wikipedia.org/wiki/Scala_(programming_language) -[2]: https://javarevisited.blogspot.com/2013/11/scala-vs-java-differences-similarities-books.html#axzz7xCsga6Qe -[3]: https://www.toptal.com/scala/why-should-i-learn-scala -[4]: https://en.wikipedia.org/wiki/Java_(programming_language) - - -## Articles - -There are 12 articles: - -- [Baklava in Scala](/projects/baklava/scala) -- [Bubble Sort in Scala](/projects/bubble-sort/scala) -- [Capitalize in Scala](/projects/capitalize/scala) -- [Even Odd in Scala](/projects/even-odd/scala) -- [Factorial in Scala](/projects/factorial/scala) -- [Fibonacci in Scala](/projects/fibonacci/scala) -- [File Input Output in Scala](/projects/file-input-output/scala) -- [Fizz Buzz in Scala](/projects/fizz-buzz/scala) -- [Hello World in Scala](/projects/hello-world/scala) -- [Linear Search in Scala](/projects/linear-search/scala) -- [Quick Sort in Scala](/projects/quick-sort/scala) -- [Reverse String in Scala](/projects/reverse-string/scala) \ No newline at end of file diff --git a/docs/languages/scheme/index.md b/docs/languages/scheme/index.md deleted file mode 100644 index f02af7a0f1..0000000000 --- a/docs/languages/scheme/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- awoerner92 -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-08 -featured-image: programming-languages.jpg -last-modified: 2024-10-28 -layout: default -tags: -- scheme -title: The Scheme Programming Language -title1: The Scheme -title2: Programming Language ---- - - - -Welcome to the Scheme page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- awoerner92 -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Once again, I took to [Wikipedia][1] to learn more about the new language. - -According to Wikipedia, Scheme is the minimalist branch of Lisp. The only indicator of -minimalism in Scheme I can find is the fact that it features only 23 s-expressions. -Unfortunately, I wasn't able to find any additional information on what makes scheme so -simple. Let me know in the comments. - -In terms of features, Scheme leverages lambda calculus, lexical scoping, tail recursion, -and first-class continuations. To be honest, I had to research [lexical scoping][2]. -Turns out, lexical scoping is just a fancy name for static scoping. In other words, variables -only exist within the block of text that they're defined. In contrast, -[Common Lisp supports both lexical and dynamic scoping][3]. - -Despite Scheme appearing back in 1970, it's still used today for primarily educational purposes. -For instance, many universities use Scheme in their introductory programming courses. Beyond -education, Scheme is mainly used by hobbyists for scripting purposes. - -[1]: https://en.wikipedia.org/wiki/Scheme_(programming_language) -[2]: https://en.wikipedia.org/wiki/Scope_(computer_science)#Lexical_scoping_and_dynamic_scoping -[3]: https://en.wikipedia.org/wiki/Common_Lisp - - -## Articles - -There are 3 articles: - -- [Baklava in Scheme](/projects/baklava/scheme) -- [Hello World in Scheme](/projects/hello-world/scheme) -- [Reverse String in Scheme](/projects/reverse-string/scheme) \ No newline at end of file diff --git a/docs/languages/scilab/index.md b/docs/languages/scilab/index.md deleted file mode 100644 index 1b1cf6f206..0000000000 --- a/docs/languages/scilab/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-11-20 -featured-image: programming-languages.jpg -last-modified: 2024-10-02 -layout: default -tags: -- scilab -title: The Scilab Programming Language -title1: The Scilab -title2: Programming Language ---- - - - -Welcome to the Scilab page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Scilab](/projects/baklava/scilab) -- [Hello World in Scilab](/projects/hello-world/scilab) \ No newline at end of file diff --git a/docs/languages/shen/index.md b/docs/languages/shen/index.md deleted file mode 100644 index 603c03ea67..0000000000 --- a/docs/languages/shen/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-11-20 -featured-image: programming-languages.jpg -last-modified: 2024-10-28 -layout: default -tags: -- shen -title: The Shen Programming Language -title1: The Shen Programming -title2: Language ---- - - - -Welcome to the Shen page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Shen](/projects/baklava/shen) -- [Hello World in Shen](/projects/hello-world/shen) \ No newline at end of file diff --git a/docs/languages/smalltalk/index.md b/docs/languages/smalltalk/index.md deleted file mode 100644 index ca66a9a352..0000000000 --- a/docs/languages/smalltalk/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-04-26 -featured-image: programming-languages.jpg -last-modified: 2024-11-16 -layout: default -tags: -- smalltalk -title: The Smalltalk Programming Language -title1: The Smalltalk -title2: Programming Language ---- - - - -Welcome to the Smalltalk page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Smalltalk](/projects/baklava/smalltalk) -- [Fizz Buzz in Smalltalk](/projects/fizz-buzz/smalltalk) -- [Hello World in Smalltalk](/projects/hello-world/smalltalk) \ No newline at end of file diff --git a/docs/languages/solidity/index.md b/docs/languages/solidity/index.md deleted file mode 100644 index 0a5d4a2384..0000000000 --- a/docs/languages/solidity/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-10-31 -featured-image: programming-languages.jpg -last-modified: 2024-10-07 -layout: default -tags: -- solidity -title: The Solidity Programming Language -title1: The Solidity -title2: Programming Language ---- - - - -Welcome to the Solidity page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -To understand Solidity, it is imperative to comprehend the context in which it -is used. So, the first question to ask is: what is a smart contract? - -### Smart Contract - -[According to Wikipedia][1], a smart contract is a computer protocol intended to -digitally facilitate, verify, or enforce the negotiation or performance of a -contract. They allow the performance of credible transactions without third-parties. - -The contracts used in this sense are the exact same as the regular contracts -you're familiar with. By removing the human factor and voiding the need for a -third-party, people and business are able to save money and reduce the chance of -fraud. Smart contracts are the main driving force of blockchains. - -### Blockchain - -[According to Wikipedia][2], a blockchain is a continuously growing list of records, -called blocks, which are linked and secured using cryptography. Each block -typically contains a cryptographic hash of the previous block, a timestamp, -and transaction data. - -Blockchain is the force driving the technology of all digital currencies. -A couple of examples are Bitcoin, Ripple, Ethereum, Litecoin, Nem just to cite a few. - -[Blockgeeks][3] has a great analogy which should help you understand blockchain works: - - Picture a spreadsheet that is duplicated thousands of times across a network - of computers. Then imagine that this network is designed to regularly update - this spreadsheet and you have a basic understanding of the blockchain. - -Another wonderful description provided by [William Mougayar][4] goes as follows: - - Imagine two entities (eg banks) that need to update their own user account - balances when there is a request to transfer money from one customer to another. - They need to spend a tremendous (and costly) amount of time and effort for - coordination, synchronization, messaging and checking to ensure that each - transaction happens exactly as it should. - - Typically, the money being transferred is held by the originator until it can be - confirmed that it was received by the recipient. With the blockchain, a single - ledger of transaction entries that both parties have access to can simplify the - coordination and validation efforts because there is always a single version of - records, not two disparate databases. - -Welcome to solidity! - -[1]: https://en.wikipedia.org/wiki/Smart_contract -[2]: https://en.wikipedia.org/wiki/Blockchain -[3]: https://blockgeeks.com/guides/what-is-blockchain-technology/ -[4]: https://medium.com/@wmougayar/explaining-the-blockchain-via-a-google-docs-analogy-56326b1bbe58 - - -## Articles - -There are 2 articles: - -- [Baklava in Solidity](/projects/baklava/solidity) -- [Hello World in Solidity](/projects/hello-world/solidity) \ No newline at end of file diff --git a/docs/languages/solisp/index.md b/docs/languages/solisp/index.md deleted file mode 100644 index 1bee6364c4..0000000000 --- a/docs/languages/solisp/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2020-02-25 -featured-image: programming-languages.jpg -last-modified: 2023-09-24 -layout: default -tags: -- solisp -title: The Solisp Programming Language -title1: The Solisp -title2: Programming Language ---- - - - -Welcome to the Solisp page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Solisp](/projects/baklava/solisp) -- [Fizz Buzz in Solisp](/projects/fizz-buzz/solisp) -- [Hello World in Solisp](/projects/hello-world/solisp) \ No newline at end of file diff --git a/docs/languages/spry/index.md b/docs/languages/spry/index.md deleted file mode 100644 index 215c1e446e..0000000000 --- a/docs/languages/spry/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2021-05-24 -featured-image: programming-languages.jpg -last-modified: 2024-12-21 -layout: default -tags: -- spry -title: The Spry Programming Language -title1: The Spry Programming -title2: Language ---- - - - -Welcome to the Spry page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Spry](/projects/baklava/spry) -- [Hello World in Spry](/projects/hello-world/spry) \ No newline at end of file diff --git a/docs/languages/swift/index.md b/docs/languages/swift/index.md deleted file mode 100644 index eb1a585003..0000000000 --- a/docs/languages/swift/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2018-03-25 -featured-image: programming-languages.jpg -last-modified: 2026-05-03 -layout: default -tags: -- swift -title: The Swift Programming Language -title1: The Swift Programming -title2: Language ---- - - - -Welcome to the Swift page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in Swift](/projects/baklava/swift) -- [Base64 Encode Decode in Swift](/projects/base64-encode-decode/swift) -- [Binary Search in Swift](/projects/binary-search/swift) -- [Bubble Sort in Swift](/projects/bubble-sort/swift) -- [Capitalize in Swift](/projects/capitalize/swift) -- [Convex Hull in Swift](/projects/convex-hull/swift) -- [Depth First Search in Swift](/projects/depth-first-search/swift) -- [Dijkstra in Swift](/projects/dijkstra/swift) -- [Duplicate Character Counter in Swift](/projects/duplicate-character-counter/swift) -- [Even Odd in Swift](/projects/even-odd/swift) -- [Factorial in Swift](/projects/factorial/swift) -- [Fibonacci in Swift](/projects/fibonacci/swift) -- [File Input Output in Swift](/projects/file-input-output/swift) -- [Fizz Buzz in Swift](/projects/fizz-buzz/swift) -- [Fraction Math in Swift](/projects/fraction-math/swift) -- [Hello World in Swift](/projects/hello-world/swift) -- [Insertion Sort in Swift](/projects/insertion-sort/swift) -- [Job Sequencing in Swift](/projects/job-sequencing/swift) -- [Josephus Problem in Swift](/projects/josephus-problem/swift) -- [Linear Search in Swift](/projects/linear-search/swift) -- [Longest Common Subsequence in Swift](/projects/longest-common-subsequence/swift) -- [Longest Palindromic Substring in Swift](/projects/longest-palindromic-substring/swift) -- [Longest Word in Swift](/projects/longest-word/swift) -- [Maximum Array Rotation in Swift](/projects/maximum-array-rotation/swift) -- [Maximum Subarray in Swift](/projects/maximum-subarray/swift) -- [Merge Sort in Swift](/projects/merge-sort/swift) -- [Minimum Spanning Tree in Swift](/projects/minimum-spanning-tree/swift) -- [Palindromic Number in Swift](/projects/palindromic-number/swift) -- [Prime Number in Swift](/projects/prime-number/swift) -- [Quick Sort in Swift](/projects/quick-sort/swift) -- [Quine in Swift](/projects/quine/swift) -- [Remove All Whitespace in Swift](/projects/remove-all-whitespace/swift) -- [Reverse String in Swift](/projects/reverse-string/swift) -- [Roman Numeral in Swift](/projects/roman-numeral/swift) -- [Rot13 in Swift](/projects/rot13/swift) -- [Selection Sort in Swift](/projects/selection-sort/swift) -- [Transpose Matrix in Swift](/projects/transpose-matrix/swift) -- [Zeckendorf in Swift](/projects/zeckendorf/swift) \ No newline at end of file diff --git a/docs/languages/tcl/index.md b/docs/languages/tcl/index.md deleted file mode 100644 index 27a1552abd..0000000000 --- a/docs/languages/tcl/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2018-04-19 -featured-image: programming-languages.jpg -last-modified: 2026-04-11 -layout: default -tags: -- tcl -title: The Tcl Programming Language -title1: The Tcl Programming -title2: Language ---- - - - -Welcome to the Tcl page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in Tcl](/projects/baklava/tcl) -- [Base64 Encode Decode in Tcl](/projects/base64-encode-decode/tcl) -- [Binary Search in Tcl](/projects/binary-search/tcl) -- [Bubble Sort in Tcl](/projects/bubble-sort/tcl) -- [Capitalize in Tcl](/projects/capitalize/tcl) -- [Convex Hull in Tcl](/projects/convex-hull/tcl) -- [Depth First Search in Tcl](/projects/depth-first-search/tcl) -- [Dijkstra in Tcl](/projects/dijkstra/tcl) -- [Duplicate Character Counter in Tcl](/projects/duplicate-character-counter/tcl) -- [Even Odd in Tcl](/projects/even-odd/tcl) -- [Factorial in Tcl](/projects/factorial/tcl) -- [Fibonacci in Tcl](/projects/fibonacci/tcl) -- [File Input Output in Tcl](/projects/file-input-output/tcl) -- [Fizz Buzz in Tcl](/projects/fizz-buzz/tcl) -- [Fraction Math in Tcl](/projects/fraction-math/tcl) -- [Hello World in Tcl](/projects/hello-world/tcl) -- [Insertion Sort in Tcl](/projects/insertion-sort/tcl) -- [Job Sequencing in Tcl](/projects/job-sequencing/tcl) -- [Josephus Problem in Tcl](/projects/josephus-problem/tcl) -- [Linear Search in Tcl](/projects/linear-search/tcl) -- [Longest Common Subsequence in Tcl](/projects/longest-common-subsequence/tcl) -- [Longest Palindromic Substring in Tcl](/projects/longest-palindromic-substring/tcl) -- [Longest Word in Tcl](/projects/longest-word/tcl) -- [Maximum Array Rotation in Tcl](/projects/maximum-array-rotation/tcl) -- [Maximum Subarray in Tcl](/projects/maximum-subarray/tcl) -- [Merge Sort in Tcl](/projects/merge-sort/tcl) -- [Minimum Spanning Tree in Tcl](/projects/minimum-spanning-tree/tcl) -- [Palindromic Number in Tcl](/projects/palindromic-number/tcl) -- [Prime Number in Tcl](/projects/prime-number/tcl) -- [Quick Sort in Tcl](/projects/quick-sort/tcl) -- [Quine in Tcl](/projects/quine/tcl) -- [Remove All Whitespace in Tcl](/projects/remove-all-whitespace/tcl) -- [Reverse String in Tcl](/projects/reverse-string/tcl) -- [Roman Numeral in Tcl](/projects/roman-numeral/tcl) -- [Rot13 in Tcl](/projects/rot13/tcl) -- [Selection Sort in Tcl](/projects/selection-sort/tcl) -- [Transpose Matrix in Tcl](/projects/transpose-matrix/tcl) -- [Zeckendorf in Tcl](/projects/zeckendorf/tcl) \ No newline at end of file diff --git a/docs/languages/terra/index.md b/docs/languages/terra/index.md deleted file mode 100644 index 541801f3ca..0000000000 --- a/docs/languages/terra/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2021-05-24 -featured-image: programming-languages.jpg -last-modified: 2024-10-03 -layout: default -tags: -- terra -title: The Terra Programming Language -title1: The Terra Programming -title2: Language ---- - - - -Welcome to the Terra page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Terra](/projects/baklava/terra) -- [Hello World in Terra](/projects/hello-world/terra) \ No newline at end of file diff --git a/docs/languages/tex/index.md b/docs/languages/tex/index.md deleted file mode 100644 index 6953c3acf0..0000000000 --- a/docs/languages/tex/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2018-08-28 -featured-image: programming-languages.jpg -last-modified: 2025-01-30 -layout: default -tags: -- tex -title: The TeX Programming Language -title1: The TeX Programming -title2: Language ---- - - - -Welcome to the TeX page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in TeX](/projects/baklava/tex) -- [Fizz Buzz in TeX](/projects/fizz-buzz/tex) -- [Hello World in TeX](/projects/hello-world/tex) \ No newline at end of file diff --git a/docs/languages/ti-basic/index.md b/docs/languages/ti-basic/index.md deleted file mode 100644 index cad0891356..0000000000 --- a/docs/languages/ti-basic/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -date: 2023-12-16 -featured-image: programming-languages.jpg -last-modified: 2026-03-07 -layout: default -tags: -- ti-basic -title: The TI-BASIC Programming Language -title1: The TI-BASIC -title2: Programming Language ---- - - - -Welcome to the TI-BASIC page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 14 articles: - -- [Baklava in TI-BASIC](/projects/baklava/ti-basic) -- [Capitalize in TI-BASIC](/projects/capitalize/ti-basic) -- [Duplicate Character Counter in TI-BASIC](/projects/duplicate-character-counter/ti-basic) -- [Even Odd in TI-BASIC](/projects/even-odd/ti-basic) -- [Factorial in TI-BASIC](/projects/factorial/ti-basic) -- [Fibonacci in TI-BASIC](/projects/fibonacci/ti-basic) -- [Fizz Buzz in TI-BASIC](/projects/fizz-buzz/ti-basic) -- [Hello World in TI-BASIC](/projects/hello-world/ti-basic) -- [Josephus Problem in TI-BASIC](/projects/josephus-problem/ti-basic) -- [Palindromic Number in TI-BASIC](/projects/palindromic-number/ti-basic) -- [Prime Number in TI-BASIC](/projects/prime-number/ti-basic) -- [Reverse String in TI-BASIC](/projects/reverse-string/ti-basic) -- [Rot13 in TI-BASIC](/projects/rot13/ti-basic) -- [Zeckendorf in TI-BASIC](/projects/zeckendorf/ti-basic) \ No newline at end of file diff --git a/docs/languages/typescript/index.md b/docs/languages/typescript/index.md deleted file mode 100644 index 684fb30a7f..0000000000 --- a/docs/languages/typescript/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -date: 2018-06-22 -featured-image: programming-languages.jpg -last-modified: 2026-05-07 -layout: default -tags: -- typescript -title: The TypeScript Programming Language -title1: The TypeScript -title2: Programming Language ---- - - - -Welcome to the TypeScript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 38 articles: - -- [Baklava in TypeScript](/projects/baklava/typescript) -- [Base64 Encode Decode in TypeScript](/projects/base64-encode-decode/typescript) -- [Binary Search in TypeScript](/projects/binary-search/typescript) -- [Bubble Sort in TypeScript](/projects/bubble-sort/typescript) -- [Capitalize in TypeScript](/projects/capitalize/typescript) -- [Convex Hull in TypeScript](/projects/convex-hull/typescript) -- [Depth First Search in TypeScript](/projects/depth-first-search/typescript) -- [Dijkstra in TypeScript](/projects/dijkstra/typescript) -- [Duplicate Character Counter in TypeScript](/projects/duplicate-character-counter/typescript) -- [Even Odd in TypeScript](/projects/even-odd/typescript) -- [Factorial in TypeScript](/projects/factorial/typescript) -- [Fibonacci in TypeScript](/projects/fibonacci/typescript) -- [File Input Output in TypeScript](/projects/file-input-output/typescript) -- [Fizz Buzz in TypeScript](/projects/fizz-buzz/typescript) -- [Fraction Math in TypeScript](/projects/fraction-math/typescript) -- [Hello World in TypeScript](/projects/hello-world/typescript) -- [Insertion Sort in TypeScript](/projects/insertion-sort/typescript) -- [Job Sequencing in TypeScript](/projects/job-sequencing/typescript) -- [Josephus Problem in TypeScript](/projects/josephus-problem/typescript) -- [Linear Search in TypeScript](/projects/linear-search/typescript) -- [Longest Common Subsequence in TypeScript](/projects/longest-common-subsequence/typescript) -- [Longest Palindromic Substring in TypeScript](/projects/longest-palindromic-substring/typescript) -- [Longest Word in TypeScript](/projects/longest-word/typescript) -- [Maximum Array Rotation in TypeScript](/projects/maximum-array-rotation/typescript) -- [Maximum Subarray in TypeScript](/projects/maximum-subarray/typescript) -- [Merge Sort in TypeScript](/projects/merge-sort/typescript) -- [Minimum Spanning Tree in TypeScript](/projects/minimum-spanning-tree/typescript) -- [Palindromic Number in TypeScript](/projects/palindromic-number/typescript) -- [Prime Number in TypeScript](/projects/prime-number/typescript) -- [Quick Sort in TypeScript](/projects/quick-sort/typescript) -- [Quine in TypeScript](/projects/quine/typescript) -- [Remove All Whitespace in TypeScript](/projects/remove-all-whitespace/typescript) -- [Reverse String in TypeScript](/projects/reverse-string/typescript) -- [Roman Numeral in TypeScript](/projects/roman-numeral/typescript) -- [Rot13 in TypeScript](/projects/rot13/typescript) -- [Selection Sort in TypeScript](/projects/selection-sort/typescript) -- [Transpose Matrix in TypeScript](/projects/transpose-matrix/typescript) -- [Zeckendorf in TypeScript](/projects/zeckendorf/typescript) \ No newline at end of file diff --git a/docs/languages/unicat/index.md b/docs/languages/unicat/index.md deleted file mode 100644 index 556a88fc45..0000000000 --- a/docs/languages/unicat/index.md +++ /dev/null @@ -1,366 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-23 -featured-image: programming-languages.jpg -last-modified: 2023-09-09 -layout: default -tags: -- unicat -title: The Unicat Programming Language -title1: The Unicat -title2: Programming Language ---- - - - -Welcome to the Unicat page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- rzuckerm - -## Description - - - -### Introduction - -If you love cats and you love emojis, then you'll *love* this language -since it is entirely composed of cat emojis! But seriously, this is an -[esoteric language][1], so it is designed to be challenging and difficult -to do anything useful. - -The Unicat language was created by [gemdude46][2]. Sadly, there was no -documentation that described how to use it. In order to learn this language, -I had to [study the code][3]. It is written in python2, which went -[End-of-Life on January 1, 2020][4]. Fortunately, I had a python2.7 -interpreter, so I was able to run the [example programs][5] and put them -on the [python2.7 debugger][6] to figure out parts of the code that I couldn't -figure out by just reading the code. - -### Character Set - -There are 9 cat emojis that make up the character set for this language. Each -one of these characters represent a byte code from `"0"` to `"8"`: - -| Emoji | Byte Code | [Emoji type][7] | -| --------------------------- | --------- | ------------------------------ | -| 😸 | `"0"` | Grinning Cat with Smiling Eyes | -| 😹 | `"1"` | Cat with Tears of Joy | -| 😺 | `"2"` | Grinning Cat | -| 😻 | `"3"` | Smiling Cat with Heart-Eyes | -| 😼 | `"4"` | Cat with Wry Smile | -| 😽 | `"5"` | Kissing Cat | -| 😾 | `"6"` | Pouting Cat | -| 😿 | `"7"` | Crying Cat | -| 🙀 | `"8"` | Weary Cat | - -Anything that is not a cat emoji is ignored, so code comments can be placed -within code without affecting the operation. - -### Memory - -Memory is made of an arbitrarily large set of addresses that are capable of -storing arbitrarily large values. In other words, it is a python dictionary -where the key is the address and the value is the integer contents of that -address. Any uninitialized memory address is assumed to be zero. - -Memory address -1 is a special address that contains the address of the -current instruction to execute. This is initialized to -1 and is incremented -before each instruction is executed. - -It should be noted that the instruction memory and the memory that the -program uses are entirely separate, so a program cannot modify itself. - -### Numbers - -Numbers that are used in instructions are represented in octal (base 8), and -each digit is converted to the corresponding emoji. The number is terminated -with 🙀 (`"8"`). If the number is negative, the next -emoji is 😿 (`"7"`). Otherwise, it may be terminated -with any other cat emoji. For the sake of brevity, let just use -🙀 (`"8"`) for positive numbers. For example: - -| Decimal Value | Octal Value | Emojis | Byte Code | -| ------------- | ----------- | ----------------------------------- | --------- | -| 457 | `0o711` | 😿😹😹🙀🙀 | `"71188"` | -| -345 | `-0o531` | 😽😻😹🙀😿 | `"53187"` | - -The `0o` is just a common way of represental octal values in several -programming languages like C and Python, to name a few. - -Any character needs to be represented by its ASCII (or Unicode) value. For -example, the ASCII value of `"H"` is 72 (`0o110`), so `"H"` is represented as -this: - -😹😹😸🙀🙀 (`"11088"`) - -One of the oddities of the way numbers are handled is that if there are no -more emojis to process, the number is interpreted as 1337. Why 1337? Well, all -I can figure is that this is actually a [leet code][8] representation for the -word "elite". - -### Instructions - -Unicat supports these 12 instructions: - -| Mnemonic | Arguments | Emojis | Byte Code | -| --------- | --------------------- | ------------------------------- | ------------ | -| `asgnlit` | `MEMADDR` `VALUE` | 😻😹 | `"31"` | -| `jumpif>` | `MEMADDR` `INSADDR` | 😽😿 | `"57"` | -| `echovar` | `MEMADDR` | 😽😼 | `"54"` | -| `echoval` | `MEMADDR` | 😼😼 | `"44"` | -| `pointer` | `MEMADDR` | 😼😾 | `"46"` | -| `randomb` | `MEMADDR` | 🙀😻 | `"83"` | -| `inputst` | `MEMADDR` | 😺😼 | `"24"` | -| `applop-` | `MEMADDR1` `MEMADDR2` | 😿🙀😺 | `"782"` | -| `applop*` | `MEMADDR1` `MEMADDR2` | 😿🙀🙀 | `"788"` | -| `applop/` | `MEMADDR1` `MEMADDR2` | 😿🙀😿 | `"787"` | -| `applop+` | `MEMADDR1` `MEMADDR2` | 😿🙀😸 | `"780"` (\*) | -| `diepgrm` | | 🙀🙀 | `"88"` | - -(\*) `applop+` can actually be respresented by any of the following: - -* 😿🙀😹 (`"781"`) -* 😿🙀😻 (`"783"`) -* 😿🙀😼 (`"784"`) -* 😿🙀😽 (`"785"`) -* 😿🙀😾 (`"786"`) - -However, let's just stick with what is in the above table. - -If an invalid instruction is detected, the program will just jump back to the -beginning, creating an infinite loop. This also happens if there are no more -instructions to process. - -The subsequent sections describe each of the instructions and their -corresponding arguments. - -#### `asgnlit` - -The `asgnlit` instruction stores a value to a memory address. It takes two -arguments: - -* `MEMADDR` - The memory address to store the value -* `VALUE` - The value to store - -For example, let's set memory address 14 (`0o16`) to -8 (`-0o10`): - -😻😹 😹😾🙀🙀 😹😸🙀😿 (`"31 1688 1087"`) - -Note that the spaces are just added to delineate the mnemonic from the -arguments. - -If `MEMADDR` is -1, the `VALUE` is the instruction address minus 1. This -acts like an unconditional jump to instruction address `VALUE` plus 1. - -For example, let's jump to instruction address 22 (`0o26`). Since the -`VALUE` is the instruction address minus 1, this will need to be represented -as 21 (`0o25`): - -😻😹 😹🙀😿 😺😾🙀🙀 (`"31 187 2588"`) - -#### `jumpif>` - -The `jumpif>` instruction compares a value of a memory address to zero. If it -is greater than zero, then the instruction address is changed to the specified -value. Otherwise, the instruction address goes to the next address. This acts -like a conditional jump. It takes two arguments: - -* `MEMADDR` - The memory address to compare -* `INSADDR` - The instruction address minus 1 - -For example, let's jump to instruction address 30 (`0o36`) if the value of -memory address 16 (`0o20`) is greater than 0. The instruction address needs to -be represented as 29 (`0o35`): - -😽😿 😺😸🙀🙀 😻😽🙀🙀 (`"57 2088 3588"`) - -#### `echovar` - -The `echovar` instruction outputs the value of a memory address as -ASCII/Unicode to standard out. It takes a single argument: - -* `MEMADDR` - The memory address to output as ASCII/Unicode - -For example, let's output the value of memory address 7 (`0o7`): - -😽😼 😿🙀🙀 (`"54 788"`) - -If memory address contains 117, a `u` is output since 117 is the ASCII code -for `u`. - -#### `echoval` - -The `echoval` instruction outputs the value of a memory address as digits to -standard out. It takes a single argument: - -* `MEMADDR` - The memory address to output as digits - -For example, let's output the value of memory address 6 (`0o6`): - -😼😼 😾🙀🙀 (`"44 688"`) - -If memory address contains 10, a `10` is output. - -#### `pointer` - -The `pointer` instruction treat a memory address as a pointer to second memory -address and stores the value of that memory address to the first one. It takes -a single argument: - -* `MEMADDR` - The memory address to use as a pointer - -This is best explained with a diagram: - -``` - Before After - =================== =================== - - | Memory | | | Memory | | - | Address | Value | | Address | Value | - +---------+-------+ +---------+-------+ - | 3 | 7 | --- => | 3 | 5 | - +---------+-------+ | +---------+-------+ ---> | 7 | 5 | | | 7 | 5 | -| | ---------------------------- - -``` - -In this diagram, memory address 3 contains a value of 7. The value of memory -address 7 is 5. Therefore, memory address 3 will contain 5, and memory address -7 remains unchanged. - -For the above case, the instruction would look like this: - -😼😾 😻🙀🙀 (`"46 388"`) - -#### `randomb` - -The `randomb` instruction sets a memory address to a random boolean value of -0 or 1. It takes a single argument: - -* `MEMADDR` - The memory address to store the random boolean value - -For example, let's set a random boolean value to address 14 (`0o16`): - -🙀😻 😹😾🙀🙀 (`"83 1688"`) - -#### `inputst` - -The `inputst` instruction reads a line from standard in and stores its -ASCII/Unicode value to a set of memory addresses starting at the specified -memory address. Each ASCII/Unicode value is stored in subsequent memory -addresses. Finally, a 0 value is stored in the next memory address to -null-terminate the line. It takes a single argument: - -* `MEMADDR` - The starting memory address to store the input line - -For example, let's store the input line to memory address 8 (`0o10`): - -😺😼 😹😸🙀🙀 (`"24 1088"`) - -If the input line is `"Hello"` followed by a newline (`"\n"`). This is the -result: - -* Memory address 8 = `"H"` (72) -* Memory address 9 = `"e"` (101) -* Memory address 10 = `"l"` (108) -* Memory address 11 = `"l"` (108) -* Memory address 12 = `"o"` (111) -* Memory address 13 = `"\n"` (10) -* Memory address 14 = `"\0"` (0) - -where `"\0"` is called the NUL character, which is used in other languages -like C to indicate the end of a string value. - -#### `applop` - -The `applop` instructions take two arguments: - -* `MEMADDR1` - The first memory address -* `MEMADDR2` - The second memory address - -It performs the following operation depending upon the mnemonic: - -| Mnemonic | Result | -| --------- | ----------------------------------------------------------------------------------------- | -| `applop+` | Value of `MEMADDR1` equals value of `MEMADDR1` plus value of `MEMADDR2` | -| `applop-` | Value of `MEMADDR1` equals value of `MEMADDR1` minus value of `MEMADDR2` | -| `applop*` | Value of `MEMADDR1` equals value of `MEMADDR1` times value of `MEMADDR2` | -| `applop/` | Value of `MEMADDR1` equals quotient of value of `MEMADDR1` divided by value of `MEMADDR2` | - -For example, let's set the value of memory address 9 (`0o11`) to 55 and the -value of memory address 7 (`0o7`) is 10: - -| Mnemonic | Emojis | Byte Code | Result | -| -------- | ------------------------------------------------ | --------------- | ---------------------------------------------- | -| `applop+` | 😿🙀😸 😹😹🙀🙀 😿🙀🙀 | `"780 1188 788"` | Memory address 9 value is `55 + 10 = 65` | -| `applop-` | 😿🙀😸 😹😹🙀🙀 😿🙀🙀 | `"782 1188 788"` | Memory address 9 value is `55 - 10 = 45` | -| `applop-` | 😿🙀🙀 😹😹🙀🙀 😿🙀🙀 | `"788 1188 788"` | Memory address 9 value is `55 * 10 = 550` | -| `applop-` | 😿🙀😿 😹😹🙀🙀 😿🙀🙀 | `"787 1188 788"` | Memory address 9 value is `floor(55 / 10) = 5` | - -### `diepgrm` - -The `diepgrm` instruction exits the program. It has no arguments. The program -*must* contain at least one of these somewhere, or the program will go into an -infinite loop. - -### Conclusion - -Programming in Unicat is really challenging. It feels more like programming -in machine language without the benefit of an assembler. Instead of -translating instructions into hexadecimal, you have to translate them into cat -emojis, some of which look very similar. If your editor has zoom capability, -I highly recommend using that. - -When you run your program, there is a good chance it will lock up. Here are -some of the reasons why (other than the obvious logic error): - -* You did not translate the instructions into the right emojis. -* You forgot to terminate a number with the right emojis. -* You forgot to add a `diepgrm` instruction. -* Your jump instructions are not going to the right place. - -By the way, I got tired of using python 2 and ported Unicat to python 3. I -also fixed a couple of bugs in the original python 2 implementation. The code -is available on [pypi][9], and the source code is available on [GitHub][10]. -It has some limited debugging capability which uses the python debugger to do -the heavy lifting. - -In the meantime, happy coding 😸! - -[1]: https://en.wikipedia.org/wiki/Esoteric_programming_language -[2]: https://github.com/gemdude46/unicat -[3]: https://github.com/gemdude46/unicat/blob/master/cat.py -[4]: https://www.python.org/doc/sunset-python-2/ -[5]: https://github.com/gemdude46/unicat/tree/master/examples -[6]: https://docs.python.org/2.7/library/pdb.html -[7]: https://emojipedia.org/cat-face -[8]: https://en.wikipedia.org/wiki/Leet -[9]: https://pypi.org/project/unicat-esolang/ -[10]: https://github.com/rzuckerm/unicat-esolang - - -## Articles - -There are 4 articles: - -- [Baklava in Unicat](/projects/baklava/unicat) -- [Fizz Buzz in Unicat](/projects/fizz-buzz/unicat) -- [Hello World in Unicat](/projects/hello-world/unicat) -- [Reverse String in Unicat](/projects/reverse-string/unicat) \ No newline at end of file diff --git a/docs/languages/v/index.md b/docs/languages/v/index.md deleted file mode 100644 index 4f31492db4..0000000000 --- a/docs/languages/v/index.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -date: 2023-06-17 -featured-image: programming-languages.jpg -last-modified: 2025-10-30 -layout: default -tags: -- v -title: The V Programming Language -title1: The V Programming -title2: Language ---- - - - -Welcome to the V page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 7 articles: - -- [Baklava in V](/projects/baklava/v) -- [Duplicate Character Counter in V](/projects/duplicate-character-counter/v) -- [Even Odd in V](/projects/even-odd/v) -- [Factorial in V](/projects/factorial/v) -- [Fizz Buzz in V](/projects/fizz-buzz/v) -- [Hello World in V](/projects/hello-world/v) -- [Reverse String in V](/projects/reverse-string/v) \ No newline at end of file diff --git a/docs/languages/verilog/index.md b/docs/languages/verilog/index.md deleted file mode 100644 index 833a199137..0000000000 --- a/docs/languages/verilog/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-04-27 -featured-image: programming-languages.jpg -last-modified: 2024-10-02 -layout: default -tags: -- verilog -title: The Verilog Programming Language -title1: The Verilog -title2: Programming Language ---- - - - -Welcome to the Verilog page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Verilog](/projects/baklava/verilog) -- [Hello World in Verilog](/projects/hello-world/verilog) \ No newline at end of file diff --git a/docs/languages/verve/index.md b/docs/languages/verve/index.md deleted file mode 100644 index 880ef1ecaf..0000000000 --- a/docs/languages/verve/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2021-05-24 -featured-image: programming-languages.jpg -last-modified: 2023-12-21 -layout: default -tags: -- verve -title: The Verve Programming Language -title1: The Verve Programming -title2: Language ---- - - - -Welcome to the Verve page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Verve](/projects/baklava/verve) -- [Fizz Buzz in Verve](/projects/fizz-buzz/verve) -- [Hello World in Verve](/projects/hello-world/verve) \ No newline at end of file diff --git a/docs/languages/vimscript/index.md b/docs/languages/vimscript/index.md deleted file mode 100644 index bf90a7f7cf..0000000000 --- a/docs/languages/vimscript/index.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -date: 2018-08-27 -featured-image: programming-languages.jpg -last-modified: 2024-09-26 -layout: default -tags: -- vimscript -title: The Vimscript Programming Language -title1: The Vimscript -title2: Programming Language ---- - - - -Welcome to the Vimscript page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 4 articles: - -- [Baklava in Vimscript](/projects/baklava/vimscript) -- [Fizz Buzz in Vimscript](/projects/fizz-buzz/vimscript) -- [Hello World in Vimscript](/projects/hello-world/vimscript) -- [Reverse String in Vimscript](/projects/reverse-string/vimscript) \ No newline at end of file diff --git a/docs/languages/visual-basic/index.md b/docs/languages/visual-basic/index.md deleted file mode 100644 index 7747649166..0000000000 --- a/docs/languages/visual-basic/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-05-04 -featured-image: programming-languages.jpg -last-modified: 2026-05-08 -layout: default -tags: -- visual-basic -title: The Visual Basic Programming Language -title1: The Visual Basic -title2: Programming Language ---- - - - -Welcome to the Visual Basic page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -According to [Wikipedia][1], Visual Basic .NET (VB.NET) is a programming language -that was created by Microsoft in 2001. Beyond that, Wikipedia doesn't have -much to offer in terms of historical information, so let's move on. - -In terms of features, however, Wikipedia has a little more to offer. For -instance, VB.NET is statically typed, but the type system is both strong -and weak as well as safe and unsafe. - -As for syntax, VB.NET is structured which reminds me of languages like -[Pascal][2] and [MATLAB][3] where blocks of code are marked by keywords, rather than -braces or whitespace. - -Beyond that, VB.NET has several versions. In fact, VB.NET only really refers -to the language before 2005, but the syntax is largely the same today. Of -course, I've sort of lumped them together in the same way I've recognized -Python as one language instead of two. - -[1]: https://en.wikipedia.org/wiki/Visual_Basic_(.NET) -[2]: https://en.wikipedia.org/wiki/Pascal_(programming_language) -[3]:https://en.wikipedia.org/wiki/MATLAB - - -## Articles - -There are 38 articles: - -- [Baklava in Visual Basic](/projects/baklava/visual-basic) -- [Base64 Encode Decode in Visual Basic](/projects/base64-encode-decode/visual-basic) -- [Binary Search in Visual Basic](/projects/binary-search/visual-basic) -- [Bubble Sort in Visual Basic](/projects/bubble-sort/visual-basic) -- [Capitalize in Visual Basic](/projects/capitalize/visual-basic) -- [Convex Hull in Visual Basic](/projects/convex-hull/visual-basic) -- [Depth First Search in Visual Basic](/projects/depth-first-search/visual-basic) -- [Dijkstra in Visual Basic](/projects/dijkstra/visual-basic) -- [Duplicate Character Counter in Visual Basic](/projects/duplicate-character-counter/visual-basic) -- [Even Odd in Visual Basic](/projects/even-odd/visual-basic) -- [Factorial in Visual Basic](/projects/factorial/visual-basic) -- [Fibonacci in Visual Basic](/projects/fibonacci/visual-basic) -- [File Input Output in Visual Basic](/projects/file-input-output/visual-basic) -- [Fizz Buzz in Visual Basic](/projects/fizz-buzz/visual-basic) -- [Fraction Math in Visual Basic](/projects/fraction-math/visual-basic) -- [Hello World in Visual Basic](/projects/hello-world/visual-basic) -- [Insertion Sort in Visual Basic](/projects/insertion-sort/visual-basic) -- [Job Sequencing in Visual Basic](/projects/job-sequencing/visual-basic) -- [Josephus Problem in Visual Basic](/projects/josephus-problem/visual-basic) -- [Linear Search in Visual Basic](/projects/linear-search/visual-basic) -- [Longest Common Subsequence in Visual Basic](/projects/longest-common-subsequence/visual-basic) -- [Longest Palindromic Substring in Visual Basic](/projects/longest-palindromic-substring/visual-basic) -- [Longest Word in Visual Basic](/projects/longest-word/visual-basic) -- [Maximum Array Rotation in Visual Basic](/projects/maximum-array-rotation/visual-basic) -- [Maximum Subarray in Visual Basic](/projects/maximum-subarray/visual-basic) -- [Merge Sort in Visual Basic](/projects/merge-sort/visual-basic) -- [Minimum Spanning Tree in Visual Basic](/projects/minimum-spanning-tree/visual-basic) -- [Palindromic Number in Visual Basic](/projects/palindromic-number/visual-basic) -- [Prime Number in Visual Basic](/projects/prime-number/visual-basic) -- [Quick Sort in Visual Basic](/projects/quick-sort/visual-basic) -- [Quine in Visual Basic](/projects/quine/visual-basic) -- [Remove All Whitespace in Visual Basic](/projects/remove-all-whitespace/visual-basic) -- [Reverse String in Visual Basic](/projects/reverse-string/visual-basic) -- [Roman Numeral in Visual Basic](/projects/roman-numeral/visual-basic) -- [Rot13 in Visual Basic](/projects/rot13/visual-basic) -- [Selection Sort in Visual Basic](/projects/selection-sort/visual-basic) -- [Transpose Matrix in Visual Basic](/projects/transpose-matrix/visual-basic) -- [Zeckendorf in Visual Basic](/projects/zeckendorf/visual-basic) \ No newline at end of file diff --git a/docs/languages/whitespace/index.md b/docs/languages/whitespace/index.md deleted file mode 100644 index 8ac017c9e6..0000000000 --- a/docs/languages/whitespace/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- rzuckerm -date: 2019-10-04 -featured-image: programming-languages.jpg -last-modified: 2025-04-27 -layout: default -tags: -- whitespace -title: The Whitespace Programming Language -title1: The Whitespace -title2: Programming Language ---- - - - -Welcome to the Whitespace page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- rzuckerm - -## Description - -According to [Wikipedia][1], Whitespace is an esoteric language developed by -Edwin Brady and Chris Morris in 2002 at the University of Durham. According to -the [Esolang Wiki][4], a post to Slashdot about the language was done on April -1, 2003. Most people assumed it was a joke. However, it was not. - -Unlike other languages where whitespace characters are either ignored -or used as a separator between tokens, Whitespace uses these characters as -instructions. All instructions are made up of 3 whitespace characters: - -- space (ASCII code 32) -- tab (ASCII code 9) -- linefeed (ASCII code 10), also called newline - -Everything else is ignored, so non-whitespace characters can be used -as comments or to annotate the program. A common practice is to add a letter -indicating the whitespace character before that character: - -- `S` for space -- `T` for tab -- `L` for linefeed - -For example, here is the code to output the letter `H`: - -```whitespace -S S S T S S T S S S L -T L -T L -S S -``` - -[Wikipedia][1] indicates that Whitespace is an imperative, stack-based -language. It also has a "heap", which is actually just memory storage to an -arbitrary address. There are instructions for the following: - -- Stack manipulation -- Arithmetic -- Heap access -- Flow control -- I/O - -Numbers are of arbitrary length and are represented like this: - -- Sign bit: space (`0`) for positive, tab (`1`) for negative -- Binary representation of the absolute value of the number, most-significant - bit first: space for `0`, tab for `1` -- Terminated with a linefeed - -For example, `100` (`110 0100`) would be represented as this: - -| sign | 1 | 1 | 0 | 0 | 1 | 0 | 0 | term | -| ---- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | -------- | -| space | tab | tab | space | space | tab | space | space | linefeed | - -For further information on the Whitespace language, see the -[official tutorial][2]. Since creating a Whitespace program is very tedious, -you can use a [Whitespace assembler][3] instead. - -[1]: https://en.wikipedia.org/wiki/Whitespace_(programming_language) -[2]: https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php -[3]: https://github.com/rzuckerm/whitespace-asm -[4]: https://esolangs.org/wiki/Whitespace - - -## Articles - -There are 4 articles: - -- [Baklava in Whitespace](/projects/baklava/whitespace) -- [Fizz Buzz in Whitespace](/projects/fizz-buzz/whitespace) -- [Hello World in Whitespace](/projects/hello-world/whitespace) -- [Quine in Whitespace](/projects/quine/whitespace) \ No newline at end of file diff --git a/docs/languages/wren/index.md b/docs/languages/wren/index.md deleted file mode 100644 index 155a99f580..0000000000 --- a/docs/languages/wren/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ron Zuckerman -date: 2018-04-20 -featured-image: programming-languages.jpg -last-modified: 2025-02-17 -layout: default -tags: -- wren -title: The Wren Programming Language -title1: The Wren Programming -title2: Language ---- - - - -Welcome to the Wren page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Last time we covered a relatively a relatively new language called Elm, -but it still managed to have a [Wikipedia page][1]. Our language today, Wren, -does not. As a result, I had to do a bit of digging to learn about this -language. - -According to the [GitHub page][2], Wren is a new scripting language. Of course, -there are plenty of those including [Python][3], [Lua][4], and [JavaScript][5]. So, what -makes Wren different? - -Well, according to the website, Wren was created as an object-oriented game -scripting language. Apparently, Lua is the go-to for game scripting currently, -but it's class system is pretty unnatural. Thus, Wren was born! - -In addition to filling the object-oriented game scripting niche, Wren has some -pretty sweet support for concurrency through a feature called fibers. Fibers -are lightweight threads which eliminate random context switching. In other words, -fibers generally only switch when they are told to, much like coroutines. - -Finally, Wren is incredibly fast for a scripting language. In fact, the website -shares some benchmarks which demonstrate it outperforming Python, Lua, and -JavaScript. Game developers should be pretty happy about this. - -[1]: https://en.wikipedia.org/wiki/Elm_(programming_language) -[2]: https://wren.io/ -[3]: https://en.wikipedia.org/wiki/Python_(programming_language) -[4]: https://en.wikipedia.org/wiki/Lua_(programming_language) -[5]: https://en.wikipedia.org/wiki/JavaScript - - -## Articles - -There are 11 articles: - -- [Baklava in Wren](/projects/baklava/wren) -- [Duplicate Character Counter in Wren](/projects/duplicate-character-counter/wren) -- [Even Odd in Wren](/projects/even-odd/wren) -- [Factorial in Wren](/projects/factorial/wren) -- [File Input Output in Wren](/projects/file-input-output/wren) -- [Fizz Buzz in Wren](/projects/fizz-buzz/wren) -- [Hello World in Wren](/projects/hello-world/wren) -- [Palindromic Number in Wren](/projects/palindromic-number/wren) -- [Prime Number in Wren](/projects/prime-number/wren) -- [Remove All Whitespace in Wren](/projects/remove-all-whitespace/wren) -- [Reverse String in Wren](/projects/reverse-string/wren) \ No newline at end of file diff --git a/docs/languages/wu/index.md b/docs/languages/wu/index.md deleted file mode 100644 index f87126db84..0000000000 --- a/docs/languages/wu/index.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -date: 2023-08-22 -featured-image: programming-languages.jpg -last-modified: 2025-10-31 -layout: default -tags: -- wu -title: The Wu Programming Language -title1: The Wu Programming -title2: Language ---- - - - -Welcome to the Wu page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 3 articles: - -- [Baklava in Wu](/projects/baklava/wu) -- [Fizz Buzz in Wu](/projects/fizz-buzz/wu) -- [Hello World in Wu](/projects/hello-world/wu) \ No newline at end of file diff --git a/docs/languages/wyvern/index.md b/docs/languages/wyvern/index.md deleted file mode 100644 index ca27edcb8b..0000000000 --- a/docs/languages/wyvern/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2018-06-21 -featured-image: programming-languages.jpg -last-modified: 2024-10-03 -layout: default -tags: -- wyvern -title: The Wyvern Programming Language -title1: The Wyvern -title2: Programming Language ---- - - - -Welcome to the Wyvern page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Wyvern](/projects/baklava/wyvern) -- [Hello World in Wyvern](/projects/hello-world/wyvern) \ No newline at end of file diff --git a/docs/languages/x86-64/index.md b/docs/languages/x86-64/index.md deleted file mode 100644 index 78155224f9..0000000000 --- a/docs/languages/x86-64/index.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -date: 2023-05-04 -featured-image: programming-languages.jpg -last-modified: 2026-01-06 -layout: default -tags: -- x86-64 -title: The x86-64 Programming Language -title1: The x86-64 -title2: Programming Language ---- - - - -Welcome to the x86-64 page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 7 articles: - -- [Baklava in x86-64](/projects/baklava/x86-64) -- [Dijkstra in x86-64](/projects/dijkstra/x86-64) -- [Even Odd in x86-64](/projects/even-odd/x86-64) -- [Fizz Buzz in x86-64](/projects/fizz-buzz/x86-64) -- [Hello World in x86-64](/projects/hello-world/x86-64) -- [Quine in x86-64](/projects/quine/x86-64) -- [Reverse String in x86-64](/projects/reverse-string/x86-64) \ No newline at end of file diff --git a/docs/languages/yoix/index.md b/docs/languages/yoix/index.md deleted file mode 100644 index 5e1268912b..0000000000 --- a/docs/languages/yoix/index.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -date: 2023-06-19 -featured-image: programming-languages.jpg -last-modified: 2024-10-03 -layout: default -tags: -- yoix -title: The Yoix Programming Language -title1: The Yoix Programming -title2: Language ---- - - - -Welcome to the Yoix page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 2 articles: - -- [Baklava in Yoix](/projects/baklava/yoix) -- [Hello World in Yoix](/projects/hello-world/yoix) \ No newline at end of file diff --git a/docs/languages/zig/index.md b/docs/languages/zig/index.md deleted file mode 100644 index 23a2519ae5..0000000000 --- a/docs/languages/zig/index.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -date: 2020-10-09 -featured-image: programming-languages.jpg -last-modified: 2025-03-29 -layout: default -tags: -- zig -title: The Zig Programming Language -title1: The Zig Programming -title2: Language ---- - - - -Welcome to the Zig page! Here, you'll find a description of the language as well as a list of sample programs in that language. - -## Description - -No 'Description' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## Articles - -There are 4 articles: - -- [Baklava in Zig](/projects/baklava/zig) -- [Base64 Encode Decode in Zig](/projects/base64-encode-decode/zig) -- [Fizz Buzz in Zig](/projects/fizz-buzz/zig) -- [Hello World in Zig](/projects/hello-world/zig) \ No newline at end of file diff --git a/docs/projects/baklava/ada/index.md b/docs/projects/baklava/ada/index.md deleted file mode 100644 index 8b5f5c5210..0000000000 --- a/docs/projects/baklava/ada/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Gagan Agarwal -date: 2021-10-29 -featured-image: baklava-in-every-language.jpg -last-modified: 2021-10-29 -layout: default -tags: -- ada -- baklava -title: Baklava in Ada -title1: Baklava -title2: in Ada ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; - -procedure Baklava is - M : Integer := 11; -begin - for I in 1 .. 11 loop - for J in 1 .. (M-1) loop - Put(" "); - end loop; - for K in 1 .. (2*I - 1) loop - Put("*"); - end loop; - M := M -1; - Put_Line(""); - end loop; - M:=2; - for I in reverse 1 .. 10 loop - for J in 1 .. (M-1) loop - Put(" "); - end loop; - for K in 1 .. (2*I - 1) loop - Put("*"); - end loop; - M := M + 1; - Put_Line(""); - end loop; -end Baklava; -``` - -{% endraw %} - -Baklava in [Ada](/languages/ada) was written by: - -- Gagan Agarwal - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/agda/index.md b/docs/projects/baklava/agda/index.md deleted file mode 100644 index 93cfdc2e08..0000000000 --- a/docs/projects/baklava/agda/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-20 -layout: default -tags: -- agda -- baklava -title: Baklava in Agda -title1: Baklava -title2: in Agda ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Agda](/languages/agda) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```agda --- Reference: https://rosettacode.org/wiki/FizzBuzz -module Baklava where - -open import Agda.Builtin.IO using (IO) -open import Agda.Builtin.Unit using (⊤) -open import Agda.Builtin.String using (String) -open import Data.Bool using (if_then_else_) -open import Data.List using (List; []; _∷_; map) -open import Data.Nat using (ℕ; _<ᵇ_; _∸_; _*_; zero; suc) -open import Data.Nat.Show using (show) -open import Data.String using (unlines; replicate; _++_) - -postulate putStrLn : String → IO ⊤ -{-# FOREIGN GHC import qualified Data.Text as T #-} -{-# COMPILE GHC putStrLn = putStrLn . T.unpack #-} - -range : (a b : ℕ) → List ℕ -range a zero = [] -range a (suc n) = a ∷ range (suc a) n - -baklava-line : (n : ℕ) → String -baklava-line n = (replicate num-spaces ' ') ++ (replicate num-stars '*') - where - num-spaces = if n <ᵇ 10 then 10 ∸ n else n ∸ 10 - num-stars = 21 ∸ 2 * num-spaces - -baklava : String -baklava = (unlines (map baklava-line (range 0 21))) - -main : IO ⊤ -main = putStrLn baklava - -``` - -{% endraw %} - -Baklava in [Agda](/languages/agda) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/algol60/index.md b/docs/projects/baklava/algol60/index.md deleted file mode 100644 index 144c9468ed..0000000000 --- a/docs/projects/baklava/algol60/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-04-06 -layout: default -tags: -- algol60 -- baklava -title: Baklava in ALGOL 60 -title1: Baklava in -title2: ALGOL 60 ---- - - - -Welcome to the [Baklava](/projects/baklava) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure outRepeatString(n, s); - value n; - integer n; - string s; - begin - integer i; - for i := 1 step 1 until n do outstring(1, s) - end outRepeatString; - - integer i, numspaces, numstars; - for i := -10 step 1 until 10 do - begin - numspaces := iabs(i); - numstars := 21 - 2 * numspaces; - outRepeatString(numspaces, " "); - outRepeatString(numstars, "*"); - outstring(1, "\n") - end -end - -``` - -{% endraw %} - -Baklava in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/algol68/index.md b/docs/projects/baklava/algol68/index.md deleted file mode 100644 index b4f344b368..0000000000 --- a/docs/projects/baklava/algol68/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-18 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-01-18 -layout: default -tags: -- algol68 -- baklava -title: Baklava in ALGOL 68 -title1: Baklava in -title2: ALGOL 68 ---- - - - -Welcome to the [Baklava](/projects/baklava) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -FOR n FROM -10 TO 10 -DO - INT num spaces := ABS n; - printf(($gl$, " " * num spaces + "*" * (21 - 2*num spaces))) -OD - -``` - -{% endraw %} - -Baklava in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/arkscript/index.md b/docs/projects/baklava/arkscript/index.md deleted file mode 100644 index 7b635defa1..0000000000 --- a/docs/projects/baklava/arkscript/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-20 -layout: default -tags: -- arkscript -- baklava -title: Baklava in ArkScript -title1: Baklava in -title2: ArkScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [ArkScript](/languages/arkscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```arkscript -(import std.List) -(import std.Math) -(import std.Range) -(import std.String) - -(let repeat_string - (fun (n s) - (string:join (list:fill n s) "") - ) -) - -(let baklava_line - (fun (n) { - (let num_spaces (math:abs n)) - (let num_stars (- 21 (* 2 num_spaces))) - (string:join [(repeat_string num_spaces " ") (repeat_string num_stars "*")] "") - }) -) - -(let ctr (range:range -10 11)) -(range:forEach - ctr - (fun (n) - (print (baklava_line n)) - ) -) - -``` - -{% endraw %} - -Baklava in [ArkScript](/languages/arkscript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/awk/index.md b/docs/projects/baklava/awk/index.md deleted file mode 100644 index 8c76f70e52..0000000000 --- a/docs/projects/baklava/awk/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- baklava -title: Baklava in AWK -title1: Baklava -title2: in AWK ---- - - - -Welcome to the [Baklava](/projects/baklava) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function repeat_string(n, s, result, k) { - result = "" - for (k = 1; k <= n; k++) { - result = result s - } - - return result -} - -BEGIN { - for (i = -10; i <= 10; i++) { - num_spaces = (i >= 0) ? i : -i - num_stars = 21 - 2 * num_spaces - print repeat_string(num_spaces, " ") repeat_string(num_stars, "*") - } -} - -``` - -{% endraw %} - -Baklava in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/baik/index.md b/docs/projects/baklava/baik/index.md deleted file mode 100644 index 03236ef4af..0000000000 --- a/docs/projects/baklava/baik/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-20 -layout: default -tags: -- baik -- baklava -title: Baklava in BAIK -title1: Baklava -title2: in BAIK ---- - - - -Welcome to the [Baklava](/projects/baklava) in [BAIK](/languages/baik) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```baik -# Since this language has Indonesian keywords, I figured it would be -# fun to use Indonesian variable and function names: -# -# - menangkal = counter -# - jumlah_spasi = number of spaces -# - jumlah_bintang = number of stars -# - senar = string -# - beberapa_kali = number of times -# -# References: -# - Google Translate -# - https://www.slideshare.net/slideshow/147-3411pb-baik/20917498 - -# Main function -# ------------------------------------------------- -untuk (menangkal = 0; menangkal <= 20; menangkal++) -ulang - # number of spaces = abs(counter - 10) - jumlah_spasi = menangkal - 10 - jumlah_spasi = abs jumlah_spasi - - # number of stars = 21 - 2 * number of spaces - jumlah_bintang = 21 - 2 * jumlah_spasi - - # Output number of spaces " " - senar = " " - &tulis_senar_ulangi(senar, jumlah_spasi) - - # Output number of stars "*" - senar = "*" - &tulis_senar_ulangi(senar, jumlah_bintang) - - # Output newline - tulis "\n" -lagi - -tamat -# ------------------------------------------------- - -# Output repeat string function -fungsi tulis_senar_ulangi(senar, beberapa_kali) -{ - untuk (menangkal = 1; menangkal <= beberapa_kali; menangkal++) - ulang - tulis senar - lagi -} - -``` - -{% endraw %} - -Baklava in [BAIK](/languages/baik) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/ballerina/index.md b/docs/projects/baklava/ballerina/index.md deleted file mode 100644 index 5fd4d6ee10..0000000000 --- a/docs/projects/baklava/ballerina/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-20 -layout: default -tags: -- baklava -- ballerina -title: Baklava in Ballerina -title1: Baklava in -title2: Ballerina ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Ballerina](/languages/ballerina) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ballerina -import ballerina/io; - -public function main(string... args) { - foreach int n in int:range(-10, 11, 1) { - int numSpaces = int:abs(n); - int numStars = 21 - 2 * numSpaces; - io:println("".padEnd(numSpaces, " ") + "".padEnd(numStars, "*")); - } -} - -``` - -{% endraw %} - -Baklava in [Ballerina](/languages/ballerina) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/bash/index.md b/docs/projects/baklava/bash/index.md deleted file mode 100644 index 4d7220f07f..0000000000 --- a/docs/projects/baklava/bash/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2019-03-18 -layout: default -tags: -- baklava -- bash -title: Baklava in Bash -title1: Baklava -title2: in Bash ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -for i in {0..9}; do - printf " %.0s" $(seq 1 $(( 10 - $i ))) - printf "*%.0s" $(seq 1 $(( $i * 2 + 1 ))) - echo -done - -printf "*%.0s" {1..21} -echo - -for i in {9..0}; do - printf " %.0s" $(seq 1 $(( 10 - $i ))) - printf "*%.0s" $(seq 1 $(( $i * 2 + 1 ))) - echo -done - -``` - -{% endraw %} - -Baklava in [Bash](/languages/bash) was written by: - -- Jeremy Grifski -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/batch/index.md b/docs/projects/baklava/batch/index.md deleted file mode 100644 index 876d168721..0000000000 --- a/docs/projects/baklava/batch/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-20 -layout: default -tags: -- baklava -- batch -title: Baklava in Batch -title1: Baklava -title2: in Batch ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Batch](/languages/batch) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```batch -@echo off - -rem Reference: https://rosettacode.org/wiki/Loops/For#Batch_File -SETLOCAL ENABLEDELAYEDEXPANSION - -for /l %%n in (0,1,20) do ( - rem num_spaces = abs(n - 10) - set /a "num_spaces=%%n-10" - if !num_spaces! lss 0 set /a "num_spaces=10-%%n" - - rem num_stars = 21 - 2 * num_spaces - set /a "num_stars=21-(2*!num_spaces!)" - - rem Get num_spaces " " - set "line=" - if !num_spaces! gtr 0 ( - for /l %%i in (1,1,!num_spaces!) do set "line=!line! " - ) - - rem Append num_stars "*" - for /l %%i in (1,1,!num_stars!) do set "line=!line!*" - - rem Output line - echo !line! -) - -ENDLOCAL - -``` - -{% endraw %} - -Baklava in [Batch](/languages/batch) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/beef/index.md b/docs/projects/baklava/beef/index.md deleted file mode 100644 index 299c4d6d90..0000000000 --- a/docs/projects/baklava/beef/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-14 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-01-14 -layout: default -tags: -- baklava -- beef -title: Baklava in Beef -title1: Baklava -title2: in Beef ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace Baklava; - -class Program -{ - public static int Main(String[] args) - { - for (int i in -10...10) - { - int num_spaces = Math.Abs(i); - int num_stars = 21 - 2 * num_spaces; - String line = scope String(); - line.Append(' ', num_spaces); - line.Append('*', num_stars); - Console.WriteLine(line); - } - return 0; - } -} - -``` - -{% endraw %} - -Baklava in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/befunge/index.md b/docs/projects/baklava/befunge/index.md deleted file mode 100644 index 951da0109f..0000000000 --- a/docs/projects/baklava/befunge/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Stuart Irwin -date: 2020-10-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2020-10-17 -layout: default -tags: -- baklava -- befunge -title: Baklava in Befunge -title1: Baklava in -title2: Befunge ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Befunge](/languages/befunge) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```befunge -56+0 v > 84*, v -> > : 55+\-: | :-1 < - v < < v *2 :$< - : + - > 1+ > 67*, v - 1 1 1 | :-1 < - + \ \ > $\ v -^_@^_^# `0 :-1 ,*25 < - - -``` - -{% endraw %} - -Baklava in [Befunge](/languages/befunge) was written by: - -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/boo/index.md b/docs/projects/baklava/boo/index.md deleted file mode 100644 index 2c7ee70b50..0000000000 --- a/docs/projects/baklava/boo/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-20 -layout: default -tags: -- baklava -- boo -title: Baklava in Boo -title1: Baklava -title2: in Boo ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Boo](/languages/boo) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```boo -for n in range(-10, 11): - numSpaces = System.Math.Abs(n) - numStars = 21 - 2 * numSpaces - print " " * numSpaces + "*" * numStars - -``` - -{% endraw %} - -Baklava in [Boo](/languages/boo) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/bracmat/index.md b/docs/projects/baklava/bracmat/index.md deleted file mode 100644 index bd36104e1c..0000000000 --- a/docs/projects/baklava/bracmat/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-20 -layout: default -tags: -- baklava -- bracmat -title: Baklava in Bracmat -title1: Baklava in -title2: Bracmat ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Bracmat](/languages/bracmat) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bracmat -{ -Resources: -- https://rosettacode.org/wiki/Loops/For#Bracmat -} - -{for n = -10 to 10} - -11:?n -& whl - ' ( 1+!n:<11:?n - { numspaces = abs(n) } - & abs$(!n):?numspaces - { numstars = 21 - 2 * numspaces} - & 21+-2*!numspaces:?numstars - { Output numspaces " "} - & whl'(!numspaces+-1:~<0:?numspaces&put$" ") - { Output numstars "*"} - & whl'(!numstars+-1:~<0:?numstars&put$"*") - { Output newline } - & put$\n - ) - -``` - -{% endraw %} - -Baklava in [Bracmat](/languages/bracmat) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/brainfuck/index.md b/docs/projects/baklava/brainfuck/index.md deleted file mode 100644 index d082c4230e..0000000000 --- a/docs/projects/baklava/brainfuck/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-11 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-12-11 -layout: default -tags: -- baklava -- brainfuck -title: Baklava in Brainfuck -title1: Baklava in -title2: Brainfuck ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Brainfuck](/languages/brainfuck) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```brainfuck -; Mem 1 = 7; Mem 2 = 42 (star); Mem 3 = 35; Mem 4 = 7 -+++++++ ; Mem 0 = 7 -[ - >+ ; Inc Mem 1 - >++++++ ; Add 6 to Mem 2 - >+++++ ; Add 5 to Mem 3 - >+ ; Inc Mem 4 - <<<<- ; Dec Mem 0 -] -; Mem 1 = 10 (newline); Mem 3 = 32 (space); Mem 4 = 11 ->+++ ; Add 3 to Mem 1 ->>--- ; Sub 3 from Mem 3 ->++++ ; Add 4 to Mem 4 -[ - ; Dec Mem 4 - - - ; Display Mem 4 spaces - ; Mem 5 = Mem 4 - ; Mem 6 = 21 minus 2 * Mem 4 - >>>+++++++ ; Mem 7 = 7 - [ - <+++ ; Add 3 to Mem 6 - >- ; Dec Mem 7 - ] - <<< - [ - <. ; Display space (Mem 3) - >>+ ; Inc Mem 5 - >-- ; Sub 2 from Mem 6 - <<- ; Dec Mem 4 - ] - ; Display Mem 6 stars - >> - [ - <<<<. ; Display star (Mem 2) - >>>>- ; Dec Mem 6 - ] - ; Display newline (Mem 1) - <<<<<. - ; Mem 4 = Mem 5 - >>>> - [ - <+ ; Inc Mem 4 - >- ; Dec Mem 5 - ] - < -] -; Mem 4 = 10 -++++++++++ -[ - ; Dec Mem 4 - - - ; Mem 5 = 10 minus Mem 4 - ; Mem 6 = 1 plus 2 * Mem 4 - >++++++++++ ; Mem 5 = 10 - >+ ; Mem 6 = 1 - << - [ - >- ; Dec Mem 5 - >++ ; Add 2 to Mem 6 - <<- ; Dec Mem 4 - ] - ; Display Mem 5 spaces - ; Mem 4 = 10 minus Mem 5 - ++++++++++ ; Mem 4 = 10 - > - [ - <<. ; Display Mem 3 (space) - >- ; Dec Mem 4 - >- ; Dec Mem 5 - ] - ; Display Mem 6 stars - > - [ - <<<<. ; Display Mem 2 (star) - >>>>- ; Dec Mem 6 - ] - ; Display newline (Mem 1) - <<<<<. - >>> -] - -``` - -{% endraw %} - -Baklava in [Brainfuck](/languages/brainfuck) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/c-plus-plus/index.md b/docs/projects/baklava/c-plus-plus/index.md deleted file mode 100644 index 8a6e7500da..0000000000 --- a/docs/projects/baklava/c-plus-plus/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Behnam Ahmad khan beigi -- Ștefan-Iulian Alecu -date: 2019-10-09 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- baklava -- c-plus-plus -title: Baklava in C++ -title1: Baklava -title2: in C++ ---- - - - -Welcome to the [Baklava](/projects/baklava) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -int main() { - constexpr int n = 21; - constexpr int mid = n / 2; - - for (int i : std::views::iota(-mid, mid + 1)) { - int stars = n - 2 * std::abs(i); - int spaces = std::abs(i); - - std::cout << std::string(spaces, ' ') << std::string(stars, '*') - << '\n'; - } -} -``` - -{% endraw %} - -Baklava in [C++](/languages/c-plus-plus) was written by: - -- Behnam Ahmad khan beigi -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/c-sharp/index.md b/docs/projects/baklava/c-sharp/index.md deleted file mode 100644 index 7a285e17b4..0000000000 --- a/docs/projects/baklava/c-sharp/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- baklava -- c-sharp -title: Baklava in C# -title1: Baklava -title2: in C# ---- - - - -Welcome to the [Baklava](/projects/baklava) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -const int Height = 10; -const char Symbol = '*'; - -Span stars = stackalloc char[Height * 2 + 1]; -stars.Fill(Symbol); - -static void PrintRow(int level, int height, ReadOnlySpan stars) -{ - Console.Write(new string(' ', height - level)); - Console.WriteLine(stars[..(level * 2 + 1)]); -} - -for (int i = 0; i < Height; i++) - PrintRow(i, Height, stars); - -for (int i = Height; i >= 0; i--) - PrintRow(i, Height, stars); - -``` - -{% endraw %} - -Baklava in [C#](/languages/c-sharp) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/c-star/index.md b/docs/projects/baklava/c-star/index.md deleted file mode 100644 index 3eab6faac4..0000000000 --- a/docs/projects/baklava/c-star/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-14 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-14 -layout: default -tags: -- baklava -- c-star -title: Baklava in C* -title1: Baklava -title2: in C* ---- - - - -Welcome to the [Baklava](/projects/baklava) in [C\*](/languages/c-star) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c\* -void main() -{ - for (int n in -10..11) { - int num_spaces = abs(n); - int num_stars = 21 - 2 * num_spaces; - println(" ".repeat(num_spaces) + string("*".repeat(num_stars))); - } -} - -``` - -{% endraw %} - -Baklava in [C\*](/languages/c-star) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/c/index.md b/docs/projects/baklava/c/index.md deleted file mode 100644 index 7f13ba5bae..0000000000 --- a/docs/projects/baklava/c/index.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Stuart Irwin -- Ștefan-Iulian Alecu -date: 2018-09-17 -featured-image: baklava-in-c.jpg -last-modified: 2026-05-15 -layout: default -tags: -- baklava -- c -title: Baklava in C -title1: Baklava -title2: in C ---- - - - -Welcome to the [Baklava](/projects/baklava) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include "stdio.h" - -int main(void) -{ - - for (int i = 0; i < 10; i++) - { - printf("%.*s", (10 - i), " "); - printf("%.*s", (i * 2 + 1), "******************************"); - printf("\n"); - } - - for (int i = 10; -1 < i; i--) - { - printf("%.*s", (10 - i), " "); - printf("%.*s", (i * 2 + 1), "******************************"); - printf("\n"); - } - - return 0; -} - -``` - -{% endraw %} - -Baklava in [C](/languages/c) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Stuart Irwin -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -### Header file - -```c -#include "stdio.h" -``` - -This line includes the standard input/output library. - -The program uses `printf()` from this library to display text on the screen. -Without including `stdio.h`, the compiler would not know what `printf()` is. - -### Main function - -```c -int main(void) -``` - -Every C program begins execution in `main`. - -`int` means the function returns an integer value. `void` means the function -takes no arguments. Returning 0 at the end tells the operating system the -program finished successfully. - -Everything inside the braces of `main` is executed in order. - -### Top half of diamond - -```c -for (int i = 0; i < 10; i++) -``` - -This loop generates the expanding upper half of the diamond. - -#### Anatomy of the loop - -A `for` loop has this structure: - -```c -for (initialization; condition; update) -``` - -In this program, -```c -int i = 0; -``` -creates the loop variable `i` and starts it at 0. Then, -```c -i < 10 -``` -is checked every iteration. As long as this condition is true, the loop keeps -running. -```c -i++ -``` -runs after each iteration and increases `i` by one. - -As such, `i` ranges from `0` to `9`, giving us ten rows. - -#### Printing the leading spaces - -```c -printf ("%.*s", (10 - i), " "); -``` - -This prints the padding before the stars. - -Normally, we use `%s` to print an entire string. But `%.*s` lets us specify the -maximum number of characters to print. As such, `(10 - i)` is passed as that -maximum width. - -At the beginning, `i` is 0, so ten spaces are printed. As the number of spaces -decreases, the stars move toward the center. - -#### Printing the stars - -```c -printf("%.*s", (i * 2 + 1), "******************************"); -``` - -This prints the visible stars, using the same mechanism as above. We use `i * -2 + 1` because every row adds two more stars than before, making the diamond -expand evenly. - -#### Moving to the next line - -```c -printf("\n"); -``` - -`\n` is the new line character. Without this, all output would appear on the -same line. - -### Bottom half of diamond - -```c -for (int i = 10; -1 < i; i--) -``` - -This loop creates the shrinking lower half. - -The logic is almost identical to the first loop, except now `i` decreases by one -due to `i--`. The number of spaces increases while the number of stars -decreases, producing the lower half of the diamond. - -### Program termination - -```c -return 0; -``` - -This ends the program and returns control to the operating system. A return -value of `0` conventionally means the program executed successfully. - - -## How to Run the Solution - -If we want to compile and run the program on a computer, we first need a C -compiler installed. Common choices include GCC, Clang, and Microsoft Visual -C++ (MSVC). - -Once a compiler is available, we can open a terminal in the same directory as -the source file and compile the program. - -For example, using GCC: -```sh -gcc -o baklava baklava.c -./baklava -``` -or using Clang: -```sh -clang -o baklava baklava.c -./baklava -``` -On Windows with the Microsoft compiler: -```sh -cl baklava.c -baklava.exe -``` \ No newline at end of file diff --git a/docs/projects/baklava/c2/index.md b/docs/projects/baklava/c2/index.md deleted file mode 100644 index 3f45d4c6d0..0000000000 --- a/docs/projects/baklava/c2/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-14 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-14 -layout: default -tags: -- baklava -- c2 -title: Baklava in C2 -title1: Baklava -title2: in C2 ---- - - - -Welcome to the [Baklava](/projects/baklava) in [C2](/languages/c2) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c2 -module hello_world; - -import stdio as io; -import string; - -public fn i32 main(i32 argc, char** argv) { - char[22] line; - for (u32 n = 0; n <= 20; n++) { - u32 num_spaces = (n < 10) ? (10 - n) : (n - 10); - u32 num_stars = 21 - 2 * num_spaces; - - // Fill line with num_spaces " " - string.memset(line, ' ', num_spaces); - - // Append num_stars "*" - string.memset(&line[num_spaces], '*', num_stars); - - // Null terminate line - line[num_spaces + num_stars] = '\0'; - - io.printf("%s\n", line); - } - - return 0; -} - -``` - -{% endraw %} - -Baklava in [C2](/languages/c2) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/carp/index.md b/docs/projects/baklava/carp/index.md deleted file mode 100644 index 3fa3713ee6..0000000000 --- a/docs/projects/baklava/carp/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-15 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-15 -layout: default -tags: -- baklava -- carp -title: Baklava in Carp -title1: Baklava -title2: in Carp ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Carp](/languages/carp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```carp -(defn main[] - (for [n -10 11] - (do - (let [ - num-spaces (abs n) - num-stars (- 21 (* 2 num-spaces)) - ] - (println* (String.repeat num-spaces " ") (String.repeat num-stars "*")) - ) - ) - ) -) - -``` - -{% endraw %} - -Baklava in [Carp](/languages/carp) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/chaiscript/index.md b/docs/projects/baklava/chaiscript/index.md deleted file mode 100644 index 953d27828e..0000000000 --- a/docs/projects/baklava/chaiscript/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-15 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-15 -layout: default -tags: -- baklava -- chaiscript -title: Baklava in ChaiScript -title1: Baklava in -title2: ChaiScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [ChaiScript](/languages/chaiscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```chaiscript -def repeat_string(s, n) { - var result = ""; - for (var i = 0; i < n; ++i) { - result += s; - } - - return result; -} - -for (var n = -10; n <= 10; ++n) { - var num_spaces = (n < 0) ? -n : n; - var num_stars = 21 - 2 * num_spaces; - print(repeat_string(" ", num_spaces) + repeat_string("*", num_stars)); -} - -``` - -{% endraw %} - -Baklava in [ChaiScript](/languages/chaiscript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/chapel/index.md b/docs/projects/baklava/chapel/index.md deleted file mode 100644 index e886bb5950..0000000000 --- a/docs/projects/baklava/chapel/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-15 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-15 -layout: default -tags: -- baklava -- chapel -title: Baklava in Chapel -title1: Baklava -title2: in Chapel ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Chapel](/languages/chapel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```chapel -for n in -10..10 { - var num_spaces = abs(n); - var num_stars = 21 - 2 * num_spaces; - writeln(" " * num_spaces + "*" * num_stars); -} - -``` - -{% endraw %} - -Baklava in [Chapel](/languages/chapel) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/clojure/index.md b/docs/projects/baklava/clojure/index.md deleted file mode 100644 index 72e0668a92..0000000000 --- a/docs/projects/baklava/clojure/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-15 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-15 -layout: default -tags: -- baklava -- clojure -title: Baklava in Clojure -title1: Baklava in -title2: Clojure ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Clojure](/languages/clojure) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```clojure -(ns baklava - (:gen-class) - (:require [clojure.string :refer [join]]) -) - -(defn repeat-string [n, s] - (join (repeat n s)) -) - -(defn baklava-line [n] - (def num-spaces (abs (- n 10))) - (def num-stars (- 21 (* 2 num-spaces))) - (str (repeat-string num-spaces " ") (repeat-string num-stars "*")) -) - -(defn baklava [n] - (join "\n" (map baklava-line (range 0 n))) -) - -(println (baklava 21)) - -``` - -{% endraw %} - -Baklava in [Clojure](/languages/clojure) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/cobol/index.md b/docs/projects/baklava/cobol/index.md deleted file mode 100644 index 759c502e7c..0000000000 --- a/docs/projects/baklava/cobol/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-18 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- baklava -- cobol -title: Baklava in COBOL -title1: Baklava -title2: in COBOL ---- - - - -Welcome to the [Baklava](/projects/baklava) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. baklava. - -data division. -working-storage section. - -01 max-width pic 9(2) value 21. -01 half-width pic 9(2). - -01 row pic 9(2). -01 num-spaces pic 9(2). -01 num-stars pic 9(2). - -01 space-line pic x(21) value all spaces. -01 star-line pic x(21) value all "*". - -procedure division. -main. - compute half-width = (max-width - 1) / 2 - - perform varying row from 0 by 1 until row = max-width - perform compute-line - perform render-line - end-perform - - stop run. - -compute-line. - compute num-spaces = function abs(row - half-width) - compute num-stars = max-width - (2 * num-spaces). - -render-line. - display space-line(1:num-spaces) with no advancing - display star-line(1:num-stars). - -``` - -{% endraw %} - -Baklava in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/coffeescript/index.md b/docs/projects/baklava/coffeescript/index.md deleted file mode 100644 index eaef02d184..0000000000 --- a/docs/projects/baklava/coffeescript/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Sayantan Sarkar -date: 2020-10-07 -featured-image: baklava-in-every-language.jpg -last-modified: 2020-10-07 -layout: default -tags: -- baklava -- coffeescript -title: Baklava in CoffeeScript -title1: Baklava in -title2: CoffeeScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -for i in [0...10] - pattern = " ".repeat (10 - i) - pattern += "*".repeat (i * 2 + 1) - console.log pattern - -for i in [10..0] - pattern = " ".repeat (10 - i) - pattern += "*".repeat (i * 2 + 1) - console.log pattern -``` - -{% endraw %} - -Baklava in [CoffeeScript](/languages/coffeescript) was written by: - -- Sayantan Sarkar - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/commodore-basic/index.md b/docs/projects/baklava/commodore-basic/index.md deleted file mode 100644 index 8e47841e3d..0000000000 --- a/docs/projects/baklava/commodore-basic/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- baklava -- commodore-basic -title: Baklava in Commodore BASIC -title1: Baklava in -title2: Commodore BASIC ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 FOR I = -10 TO 10 -20 NSP% = ABS(I) -30 SP$ = "" -40 IF NSP% = 0 GOTO 80 -50 FOR J = 1 TO NSP% -60 SP$ = SP$ + " " -70 NEXT J -80 ST$ = "" -90 FOR J = 1 TO 21 - 2 * NSP% -100 ST$ = ST$ + "*" -110 NEXT J -120 PRINT SP$ + ST$ -130 NEXT I - -``` - -{% endraw %} - -Baklava in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/crystal/index.md b/docs/projects/baklava/crystal/index.md deleted file mode 100644 index acb11233b6..0000000000 --- a/docs/projects/baklava/crystal/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2018-09-17 -layout: default -tags: -- baklava -- crystal -title: Baklava in Crystal -title1: Baklava in -title2: Crystal ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Crystal](/languages/crystal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```crystal -a = -1 -loop do - a += 1 - puts ((" " * (10 - a)) + ("*" * (a * 2 + 1))) - break if a == 10 -end - -b = 10 -loop do - b -= 1 - puts ((" " * (10 - b)) + ("*" * (b * 2 + 1))) - break if b == 0 -end - -``` - -{% endraw %} - -Baklava in [Crystal](/languages/crystal) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/cyclone/index.md b/docs/projects/baklava/cyclone/index.md deleted file mode 100644 index 6df5b0fd85..0000000000 --- a/docs/projects/baklava/cyclone/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-17 -layout: default -tags: -- baklava -- cyclone -title: Baklava in Cyclone -title1: Baklava in -title2: Cyclone ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Cyclone](/languages/cyclone) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cyclone -#include -#include - -int main() { - char line[22]; - - // Tell compiler that pointer math is going to be done, and the result - // may not be null terminated - char *@fat @nozeroterm line_ptr = line; - - for (int n = -10; n <= 10; n++) { - int num_spaces = (n >= 0) ? n : -n; - int num_stars = 21 - 2 * num_spaces; - - // Write num_spaces " " to line - memset(line_ptr, ' ', num_spaces); - - // Append num_stars "*" to line - memset(&line_ptr[num_spaces], '*', num_stars); - - // Null terminate line - line_ptr[num_spaces + num_stars] = '\0'; - - printf("%s\n", line); - } - - return 0; -} - -``` - -{% endraw %} - -Baklava in [Cyclone](/languages/cyclone) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/cython/index.md b/docs/projects/baklava/cython/index.md deleted file mode 100644 index 5cc23d8ad7..0000000000 --- a/docs/projects/baklava/cython/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-31 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-10-31 -layout: default -tags: -- baklava -- cython -title: Baklava in Cython -title1: Baklava -title2: in Cython ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Cython](/languages/cython) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cython -from libc.stdio cimport printf - - -cdef main(): - cdef int n - cdef int num_spaces - cdef int num_stars - cdef bytes buffer - for n in range(-10, 11): - num_spaces = abs(n) - num_stars = 21 - 2 * num_spaces - buffer = b" " * num_spaces + b"*" * num_stars - printf(b"%s\n", buffer) - - -if __name__ == "__main__": - main() - -``` - -{% endraw %} - -Baklava in [Cython](/languages/cython) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/d/index.md b/docs/projects/baklava/d/index.md deleted file mode 100644 index 0f1b1dfc5e..0000000000 --- a/docs/projects/baklava/d/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2018-09-17 -layout: default -tags: -- baklava -- d -title: Baklava in D -title1: Baklava -title2: in D ---- - - - -Welcome to the [Baklava](/projects/baklava) in [D](/languages/d) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```d -import std.stdio, std.array; - -void main (string[ ] args) -{ - - for (byte i = 0; i < 10; i++) - writeln ( - " ".replicate (10 - i), "*".replicate (i * 2 + 1) - ); - - for (byte i = 10; -1 < i; i--) - writeln ( - " ".replicate (10 - i), "*".replicate (i * 2 + 1) - ); - -} - -``` - -{% endraw %} - -Baklava in [D](/languages/d) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/dale/index.md b/docs/projects/baklava/dale/index.md deleted file mode 100644 index 1b22dcdd0d..0000000000 --- a/docs/projects/baklava/dale/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-13 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-13 -layout: default -tags: -- baklava -- dale -title: Baklava in Dale -title1: Baklava -title2: in Dale ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Dale](/languages/dale) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dale -(import cstdio) -(import stdlib) -(import cmath) -(import cstring) - -(def main (fn extern-c int (void) - (def n (var auto int)) - (def num-spaces (var auto int)) - (def num-stars (var auto int)) - (def line (var auto (array-of 22 char))) - - (for (setv n -10) (<= n 10) (incv n) - (do - (setv num-spaces (abs n)) - (setv num-stars (- 21 (* 2 num-spaces))) - - ; Fill line with num-spaces " " - (memset (cast line (p void)) #\SPACE num-spaces) - - ; Append num-stars "*" to line - (memset (cast ($ line num-spaces) (p void)) #\* num-stars) - - ; Null terminate line - (setf ($ line (+ num-spaces num-stars)) #\NULL) - - (printf "%s\n" line) - ) - ) -)) - -``` - -{% endraw %} - -Baklava in [Dale](/languages/dale) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/dart/index.md b/docs/projects/baklava/dart/index.md deleted file mode 100644 index bb238f6092..0000000000 --- a/docs/projects/baklava/dart/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Paddy -date: 2019-10-21 -featured-image: baklava-in-every-language.jpg -last-modified: 2019-10-21 -layout: default -tags: -- baklava -- dart -title: Baklava in Dart -title1: Baklava -title2: in Dart ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -main() { - for (var i = 0; i < 10; i++) { - print(" " * (10 - i) + "*" * (i * 2 + 1)); - } - for (var i = 10; 0 <= i; i--) { - print(" " * (10 - i) + "*" * (i * 2 + 1)); - } -} - -``` - -{% endraw %} - -Baklava in [Dart](/languages/dart) was written by: - -- Paddy - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/dg/index.md b/docs/projects/baklava/dg/index.md deleted file mode 100644 index be501ff0d2..0000000000 --- a/docs/projects/baklava/dg/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-13 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-13 -layout: default -tags: -- baklava -- dg -title: Baklava in Dg -title1: Baklava -title2: in Dg ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Dg](/languages/dg) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dg -for n in range -10 11 => - num_spaces = abs n - line = (" " * num_spaces) + ("*" * (21 - 2 * num_spaces)) - print line - -``` - -{% endraw %} - -Baklava in [Dg](/languages/dg) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/discus/index.md b/docs/projects/baklava/discus/index.md deleted file mode 100644 index 2c233c4625..0000000000 --- a/docs/projects/baklava/discus/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-14 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-14 -layout: default -tags: -- baklava -- discus -title: Baklava in Discus -title1: Baklava -title2: in Discus ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Discus](/languages/discus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```discus -module Main -import System.IO.Console -import Data.List -import Data.Text.List - -where - -baklavaLine (n: Nat): Text - = (textOfCharList (replicate num_spaces ' ')) % (textOfCharList (replicate num_stars '*')) - where - num_spaces = if n > 10 then n - 10 else 10 -n - num_stars = 21 - 2 * num_spaces - -main () - = forS (enumFromTo 0 20) $ λn - -> writel $ baklavaLine n - -``` - -{% endraw %} - -Baklava in [Discus](/languages/discus) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/dusk/index.md b/docs/projects/baklava/dusk/index.md deleted file mode 100644 index 7caaab6b42..0000000000 --- a/docs/projects/baklava/dusk/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-14 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-14 -layout: default -tags: -- baklava -- dusk -title: Baklava in Dusk -title1: Baklava -title2: in Dusk ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Dusk](/languages/dusk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dusk -let repeat_string = |s, n| join(alloc(n, s), '') - -let n = -10 -while n < 11 { - let num_spaces = n - if num_spaces < 0: num_spaces = -num_spaces - let num_stars = 21 - 2 * num_spaces - n += 1 - println(repeat_string(' ', num_spaces) + repeat_string('*', num_stars)) -} - -``` - -{% endraw %} - -Baklava in [Dusk](/languages/dusk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/egison/index.md b/docs/projects/baklava/egison/index.md deleted file mode 100644 index 8c3a142c76..0000000000 --- a/docs/projects/baklava/egison/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-08 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-08 -layout: default -tags: -- baklava -- egison -title: Baklava in Egison -title1: Baklava -title2: in Egison ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Egison](/languages/egison) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```egison -def stringRepeat s n := - (S.concat (take n (repeat1 s))) - -def baklavaLine n := - let numSpaces := abs (n - 10) - numStars := 21 - 2 * numSpaces in - (S.concat [(stringRepeat " " numSpaces), (stringRepeat "*" numStars), "\n"]) - -def baklava n := - (S.concat (map baklavaLine [0..n])) - -def main args := do - write (baklava 20) - -``` - -{% endraw %} - -Baklava in [Egison](/languages/egison) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/eiffel/index.md b/docs/projects/baklava/eiffel/index.md deleted file mode 100644 index 6ad301ce2c..0000000000 --- a/docs/projects/baklava/eiffel/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-08 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-08 -layout: default -tags: -- baklava -- eiffel -title: Baklava in Eiffel -title1: Baklava -title2: in Eiffel ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Eiffel](/languages/eiffel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```eiffel -class - baklava - -create - make - -feature - - make - local - num_spaces: INTEGER - num_stars: INTEGER - do - across - -10 |..| 10 as n - loop - num_spaces := n.item.abs - num_stars := 21 - 2 * num_spaces - print (repeat_string(" ", num_spaces) + repeat_string("*", num_stars) + "%N") - end - end - - repeat_string(s: STRING; n: INTEGER): STRING - do - Result := "" - across - 1 |..| n as x - loop - Result := Result + s - end - end -end - -``` - -{% endraw %} - -Baklava in [Eiffel](/languages/eiffel) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/elena/index.md b/docs/projects/baklava/elena/index.md deleted file mode 100644 index c36d811d29..0000000000 --- a/docs/projects/baklava/elena/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-13 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-09-25 -layout: default -tags: -- baklava -- elena -title: Baklava in Elena -title1: Baklava -title2: in Elena ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Elena](/languages/elena) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elena -import extensions; -import extensions'text; -import extensions'math; - -public program() -{ - int space := " ".toChar(); - int star := "*".toChar(); - for (int n := -10; n <= 10; n++) { - int num_spaces := abs(n); - int num_stars := 21 - 2 * num_spaces; - console.writeLine(String.fill(num_spaces, space) + String.fill(num_stars, star)); - } -} - -``` - -{% endraw %} - -Baklava in [Elena](/languages/elena) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/elixir/index.md b/docs/projects/baklava/elixir/index.md deleted file mode 100644 index 02692a8da2..0000000000 --- a/docs/projects/baklava/elixir/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Oleksii Filonenko -date: 2019-05-22 -featured-image: baklava-in-every-language.jpg -last-modified: 2019-05-22 -layout: default -tags: -- baklava -- elixir -title: Baklava in Elixir -title1: Baklava -title2: in Elixir ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Elixir](/languages/elixir) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elixir -defmodule Baklava do - @doc """ - Create baklava where the top has 10 spaces and then 1 asterisk. - """ - @spec baklava() :: String.t() - def baklava, do: baklava_grow(10, 1) - - @doc """ - Recursively grow the baklava until spaces <= zero. - """ - @spec baklava_grow(spaces :: integer, asterisks :: integer) :: String.t() - def baklava_grow(spaces, asterisks) when spaces <= 0 do - line(0, asterisks) <> "\n" <> baklava_shrink(1, asterisks - 2) - end - - def baklava_grow(spaces, asterisks) do - line(spaces, asterisks) <> "\n" <> baklava_grow(spaces - 1, asterisks + 2) - end - - @doc """ - Recursively shrink the baklava until asterisks <= zero. - """ - @spec baklava_shrink(spaces :: integer, asterisks :: integer) :: String.t() - def baklava_shrink(spaces, asterisks) when asterisks <= 1, do: line(spaces, 1) - - def baklava_shrink(spaces, asterisks) do - line(spaces, asterisks) <> "\n" <> baklava_shrink(spaces + 1, asterisks - 2) - end - - @doc """ - Return a single line of the baklava. - """ - @spec line(spaces :: integer, asterisks :: integer) :: String.t() - def line(spaces, asterisks) do - String.duplicate(" ", spaces) <> String.duplicate("*", asterisks) - end -end - -Baklava.baklava() |> IO.puts() - -``` - -{% endraw %} - -Baklava in [Elixir](/languages/elixir) was written by: - -- Oleksii Filonenko - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/elvish/index.md b/docs/projects/baklava/elvish/index.md deleted file mode 100644 index 4f6578079b..0000000000 --- a/docs/projects/baklava/elvish/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-07 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-07 -layout: default -tags: -- baklava -- elvish -title: Baklava in Elvish -title1: Baklava -title2: in Elvish ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -# By github.com/Kaamkiya - -for i [(range 11) (range 9 -1)] { - var line = '' - - range (- 10 $i) | each { |_| set line = $line' '} - range (+ 1 (* 2 $i)) | each { |_| set line = $line'*' } - - echo $line -} - -``` - -{% endraw %} - -Baklava in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/emojicode/index.md b/docs/projects/baklava/emojicode/index.md deleted file mode 100644 index 0289586782..0000000000 --- a/docs/projects/baklava/emojicode/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-13 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-13 -layout: default -tags: -- baklava -- emojicode -title: Baklava in Emojicode -title1: Baklava in -title2: Emojicode ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Emojicode](/languages/emojicode) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```emojicode -🏁 🍇 - 💭 Repeat a string - 🍇 str 🔡 count 🔢 ➡️ 🔡 - 💭 result = "" - 🖍🆕 result 🔡 - 🔤🔤 ➡️ 🖍 result - 💭 for i = 0 to count - 1: - 🔂 i 🆕⏩ 0 count❗️ 🍇 - 💭 result += str - 🔤🧲result🧲🧲str🧲🔤 ➡️ 🖍 result - 🍉 - ↩️ result - 🍉 ➡️ repeat_string - - 💭 for n = -10 to 10: - 🔂 n 🆕⏩ -10 11❗️ 🍇 - 💭 num_spaces = abs(n) - n ➡️ 🖍🆕num_spaces - ↪️ n ◀️ 0 🍇 - num_spaces ⬅️ ✖️ -1 - 🍉 - 💭 num_stars = 21 - 2 * num_spaces - 21 ➖ 2 ✖️ num_spaces ➡️ num_stars - 💭 Output num_spaces " ", num_stars "*" - ⁉️repeat_string 🔤 🔤 num_spaces❗️➡️ spaces - ⁉️repeat_string 🔤*🔤 num_stars❗️➡️ stars - 😀 🔤🧲spaces🧲🧲stars🧲🔤 ❗️ - 🍉 -🍉 - -``` - -{% endraw %} - -Baklava in [Emojicode](/languages/emojicode) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/erlang/index.md b/docs/projects/baklava/erlang/index.md deleted file mode 100644 index 2cb0960474..0000000000 --- a/docs/projects/baklava/erlang/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- Mark Magahis -- rzuckerm -date: 2019-10-04 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-11-21 -layout: default -tags: -- baklava -- erlang -title: Baklava in Erlang -title1: Baklava -title2: in Erlang ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Erlang](/languages/erlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```erlang --module(baklava). --export([main/1]). - --spec baklava(MaxWidth :: integer(), - Incrementor :: integer()) -> ok. -%%-------------------------------------------------------------------- -%% Recursively prints the top half of the baklava -%%-------------------------------------------------------------------- -baklava(MaxWidth, MaxWidth) -> - print((MaxWidth*2)+1, star), - reverse_baklava(MaxWidth, MaxWidth-1); -baklava(MaxWidth, Incrementor) -> - print(MaxWidth-Incrementor, space), - print((Incrementor*2)+1, star), - baklava(MaxWidth, Incrementor+1). - --spec reverse_baklava(MaxWidth :: integer(), - Decrementor :: integer()) -> ok. -%%-------------------------------------------------------------------- -%% Recursively prints the bottom half of the baklava -%%-------------------------------------------------------------------- -reverse_baklava(MaxWidth, 0) -> - print(MaxWidth, space), - print(1, star); -reverse_baklava(MaxWidth, Decrementor) -> - print(MaxWidth-Decrementor, space), - print((Decrementor*2)+1, star), - reverse_baklava(MaxWidth, Decrementor-1). - --spec print(Number :: integer(), - Type :: star | space) -> ok. -%%-------------------------------------------------------------------- -%% Recursively prints the specified Number of stars or spaces -%%-------------------------------------------------------------------- -main(_) -> - baklava(10, 0). - -print(0,star) -> - io:format("~n"); -print(0,_) -> - ok; -print(N, space) -> - io:format(" "), - print(N-1, space); -print(N, star) -> - io:format("*"), - print(N-1, star). - -``` - -{% endraw %} - -Baklava in [Erlang](/languages/erlang) was written by: - -- Mark Magahis -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/eta/index.md b/docs/projects/baklava/eta/index.md deleted file mode 100644 index 3974e9d9e7..0000000000 --- a/docs/projects/baklava/eta/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-13 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-13 -layout: default -tags: -- baklava -- eta -title: Baklava in Eta -title1: Baklava -title2: in Eta ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Eta](/languages/eta) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```eta -module Main where - -baklavaLine :: Int -> String -baklavaLine n = (replicate numSpaces ' ') ++ (replicate numStars '*') ++ "\n" - where - numSpaces = abs(n - 10) - numStars = 21 - 2 * numSpaces - -baklava :: String -> Int -> String -baklava s 0 = s ++ baklavaLine 0 -baklava s n = s ++ baklavaLine n ++ baklava s (n - 1) - -main :: IO () -main = putStr (baklava "" 20) - -``` - -{% endraw %} - -Baklava in [Eta](/languages/eta) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/euphoria/index.md b/docs/projects/baklava/euphoria/index.md deleted file mode 100644 index 5206684bce..0000000000 --- a/docs/projects/baklava/euphoria/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-16 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-02-16 -layout: default -tags: -- baklava -- euphoria -title: Baklava in Euphoria -title1: Baklava in -title2: Euphoria ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/math.e - -for n = -10 to 10 -do - integer num_spaces = abs(n) - integer num_stars = 21 - 2 * num_spaces - printf(STDOUT, "%s%s\n", {repeat(' ', num_spaces), repeat('*', num_stars)}) -end for - -``` - -{% endraw %} - -Baklava in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/f-sharp/index.md b/docs/projects/baklava/f-sharp/index.md deleted file mode 100644 index 91de1b1fe0..0000000000 --- a/docs/projects/baklava/f-sharp/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2019-09-12 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-04-05 -layout: default -tags: -- baklava -- f-sharp -title: Baklava in F# -title1: Baklava -title2: in F# ---- - - - -Welcome to the [Baklava](/projects/baklava) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -let inline repeat count (char: char) = String(char, count) - -let baklava size = - { -size .. size } - |> Seq.map (fun y -> - let padding = abs y - repeat padding ' ' + repeat (2 * (size - padding) + 1) '*') - |> String.concat Environment.NewLine - -[] -let main argv = - baklava 10 |> printfn "%s" - 0 - -``` - -{% endraw %} - -Baklava in [F#](/languages/f-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/f-star/index.md b/docs/projects/baklava/f-star/index.md deleted file mode 100644 index 4fa2236024..0000000000 --- a/docs/projects/baklava/f-star/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- f-star -title: Baklava in F* -title1: Baklava -title2: in F* ---- - - - -Welcome to the [Baklava](/projects/baklava) in [F\*](/languages/f-star) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f\* -module Baklava - -open FStar.IO -open FStar.Math.Lib -open FStar.Mul - -let baklava_line (n:nat {n <= 20}) : string = - let num_spaces:nat = (abs (n - 10)) in - let num_stars:nat = 21 - 2 * num_spaces in - (String.make num_spaces ' ') ^ (String.make num_stars '*') ^ "\n" - -let rec baklava (lines:string) (n:nat {n <= 20}) : string = - match n with - | 0 -> lines ^ (baklava_line 0) - | _ -> lines ^ (baklava_line n) ^ (baklava lines (n - 1)) - -let main = print_string (baklava "" 20) - -``` - -{% endraw %} - -Baklava in [F\*](/languages/f-star) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/factor/index.md b/docs/projects/baklava/factor/index.md deleted file mode 100644 index 4f8ad0c9f6..0000000000 --- a/docs/projects/baklava/factor/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- factor -title: Baklava in Factor -title1: Baklava -title2: in Factor ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Factor](/languages/factor) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```factor -USING: io kernel math prettyprint ranges sequences ; -IN: baklava - -! Based on https://rosettacode.org/wiki/Repeat_a_string#Factor -! but reversed arguments for fewer operations -: repeat-string ( n str -- str' ) concat ; - -: baklava-line ( n -- str ) - 10 - abs ! stack: num-spaces = abs(n - 10) - dup ! stack: num-spaces, num-spaces - " " ! stack: num-spaces, num-spaces, " " - repeat-string ! stack: num-spaces, spaces = " " num-spaces times - swap ! stack: spaces, num-spaces - -2 * 21 + ! stack: spaces, num-stars = 21 - 2 * num-spaces - "*" ! stack: spaces, num-stars, "*" - repeat-string ! stack: spaces, stars = "*" num-stars times - append ! stack: spaces + stars - ; - -! For n = 0 to 20, output Baklava line n -20 [0..b] [ baklava-line print ] each - -``` - -{% endraw %} - -Baklava in [Factor](/languages/factor) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/felix/index.md b/docs/projects/baklava/felix/index.md deleted file mode 100644 index 32d68d9d50..0000000000 --- a/docs/projects/baklava/felix/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- felix -title: Baklava in Felix -title1: Baklava -title2: in Felix ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Felix](/languages/felix) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```felix -for i in -10..10 do - var num_spaces = abs(i); - var num_stars = 21 - 2 * num_spaces; - println$ " " * num_spaces + "*" * num_stars; -done - -``` - -{% endraw %} - -Baklava in [Felix](/languages/felix) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/fennel/index.md b/docs/projects/baklava/fennel/index.md deleted file mode 100644 index c145fde7c5..0000000000 --- a/docs/projects/baklava/fennel/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- fennel -title: Baklava in Fennel -title1: Baklava -title2: in Fennel ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Fennel](/languages/fennel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fennel -(for [i -10 10] - (let [ - num-spaces (math.abs i) - num-stars (- 21 (* 2 num-spaces)) - ] - (print (.. (string.rep " " num-spaces) (string.rep "*" num-stars))) - ) -) - -``` - -{% endraw %} - -Baklava in [Fennel](/languages/fennel) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/ferret/index.md b/docs/projects/baklava/ferret/index.md deleted file mode 100644 index b190bb9621..0000000000 --- a/docs/projects/baklava/ferret/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- ferret -title: Baklava in Ferret -title1: Baklava -title2: in Ferret ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Ferret](/languages/ferret) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ferret -(defn print-repeat-string - ([s n] - (if (> n 0) - (do - (print s) - (print-repeat-string s (dec n)) - ) - ) - ) -) - -(defn baklava-line - ([n] - (let [ - num-spaces (abs n) - num-stars (- 21 (* 2 num-spaces)) - ] - (print-repeat-string " " num-spaces) - (print-repeat-string "*" num-stars) - (println) - ) - ) -) - -(defn baklava - ([n ne] - (if (<= n ne) - (do - (baklava-line n) - (baklava (inc n) ne) - ) - ) - ) -) - -(do - (baklava -10 10) -) - -``` - -{% endraw %} - -Baklava in [Ferret](/languages/ferret) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/fetlang/index.md b/docs/projects/baklava/fetlang/index.md deleted file mode 100644 index b6e055d8ce..0000000000 --- a/docs/projects/baklava/fetlang/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- fetlang -title: Baklava in Fetlang -title1: Baklava in -title2: Fetlang ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Fetlang](/languages/fetlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fetlang -worship Zera (0 * 1) -spank Nora ten times (0 - 10) -lick Enzo eleven times (0 + 11) - -(while Nora < Enzo) -while Nora is submissive to Enzo - (Spencer = number of spaces = abs(Nora)) - if Nora is submissive to Zera - have Nora spank Spencer (0 - Nora) - otherwise - have Nora lick Spencer (0 + Nora) - - (Starr = number of stars = 21 - 2 * Spencer) - lick Starr twenty one times (0 + 21) - have Spencer spank Starr (21 - Spencer) - have Spencer spank Starr (21 - 2 * Spencer) - - (Output " " Spencer times - Note: Spencer will be zero when this loop exits) - while Spencer is dominant towards Zera - make slave moan " " - spank Spencer - - (Output "*" Starr times - Note: Starr will be zero when this loop exits) - while Starr is dominant towards Zera - make slave moan "*" - spank Starr - - (Output newline) - make slave scream - - (Increment Nora) - lick Nora - -``` - -{% endraw %} - -Baklava in [Fetlang](/languages/fetlang) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/flix/index.md b/docs/projects/baklava/flix/index.md deleted file mode 100644 index 0967210790..0000000000 --- a/docs/projects/baklava/flix/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- flix -title: Baklava in Flix -title1: Baklava -title2: in Flix ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Flix](/languages/flix) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```flix -def baklavaLine(n: Int32): String = - let numSpaces = Int32.abs(n); - let numStars = 21 - 2 * numSpaces; - String.repeat(numSpaces, " ") + String.repeat(numStars, "*") - -def main(): Unit \ IO = - List.range(-10, 11) |> - List.map(baklavaLine) |> - List.forEach(println) - -``` - -{% endraw %} - -Baklava in [Flix](/languages/flix) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/formality/index.md b/docs/projects/baklava/formality/index.md deleted file mode 100644 index b826df8ed4..0000000000 --- a/docs/projects/baklava/formality/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- formality -title: Baklava in Formality -title1: Baklava in -title2: Formality ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Formality](/languages/formality) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```formality -baklavaLine(n: Nat): String - let numSpaces = if Nat.gte(n, 10) then Nat.sub(n, 10) else Nat.sub(10, n) - let numStars = Nat.sub(21, Nat.mul(2, numSpaces)) - String.repeat(" ", numSpaces) | String.repeat("*", numStars) | "\n" - -baklava(lines: String, n:Nat): String - case n { - zero: lines | baklavaLine(0), - succ: lines | baklavaLine(n) | baklava(lines, n.pred) - } - -Main: IO(Unit) - do IO { - IO.put_string(baklava("", 20)) - } - -``` - -{% endraw %} - -Baklava in [Formality](/languages/formality) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/forth/index.md b/docs/projects/baklava/forth/index.md deleted file mode 100644 index 6851c68261..0000000000 --- a/docs/projects/baklava/forth/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- forth -title: Baklava in Forth -title1: Baklava -title2: in Forth ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Forth](/languages/forth) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```forth -: baklava - ( for counter = -10 to 10 ) - 11 -10 do - i \ put outermost loop index on the stack - abs \ num-spaces = abs(counter) - dup spaces \ output num-spaces " " - -2 * 21 + \ num-stars = 21 - 2 * num-spaces - 0 do [char] * emit loop \ for inner-counter = 0 to num-stars - 1, output "*" - \ Source: https://rosettacode.org/wiki/Loops/For#Forth - cr - loop ; - -baklava -bye - -``` - -{% endraw %} - -Baklava in [Forth](/languages/forth) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/fortran/index.md b/docs/projects/baklava/fortran/index.md deleted file mode 100644 index 57ae879ed7..0000000000 --- a/docs/projects/baklava/fortran/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-15 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-10-15 -layout: default -tags: -- baklava -- fortran -title: Baklava in Fortran -title1: Baklava in -title2: Fortran ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program baklava - implicit none - integer :: i, size, spaces, stars - - parameter (size = 10) - - do i = 0, size - spaces = size - i - stars = i * 2 + 1 - print '(A)', repeat(' ', spaces)//repeat('*', stars) - end do - - do i = size-1, 0, -1 - spaces = size - i - stars = i * 2 + 1 - print '(A)', repeat(' ', spaces)//repeat('*', stars) - end do -end program baklava - -``` - -{% endraw %} - -Baklava in [Fortran](/languages/fortran) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/frege/index.md b/docs/projects/baklava/frege/index.md deleted file mode 100644 index 13784f572e..0000000000 --- a/docs/projects/baklava/frege/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-06 -layout: default -tags: -- baklava -- frege -title: Baklava in Frege -title1: Baklava -title2: in Frege ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Frege](/languages/frege) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```frege -module Baklava where - -main :: IO () -main = putStr (baklava "" 20) - -baklava :: String -> Int -> String -baklava s n - | n < 0 = "" - | otherwise = s ++ baklavaLine n ++ baklava s (n - 1) - -baklavaLine :: Int -> String -baklavaLine n = do - let num_spaces = abs (n - 10) - let num_stars = 21 - 2 * num_spaces - packed (replicate num_spaces ' ') ++ packed (replicate num_stars '*') ++ "\n" - -``` - -{% endraw %} - -Baklava in [Frege](/languages/frege) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/gerbil/index.md b/docs/projects/baklava/gerbil/index.md deleted file mode 100644 index 7517bf2ace..0000000000 --- a/docs/projects/baklava/gerbil/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- gerbil -title: Baklava in Gerbil -title1: Baklava -title2: in Gerbil ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Gerbil](/languages/gerbil) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gerbil -(import :std/iter) -(import :std/misc/func) - -(export main) - -(def (string-repeat n str) - (string-join (repeat str n) "") -) - -(def (main . args) - (for (i (in-range -10 11)) - (def num-spaces (abs i)) - (def num-stars (- 21 (* 2 num-spaces))) - (displayln (string-repeat num-spaces " ") (string-repeat num-stars "*")) - ) -) - -``` - -{% endraw %} - -Baklava in [Gerbil](/languages/gerbil) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/gluon/index.md b/docs/projects/baklava/gluon/index.md deleted file mode 100644 index 05e0ceb371..0000000000 --- a/docs/projects/baklava/gluon/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- gluon -title: Baklava in Gluon -title1: Baklava -title2: in Gluon ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Gluon](/languages/gluon) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gluon -let io @ { ? } = import! std.io -let int @ { ? } = import! std.int - -rec let repeat_string s n : String -> Int -> String = - if n > 0 then - s ++ (repeat_string s (n - 1)) - else - "" - -let baklava_line n : Int -> String = - let num_spaces = int.abs n - let num_stars = 21 - 2 * num_spaces - (repeat_string " " num_spaces) ++ (repeat_string "*" num_stars) - -rec let baklava n ne : Int -> Int -> io.IO () = - if n <= ne then - io.println (baklava_line n) - baklava (n + 1) ne - else - io.print "" - -baklava -10 10 - -``` - -{% endraw %} - -Baklava in [Gluon](/languages/gluon) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/gnu-make/index.md b/docs/projects/baklava/gnu-make/index.md deleted file mode 100644 index ae213f8552..0000000000 --- a/docs/projects/baklava/gnu-make/index.md +++ /dev/null @@ -1,479 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-07-13 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-08-23 -layout: default -tags: -- baklava -- gnu-make -title: Baklava in GNU Make -title1: Baklava in -title2: GNU Make ---- - - - -Welcome to the [Baklava](/projects/baklava) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -# Constants -EMPTY := -SPACE := $(EMPTY) $(EMPTY) -STAR := * - -# Numbers are represented as x's so that they can be manipulated with text functions. -# This idea is based on how the GNU Make Standard Library (https://github.com/jgrahamc/gmsl) -# handles numbers. -ONE := x -TWO := x x -TEN := $(TWO) $(TWO) $(TWO) $(TWO) $(TWO) - -# Increment function -# Arg 1: Number encoded as x's -# Return: Number + 1 encoded as x's -INC = $(strip $(1) $(ONE)) - -# Decrement function -# Arg 1: Number encoded as x's -# Return: max(Number - 1, 0) encoded as x's -DEC = $(wordlist 2,$(words $(1)),$1) - -# Add function -# Arg 1: Number 1 encoded as x's -# Arg 2: Number 2 encoded as x's -# Return: Number 1 + Number 2 encoded as x's -ADD = $(strip $(1) $(2)) - -# Subtract function -# Arg 1: Number 1 encoded as x's -# Arg 2: Number 2 encoded as x's -# Return: Max(Number 1 - Number 2, 0) encoded as x's -SUB = $(wordlist $(words $(call INC,$(2))),$(words $(1)),$(1)) - -# Repeat function -# Arg 1: Character -# Arg 2: Number of repeats encoded as x's -# Return: Character repeated specified number of times -REPEAT = $(subst $(1)$(SPACE),$(1),$(foreach _,$(2),$(1))) - -# Baklava line function -# Arg 1: Number of spaces encoded as x's -# Arg 2: Number of stars encoded as x's -# Return: Specified number of spaces followed by specified number of stars -BAKLAVA_LINE = $(call REPEAT,$(SPACE),$(1))$(call REPEAT,$(STAR),$(2)) - -# Baklava upper loop -# -# Output upper portion of Bakalava -# -# Arg 1: Starting number of spaces encoded as x's -# Arg 2: Starting number of stars encoded as x's -define UPPER_BAKLAVA_LOOP -$(info $(call BAKLAVA_LINE,$(1),$(2))) -$(if $(1),$(call UPPER_BAKLAVA_LOOP,$(call DEC,$(1)),$(call ADD,$(2),$(TWO)))) -endef - -# Baklava lower loop -# -# Output lower portion of Baklava -# Arg 1: Starting number of spaces encoded as x's -# Arg 2: Starting number of stars encoded as x's -define LOWER_BAKLAVA_LOOP -$(if $(2),\ - $(info $(call BAKLAVA_LINE,$(1),$(2)))\ - $(call LOWER_BAKLAVA_LOOP,$(call INC,$(1)),$(call SUB,$(2),$(TWO)))\ -) -endef - -# Run Bakalava loops -$(call UPPER_BAKLAVA_LOOP,$(TEN),$(ONE)) -$(call LOWER_BAKLAVA_LOOP,$(ONE),$(call DEC,$(call ADD,$(TEN),$(TEN)))) - -.PHONY: all -all: ;@: - -``` - -{% endraw %} - -Baklava in [GNU Make](/languages/gnu-make) was written by: - -- rzuckerm - -This article was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -### Introduction - -GNU Make is not a language that has much support for numerical operations. -Instead, numbers have to be represented as a space-separated list of `x`'s. -For example, 0 is an empty string and 6 is `x x x x x x`. I can't claim to -have thought of this on my own. The idea is based on the -[GNU Make Standard Library][1]. - -Before looking at the code, there's a few concepts that need to be explained -first. - -### Immediate vs. Deferred Assignment - -Throughout the code, there are [two types of assignment][2]: - -* `:=` means immediate assignment. -* `=` means deferred assignment. - -As the name implies, immediate assignment assigns the value to the variable -right away. This is typically used for constants. Deferred assignment is only -evaluated when it is needed. Until then, the variable just equals the -expression. This can be used to create user-defined functions. - -### User-Defined Functions - -User-defined functions are done using deferred assignment. The arguments of -a user-defined function are one-based argument numbers enclosed in `$()`. For -example, `$(3)` is the third argument. - -These functions are invoked using the [call][3] function. The first argument -of the `call` function is the variable name that contains the function. The -remaining arguments are the arguments to pass to the user-defined function. - -### Built-In Numeric Functions - -GNU has a few functions that deal with numbers: - -* [words][4] -* [wordlist][5] - -#### words Function - -The `words` function accepts a single argument which is a space-separated list. -It just returns the number of elements in that list. - -#### wordlist Function - -The `wordlist` function accepts three arguments: - -1. One-based starting index. Let's call this `s`. -2. One-based ending index. Let's call this `e`. -3. A space-separated list - -The function returns element `s` through element `e` of the list. The `s` and -`e` arguments are constrained by the size of the list. In other words, the -`wordlist` function will not go past the end of the list. If `e` is less than -`s`, an empty string is returned. - -### Built-In Conditional Function - -The [if][6] function is a conditional function that returns one of two values: -one for the "true" case, and one for the "false" case. This function takes -three arguments: - -1. The value to compare -2. The value to return if "true" -3. The value to return if "false" - -A value is considered "true" if it is not empty, "false" otherwise. - -### Constants - -The Baklava algorithm requires displaying spaces and asterisks (stars). -Therefore, these constants are defined: - -```make -EMPTY := -SPACE := $(EMPTY) $(EMPTY) -STAR := * -``` - -Since GNU Make ignores leading and trailing spaces in variable assignments, in -order to get a variable to assigned to a space (`SPACE`), the space needs to -be sandwiched between an empty variable (`EMPTY`). The `STAR` variable just -contains a single star. - -### Numbers - -This code sets the numbers that are needed to implement the Baklava algorithm: - -```make -ONE := x -TWO := x x -TEN := $(TWO) $(TWO) $(TWO) $(TWO) $(TWO) -``` - -`TEN` is just five copies `TWO` (effectively 2 times 5). - -### Math Functions - -A number of math functions are needed to implement the Baklava algorithm: - -* Increment (`INC`) -* Decrement (`DEC`) -* Add (`ADD`) -* Subtract (`SUB`) - -#### INC Function - -The `INC` function takes a single value and returns that value plus one. The -values are represents as space-separated `x`'s, so all that needs to be done -is to append a single `x`: - -```make -INC = $(strip $(1) $(ONE)) -``` - -The [strip][7] function just removes leading and trailing spaces. It is needed -for the case where the argument is an empty string (0). If this function were -not added, ` x` would be returned instead of `x`. - -#### DEC Function - -The `DEC` function takes a single value (let's call this `n`) represented as -`x`'s. It returns that value minus 1, limited to be no less than zero since -negative numbers cannot be represented. All that needs to be done is to remove -a single `x`: - -```make -DEC = $(wordlist 2,$(words $(1)),$1) -``` - -The above returns element 2 through `n` (using the `wordlist` function), where -The value of `n` is returned using the `words` function. For example, if the -value is 3 (`x x x`), then 2 (`x x`) is returned. - -#### ADD Function - -The `ADD` function takes two values and returns the sum of them. All that -needs to be done is to concatenate the two values: - -```make -ADD = $(strip $(1) $(2)) -``` - -The `strip` function removes leading or trailing spaces for the case where -either argument is an empty string (0). If this were not done then 0 plus -2 would be ` x x` instead of `x x`, and 2 plus 0 would be `x x ` instead -of `x x`. - -#### SUB Function - -The `SUB` function takes two values (let's call these `a` and `b`) and returns -the first value minus the second value, limited to be no less than zero since -negative numbers cannot be represented. All that needs to be done is the -remove the second value from the first: - -```make -$(wordlist $(words $(call INC,$(2))),$(words $(1)),$(1)) -``` - -This is similar to what the `DEC` function does, but instead of starting 2, it -starts at `a + 1`. Note that the second argument is incremented due to the -fact that one-base indexes are used. For example, let say that `a` is 5 -(`x x x x x`), and `b` is 3 (`x x x`), then element 4 (`3 + 1`) through 5 is -returned, which are the 2 (`x x`) right-most elements: - -``` -1 2 3 | 4 5 -x x x | x x -``` - -### REPEAT Function - -The `REPEAT` function takes two argument: - -1. The character to repeat -2. The number of times to repeat the character (`n`) represented as `x`'s - -The function returns the character repeated the specified number of times: - -```make -REPEAT = $(subst $(1)$(SPACE),$(1),$(foreach _,$(2),$(1))) -``` - -Let's break this down starting with the [foreach][8] function. This function -takes three arguments: - -1. A variable name -2. A space-separated list -3. A text value - -It returns a space-separated list that contains the text value for each item -in the list. In this case, the variable `_` is unused. The list is `n` -represented as `x`'s. The text is the character to repeat. What this will do -is repeat the character `n` times separated by spaces. For example, if `n` is -7 (`x x x x x x x`) and the character is `*`, then `* * * * * * *` would be -returned. - -Since we don't want those extra spaces, we need to remove them. However, we -have to be smart about it. We can't just remove all spaces. If the character -is ` `, then `foreach` will return `2*n - 1` spaces, and removing all the -spaces would return in a empty string instead of `n` spaces. Therefore, -the [subst][9] function is used. This function takes three arguments: - -1. The search string -2. The replace string -3. The string to modify - -This is used to change the character plus a space to just the character. - -### The Baklava Algorithm - -All the above is used to display the Baklava pattern, which is a diamond shape -composed of lines of spaces and stars. - -#### BAKLAVA_LINE Function - -This function takes two arguments: - -1. The number of spaces represented as `x`'s -2. The number of stars represented as `x`'s - -This function returns the requested number of spaces concatenated with the -requested number of stars: - -```make -BAKLAVA_LINE = $(call REPEAT,$(SPACE),$(1))$(call REPEAT,$(STAR),$(2)) -``` - -This is done with the `REPEAT` function. - -#### UPPER_BAKLAVA_LOOP Function - -This function displays the upper triangle of the Baklava. It takes two -arguments: - -1. The starting number of spaces represented as `x`'s. Let's call this `num_spaces`. -2. The starting number of stars represented as `x`'s. Let's call this `num_stars`. - -Here is the function: - -```make -define UPPER_BAKLAVA_LOOP -$(info $(call BAKLAVA_LINE,$(1),$(2))) -$(if $(1),$(call UPPER_BAKLAVA_LOOP,$(call DEC,$(1)),$(call ADD,$(2),$(TWO)))) -endef -``` - -The [define][10] keyword assigns a multi-line value to a variable. The value -is terminated with an `endef` keyword. The [info][11] function takes a single -value: the value to be displayed. - -Here's what the function looks like in pseudo-code: - -``` -function UPPER_BAKLAVA_LOOP(num_spaces, num_stars) - display BAKLAVA_LINE(num_spaces, num_starts) - if num_spaces is not 0: - call UPPER_BAKLAVA_LOOP(num_spaces - 1, num_stars + 2) -``` - -You'll notice that this is using recursion. That is the only way to implement -loops in GNU Make. Here, each successive loop decreases the number of spaces -displayed by one and increases the number of stars displayed by two until the -number of spaces is zero. - -#### LOWER_BAKLAVA_LOOP Function - -This function displays the lower triangle of the Baklava. It takes two -arguments: - -1. The starting number of spaces represented as `x`'s. Let's call this - `num_spaces`. -2. The starting number of stars represented as `x`'s. Let's call this - `num_stars`. - -Here is the function: - -```make -define LOWER_BAKLAVA_LOOP -$(if $(2),\ - $(info $(call BAKLAVA_LINE,$(1),$(2)))\ - $(call LOWER_BAKLAVA_LOOP,$(call INC,$(1)),$(call SUB,$(2),$(TWO)))\ -) -endef -``` - -Here's what the function looks like in pseudo-code: - -``` -function LOWER_BAKLAVA_LOOP(num_spaces, num_stars) - if num_stars is not zero: - display BAKLAVA_LINE(num_spaces, num_stars) - call LOWER_BAKLAVA_LOOP(num_spaces + 1, num_stars - 2) -``` - -Once again, recursion. Here, while the number of stars is non-zero, each -successive loop increases the number of spaces displayed by one, and decreases -the number of stars displayed by two. This is exactly the opposite of what -`LOWER_BAKLAVA_LOOP` does. - -#### The Final Step - -In order to run the Baklava algorithm and display the results, the two Baklava -loops must be invoked with the correct starting number of spaces and stars. -Since there are 10 (`$(TEN)`) spaces and 1 (`$(ONE)`) star on the first row of -the upper triangle, `UPPER_BAKLAVA_LOOP` is called like this: - -```make -$(call UPPER_BAKLAVA_LOOP,$(TEN),$(ONE)) -``` - -Since there is 1 (`$(ONE)`) space and 19 (`10*2 - 1`) stars on the first row -of the lower triangle, `LOWER_BAKLAVA_LOOP` is called list this: - -```make -$(call LOWER_BAKLAVA_LOOP,$(ONE),$(call DEC,$(call ADD,$(TEN),$(TEN)))) -``` - -That's all there is to it! - -[1]: https://github.com/jgrahamc/gmsl -[2]: https://www.gnu.org/software/make/manual/html_node/Reading-Makefiles.html -[3]: https://www.gnu.org/software/make/manual/html_node/Call-Function.html -[4]: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-words -[5]: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-wordlist -[6]: https://www.gnu.org/software/make/manual/html_node/Conditional-Functions.html#index-if-1 -[7]: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-stripping-whitespace -[8]: https://www.gnu.org/software/make/manual/html_node/Foreach-Function.html -[9]: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-subst-1 -[10]: https://www.gnu.org/software/make/manual/html_node/Multi_002dLine.html -[11]: https://www.gnu.org/software/make/manual/html_node/Make-Control-Functions.html#index-info - - -## How to Run the Solution - -To run this program, download and install the latest GNU Make using these -instructions: - -* [Windows][12] -* For [Linux][13], see "How to Download" section -* [Mac][14] - -Download a copy of [Baklava in GNU Make][15], and run this command: - -``` -make -sf baklava.mk -``` - -[12]: https://leangaurav.medium.com/how-to-setup-install-gnu-make-on-windows-324480f1da69 -[13]: https://www.incredibuild.com/integrations/gnu-make -[14]: https://formulae.brew.sh/formula/make -[15]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/g/gnu-make/baklava.mk diff --git a/docs/projects/baklava/go/index.md b/docs/projects/baklava/go/index.md deleted file mode 100644 index 3689bea1af..0000000000 --- a/docs/projects/baklava/go/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2019-04-01 -layout: default -tags: -- baklava -- go -title: Baklava in Go -title1: Baklava -title2: in Go ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "strings" -) - -func main() { - for i := 0; i < 10; i++ { - fmt.Println(strings.Repeat(" ", (10-i)) + strings.Repeat("*", (i*2+1))) - } - - for i := 10; -1 < i; i-- { - fmt.Println(strings.Repeat(" ", (10-i)) + strings.Repeat("*", (i*2+1))) - } -} - -``` - -{% endraw %} - -Baklava in [Go](/languages/go) was written by: - -- Jeremy Grifski -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/goby/index.md b/docs/projects/baklava/goby/index.md deleted file mode 100644 index ff77166140..0000000000 --- a/docs/projects/baklava/goby/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- goby -title: Baklava in Goby -title1: Baklava -title2: in Goby ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Goby](/languages/goby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```goby -(-10..10).each do |n| - num_spaces = if n >= 0 n else -n end - num_stars = 21 - 2 * num_spaces - puts(" " * num_spaces + "*" * num_stars) -end - -``` - -{% endraw %} - -Baklava in [Goby](/languages/goby) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/golo/index.md b/docs/projects/baklava/golo/index.md deleted file mode 100644 index 2ceaf7a588..0000000000 --- a/docs/projects/baklava/golo/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- golo -title: Baklava in Golo -title1: Baklava -title2: in Golo ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Golo](/languages/golo) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```golo -module baklava - -function main = |args| { - for (var n = -10, n <= 10, n = n + 1) { - let numSpaces = Math.abs(n) - let numStars = 21 - 2 * numSpaces - println(" " * numSpaces + "*" * numStars) - } -} - -``` - -{% endraw %} - -Baklava in [Golo](/languages/golo) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/gosu/index.md b/docs/projects/baklava/gosu/index.md deleted file mode 100644 index 964436c3ee..0000000000 --- a/docs/projects/baklava/gosu/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- gosu -title: Baklava in Gosu -title1: Baklava -title2: in Gosu ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Gosu](/languages/gosu) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gosu -for ( n in -10..10) { - var numSpaces = Math.abs(n) - var numStars = 21 - 2 * numSpaces - print(" ".repeat(numSpaces) + "*".repeat(numStars)) -} - -``` - -{% endraw %} - -Baklava in [Gosu](/languages/gosu) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/grain/index.md b/docs/projects/baklava/grain/index.md deleted file mode 100644 index 57dfcc8cb3..0000000000 --- a/docs/projects/baklava/grain/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- grain -title: Baklava in Grain -title1: Baklava -title2: in Grain ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Grain](/languages/grain) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```grain -module Main - -from "array" include Array -from "number" include Number -from "range" include Range -from "string" include String - -let repeatString = (s, n) => Array.join("", Array.make(n, s)) -let baklavaLine = (n) => { - let numSpaces = Number.abs(n) - let numStars = 21 - 2 * numSpaces - return String.concat(repeatString(" ", numSpaces), repeatString("*", numStars)) -} - -Range.forEach(n => print(baklavaLine(n)), {rangeStart: -10, rangeEnd: 11}) - -``` - -{% endraw %} - -Baklava in [Grain](/languages/grain) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/granule/index.md b/docs/projects/baklava/granule/index.md deleted file mode 100644 index 3c370039f5..0000000000 --- a/docs/projects/baklava/granule/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- granule -title: Baklava in Granule -title1: Baklava in -title2: Granule ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Granule](/languages/granule) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```granule -import Bool - -repeatString : Int -> String[] -> String -repeatString 0 [str] = ""; -repeatString times [str] = str `stringAppend` (repeatString (times - 1) [str]) - -numSpaces : Int[] -> Int -numSpaces [n] = if n < 0 then 0 - n else n - -numStars : Int[] -> Int -numStars [n] = 21 - 2 * numSpaces [n] - -baklavaLine : Int[] -> String -baklavaLine [n] = - (repeatString (numSpaces [n]) [" "]) `stringAppend` (repeatString (numStars [n]) ["*"]) `stringAppend` "\n" - -baklava : String[] -> Int[] -> Int[] -> String -baklava [lines] [n] [ne] = - if n <= ne then - lines `stringAppend` (baklavaLine [n]) `stringAppend` (baklava [lines] [n + 1] [ne]) - else - lines - -main : () <{Stdout}> -main = toStdout (baklava [""] [-10] [10]) - -``` - -{% endraw %} - -Baklava in [Granule](/languages/granule) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/gravity/index.md b/docs/projects/baklava/gravity/index.md deleted file mode 100644 index 0f706f0864..0000000000 --- a/docs/projects/baklava/gravity/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- gravity -title: Baklava in Gravity -title1: Baklava in -title2: Gravity ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Gravity](/languages/gravity) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gravity -func main() { - for (var n in -10...10) { - var numSpaces = Math.abs(n) - var numStars = 21 - 2 * numSpaces - var spaces = (numSpaces > 0) ? " ".repeat(numSpaces) : "" - var stars = "*".repeat(numStars) - System.print(spaces + stars) - } -} - -``` - -{% endraw %} - -Baklava in [Gravity](/languages/gravity) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/groovy/index.md b/docs/projects/baklava/groovy/index.md deleted file mode 100644 index fe3bb46318..0000000000 --- a/docs/projects/baklava/groovy/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Rafael Vargas -- rzuckerm -date: 2019-10-12 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-07-25 -layout: default -tags: -- baklava -- groovy -title: Baklava in Groovy -title1: Baklava -title2: in Groovy ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -(0..10).each{ index -> - println "${' ' * (10 - index)}${'*' * (index * 2 + 1)}" -} -(9..0).each{ index -> - println "${' ' * (10 - index)}${'*' * (index * 2 + 1)}" -} -``` - -{% endraw %} - -Baklava in [Groovy](/languages/groovy) was written by: - -- Rafael Vargas -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/hack/index.md b/docs/projects/baklava/hack/index.md deleted file mode 100644 index 1fbce0ad1d..0000000000 --- a/docs/projects/baklava/hack/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- hack -title: Baklava in Hack -title1: Baklava -title2: in Hack ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Hack](/languages/hack) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```hack -use namespace HH\Lib\Str; - -<<__EntryPoint>> -function main(): void { - for ($n = -10; $n <= 10; $n++) { - $numSpaces = abs($n); - $numStars = 21 - 2 * $numSpaces; - echo Str\repeat(" ", $numSpaces) . Str\repeat("*", $numStars) . "\n"; - } -} - -``` - -{% endraw %} - -Baklava in [Hack](/languages/hack) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/haskell/index.md b/docs/projects/baklava/haskell/index.md deleted file mode 100644 index 5746c1b0aa..0000000000 --- a/docs/projects/baklava/haskell/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-10-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2019-03-26 -layout: default -tags: -- baklava -- haskell -title: Baklava in Haskell -title1: Baklava in -title2: Haskell ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -main :: IO () -main = putStrLn baklava - --- Create baklava where the top has 10 spaces and then 1 asterisk -baklava :: String -baklava = baklavaGrow 10 1 - --- Recursively grow the baklava until spaces <= zero -baklavaGrow :: Int -> Int -> String -baklavaGrow space asterisk - | space <= 0 = line 0 asterisk ++ "\n" ++ baklavaShrink 1 (asterisk - 2) - | otherwise = line space asterisk ++ "\n" ++ baklavaGrow (space - 1) (asterisk + 2) - --- Recursively shrink the baklava until asterisks <= zero -baklavaShrink :: Int -> Int -> String -baklavaShrink space asterisk - | asterisk <= 1 = line space 1 - | otherwise = line space asterisk ++ "\n" ++ baklavaShrink (space + 1) (asterisk - 2) - --- Return a single line of the baklava -line space asterisk = replicate space ' ' ++ replicate asterisk '*' - -``` - -{% endraw %} - -Baklava in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/haxe/index.md b/docs/projects/baklava/haxe/index.md deleted file mode 100644 index 9e218bd69a..0000000000 --- a/docs/projects/baklava/haxe/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- haxe -title: Baklava in Haxe -title1: Baklava -title2: in Haxe ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Haxe](/languages/haxe) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haxe -import StringTools; - -class Baklava { - static private function repeatString(s:String, n:Int): String { - return StringTools.rpad("", s, n); - } - - static public function main() { - for (n in -10...11) { - var numSpaces = Std.int(Math.abs(n)); - var numStars = 21 - 2 * numSpaces; - trace(repeatString(" ", numSpaces) + repeatString("*", numStars)); - } - } -} - -``` - -{% endraw %} - -Baklava in [Haxe](/languages/haxe) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/hobbes/index.md b/docs/projects/baklava/hobbes/index.md deleted file mode 100644 index 941973d2b7..0000000000 --- a/docs/projects/baklava/hobbes/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- hobbes -title: Baklava in Hobbes -title1: Baklava -title2: in Hobbes ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Hobbes](/languages/hobbes) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```hobbes -repeatString :: (string, int) -> string -repeatString s n = if (n > 0) then s ++ repeatString(s, n - 1) else "" - -iabs :: int -> int -iabs n = if (n < 0) then -n else n - -baklavaLine :: int -> string -baklavaLine n = - let - numSpaces = iabs(n); - numStars = 21 - 2 * numSpaces - in - repeatString(" ", numSpaces) ++ repeatString("*", numStars) - -baklava :: (int, int) -> () -baklava n ne = if (n <= ne) then do { - putStrLn(baklavaLine(n)); - baklava(n + 1, ne); -} else () - -baklava(-10, 10) - -``` - -{% endraw %} - -Baklava in [Hobbes](/languages/hobbes) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/idris/index.md b/docs/projects/baklava/idris/index.md deleted file mode 100644 index 14755df979..0000000000 --- a/docs/projects/baklava/idris/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- idris -title: Baklava in Idris -title1: Baklava -title2: in Idris ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Idris](/languages/idris) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```idris -module Main - -repeatString : String -> Int -> String -repeatString s n = if n < 1 then "" else s ++ repeatString s (n - 1) - -baklavaLine : Int -> String -baklavaLine n = repeatString " " numSpaces ++ repeatString "*" numStars - where - numSpaces = abs n - numStars = 21 - 2 * numSpaces - -main : IO () -main = sequence_ $ map (putStrLn . baklavaLine) [-10..10] - -``` - -{% endraw %} - -Baklava in [Idris](/languages/idris) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/index.md b/docs/projects/baklava/index.md deleted file mode 100644 index 43e2415741..0000000000 --- a/docs/projects/baklava/index.md +++ /dev/null @@ -1,261 +0,0 @@ ---- -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-05-15 -layout: default -tags: -- baklava -title: Baklava -title1: Baklava -title2: '' ---- - - - -Welcome to the Baklava page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Baklava is a Turkish dessert, and its shape is like an equilateral quadrangle. -It is used as an example for programming education in Turkish schools. - -In general, this solution can be accomplished using a pair of loops. Of course, all -possible programs are welcome. - - -## Requirements - -For simplicity, Baklava requires no inputs and can be executed in some form as follows: - -```console -$ ./baklava.lang -``` - -The following is the expected output: - - * - *** - ***** - ******* - ********* - *********** - ************* - *************** - ***************** - ******************* - ********************* - ******************* - ***************** - *************** - ************* - *********** - ********* - ******* - ***** - *** - * - -1. The shape should be symmetrical both horizontally and vertically -2. Each subsequent line should either add or remove padding by one character on both sides -3. Whitespace should be adjusted accordingly in order to properly output the shape - - -## Testing - -Verify that the actual output matches the expected output -(see [Requirements](#requirements)). - - -## Articles - -There are 158 articles: - -- [Baklava in ALGOL 60](/projects/baklava/algol60) -- [Baklava in ALGOL 68](/projects/baklava/algol68) -- [Baklava in AWK](/projects/baklava/awk) -- [Baklava in Ada](/projects/baklava/ada) -- [Baklava in Agda](/projects/baklava/agda) -- [Baklava in ArkScript](/projects/baklava/arkscript) -- [Baklava in BAIK](/projects/baklava/baik) -- [Baklava in Ballerina](/projects/baklava/ballerina) -- [Baklava in Bash](/projects/baklava/bash) -- [Baklava in Batch](/projects/baklava/batch) -- [Baklava in Beef](/projects/baklava/beef) -- [Baklava in Befunge](/projects/baklava/befunge) -- [Baklava in Boo](/projects/baklava/boo) -- [Baklava in Bracmat](/projects/baklava/bracmat) -- [Baklava in Brainfuck](/projects/baklava/brainfuck) -- [Baklava in C](/projects/baklava/c) -- [Baklava in C#](/projects/baklava/c-sharp) -- [Baklava in C\*](/projects/baklava/c-star) -- [Baklava in C++](/projects/baklava/c-plus-plus) -- [Baklava in C2](/projects/baklava/c2) -- [Baklava in COBOL](/projects/baklava/cobol) -- [Baklava in Carp](/projects/baklava/carp) -- [Baklava in ChaiScript](/projects/baklava/chaiscript) -- [Baklava in Chapel](/projects/baklava/chapel) -- [Baklava in Clojure](/projects/baklava/clojure) -- [Baklava in CoffeeScript](/projects/baklava/coffeescript) -- [Baklava in Commodore BASIC](/projects/baklava/commodore-basic) -- [Baklava in Crystal](/projects/baklava/crystal) -- [Baklava in Cyclone](/projects/baklava/cyclone) -- [Baklava in Cython](/projects/baklava/cython) -- [Baklava in D](/projects/baklava/d) -- [Baklava in Dale](/projects/baklava/dale) -- [Baklava in Dart](/projects/baklava/dart) -- [Baklava in Dg](/projects/baklava/dg) -- [Baklava in Discus](/projects/baklava/discus) -- [Baklava in Dusk](/projects/baklava/dusk) -- [Baklava in Egison](/projects/baklava/egison) -- [Baklava in Eiffel](/projects/baklava/eiffel) -- [Baklava in Elena](/projects/baklava/elena) -- [Baklava in Elixir](/projects/baklava/elixir) -- [Baklava in Elvish](/projects/baklava/elvish) -- [Baklava in Emojicode](/projects/baklava/emojicode) -- [Baklava in Erlang](/projects/baklava/erlang) -- [Baklava in Eta](/projects/baklava/eta) -- [Baklava in Euphoria](/projects/baklava/euphoria) -- [Baklava in F#](/projects/baklava/f-sharp) -- [Baklava in F\*](/projects/baklava/f-star) -- [Baklava in Factor](/projects/baklava/factor) -- [Baklava in Felix](/projects/baklava/felix) -- [Baklava in Fennel](/projects/baklava/fennel) -- [Baklava in Ferret](/projects/baklava/ferret) -- [Baklava in Fetlang](/projects/baklava/fetlang) -- [Baklava in Flix](/projects/baklava/flix) -- [Baklava in Formality](/projects/baklava/formality) -- [Baklava in Forth](/projects/baklava/forth) -- [Baklava in Fortran](/projects/baklava/fortran) -- [Baklava in Frege](/projects/baklava/frege) -- [Baklava in GNU Make](/projects/baklava/gnu-make) -- [Baklava in Gerbil](/projects/baklava/gerbil) -- [Baklava in Gluon](/projects/baklava/gluon) -- [Baklava in Go](/projects/baklava/go) -- [Baklava in Goby](/projects/baklava/goby) -- [Baklava in Golo](/projects/baklava/golo) -- [Baklava in Gosu](/projects/baklava/gosu) -- [Baklava in Grain](/projects/baklava/grain) -- [Baklava in Granule](/projects/baklava/granule) -- [Baklava in Gravity](/projects/baklava/gravity) -- [Baklava in Groovy](/projects/baklava/groovy) -- [Baklava in Hack](/projects/baklava/hack) -- [Baklava in Haskell](/projects/baklava/haskell) -- [Baklava in Haxe](/projects/baklava/haxe) -- [Baklava in Hobbes](/projects/baklava/hobbes) -- [Baklava in Idris](/projects/baklava/idris) -- [Baklava in Io](/projects/baklava/io) -- [Baklava in Janet](/projects/baklava/janet) -- [Baklava in Java](/projects/baklava/java) -- [Baklava in JavaScript](/projects/baklava/javascript) -- [Baklava in Julia](/projects/baklava/julia) -- [Baklava in Kitten](/projects/baklava/kitten) -- [Baklava in Koka](/projects/baklava/koka) -- [Baklava in Kotlin](/projects/baklava/kotlin) -- [Baklava in LOLCODE](/projects/baklava/lolcode) -- [Baklava in Latte](/projects/baklava/latte) -- [Baklava in Lily](/projects/baklava/lily) -- [Baklava in Lisp](/projects/baklava/lisp) -- [Baklava in Little](/projects/baklava/little) -- [Baklava in LiveScript](/projects/baklava/livescript) -- [Baklava in Lobster](/projects/baklava/lobster) -- [Baklava in Lua](/projects/baklava/lua) -- [Baklava in Lucee](/projects/baklava/lucee) -- [Baklava in Malbolge](/projects/baklava/malbolge) -- [Baklava in Mathematica](/projects/baklava/mathematica) -- [Baklava in Mirth](/projects/baklava/mirth) -- [Baklava in Modula-2](/projects/baklava/modula2) -- [Baklava in MojiScript](/projects/baklava/mojiscript) -- [Baklava in MoonScript](/projects/baklava/moonscript) -- [Baklava in Never](/projects/baklava/never) -- [Baklava in Nim](/projects/baklava/nim) -- [Baklava in Nit](/projects/baklava/nit) -- [Baklava in OCaml](/projects/baklava/ocaml) -- [Baklava in Objective-C](/projects/baklava/objective-c) -- [Baklava in Octave](/projects/baklava/octave) -- [Baklava in Odin](/projects/baklava/odin) -- [Baklava in Opa](/projects/baklava/opa) -- [Baklava in Orc](/projects/baklava/orc) -- [Baklava in Owl Lisp](/projects/baklava/owl-lisp) -- [Baklava in PHP](/projects/baklava/php) -- [Baklava in Pascal](/projects/baklava/pascal) -- [Baklava in Perl](/projects/baklava/perl) -- [Baklava in Phix](/projects/baklava/phix) -- [Baklava in PicoLisp](/projects/baklava/picolisp) -- [Baklava in Piet](/projects/baklava/piet) -- [Baklava in Pineapple](/projects/baklava/pineapple) -- [Baklava in Pinecone](/projects/baklava/pinecone) -- [Baklava in Pony](/projects/baklava/pony) -- [Baklava in PowerShell](/projects/baklava/powershell) -- [Baklava in Prolog](/projects/baklava/prolog) -- [Baklava in PureScript](/projects/baklava/purescript) -- [Baklava in Pyret](/projects/baklava/pyret) -- [Baklava in Python](/projects/baklava/python) -- [Baklava in Quackery](/projects/baklava/quackery) -- [Baklava in R](/projects/baklava/r) -- [Baklava in Racket](/projects/baklava/racket) -- [Baklava in Raku](/projects/baklava/raku) -- [Baklava in Red](/projects/baklava/red) -- [Baklava in Rexx](/projects/baklava/rexx) -- [Baklava in Ring](/projects/baklava/ring) -- [Baklava in Ruby](/projects/baklava/ruby) -- [Baklava in Rust](/projects/baklava/rust) -- [Baklava in Sather](/projects/baklava/sather) -- [Baklava in Scala](/projects/baklava/scala) -- [Baklava in Scheme](/projects/baklava/scheme) -- [Baklava in Scilab](/projects/baklava/scilab) -- [Baklava in Shen](/projects/baklava/shen) -- [Baklava in Smalltalk](/projects/baklava/smalltalk) -- [Baklava in Solidity](/projects/baklava/solidity) -- [Baklava in Solisp](/projects/baklava/solisp) -- [Baklava in Spry](/projects/baklava/spry) -- [Baklava in Swift](/projects/baklava/swift) -- [Baklava in TI-BASIC](/projects/baklava/ti-basic) -- [Baklava in Tcl](/projects/baklava/tcl) -- [Baklava in TeX](/projects/baklava/tex) -- [Baklava in Terra](/projects/baklava/terra) -- [Baklava in TypeScript](/projects/baklava/typescript) -- [Baklava in Unicat](/projects/baklava/unicat) -- [Baklava in V](/projects/baklava/v) -- [Baklava in Verilog](/projects/baklava/verilog) -- [Baklava in Verve](/projects/baklava/verve) -- [Baklava in Vimscript](/projects/baklava/vimscript) -- [Baklava in Visual Basic](/projects/baklava/visual-basic) -- [Baklava in Whitespace](/projects/baklava/whitespace) -- [Baklava in Wren](/projects/baklava/wren) -- [Baklava in Wu](/projects/baklava/wu) -- [Baklava in Wyvern](/projects/baklava/wyvern) -- [Baklava in Yoix](/projects/baklava/yoix) -- [Baklava in Zig](/projects/baklava/zig) -- [Baklava in m4](/projects/baklava/m4) -- [Baklava in x86-64](/projects/baklava/x86-64) - -*** - - \ No newline at end of file diff --git a/docs/projects/baklava/io/index.md b/docs/projects/baklava/io/index.md deleted file mode 100644 index 2b0398dd38..0000000000 --- a/docs/projects/baklava/io/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- io -title: Baklava in Io -title1: Baklava -title2: in Io ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Io](/languages/io) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```io -baklavaLine := method(n, - num_spaces := n abs - num_stars := 21 - (2 * num_spaces) - (" " repeated(num_spaces)) .. ("*" repeated(num_stars)) -) - -for(n, -10, 10, baklavaLine(n) println) - -``` - -{% endraw %} - -Baklava in [Io](/languages/io) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/janet/index.md b/docs/projects/baklava/janet/index.md deleted file mode 100644 index 57a7a0f157..0000000000 --- a/docs/projects/baklava/janet/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-01 -layout: default -tags: -- baklava -- janet -title: Baklava in Janet -title1: Baklava -title2: in Janet ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Janet](/languages/janet) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```janet -(for n -10 11 - (let [num_spaces (math/abs n) - num_stars (- 21 (* 2 num_spaces))] - (print (string/repeat " " num_spaces) (string/repeat "*" num_stars)) - ) -) - -``` - -{% endraw %} - -Baklava in [Janet](/languages/janet) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/java/index.md b/docs/projects/baklava/java/index.md deleted file mode 100644 index 1cc71aad9f..0000000000 --- a/docs/projects/baklava/java/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -date: 2018-12-30 -featured-image: baklava-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- baklava -- java -title: Baklava in Java -title1: Baklava -title2: in Java ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class Baklava { - public static void up() { - for (int i = 0; i < 10; i++) - printRow(i); - } - - public static void down() { - for (int i = 10; i >= 0; i--) - printRow(i); - } - - public static void printRow(int rowNum) { - for (int j = 10 - rowNum; j > 0; j--) - System.out.print(" "); - for (int j = 0; j <= rowNum * 2; j++) - System.out.print("*"); - System.out.println(); - } - - public static void main(String[] args) { - up(); - down(); - } -} - -``` - -{% endraw %} - -Baklava in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/javascript/index.md b/docs/projects/baklava/javascript/index.md deleted file mode 100644 index 96e45349a1..0000000000 --- a/docs/projects/baklava/javascript/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2018-09-17 -layout: default -tags: -- baklava -- javascript -title: Baklava in JavaScript -title1: Baklava in -title2: JavaScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -for (var i = 0; i < 10; i++) - console.log ( - " ".repeat (10 - i) + "*".repeat (i * 2 + 1) - ); - -for (var i = 10; -1 < i; i--) - console.log ( - " ".repeat (10 - i) + "*".repeat (i * 2 + 1) - ); - -``` - -{% endraw %} - -Baklava in [JavaScript](/languages/javascript) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/julia/index.md b/docs/projects/baklava/julia/index.md deleted file mode 100644 index ae480d82c3..0000000000 --- a/docs/projects/baklava/julia/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- germmand -- Jeremy Grifski -date: 2018-10-04 -featured-image: baklava-in-every-language.jpg -last-modified: 2019-03-27 -layout: default -tags: -- baklava -- julia -title: Baklava in Julia -title1: Baklava -title2: in Julia ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -#!/usr/bin/julia - -function main() - for i = 0:10 - print(" "^(10 - i)) - println("*"^(i * 2 + 1)) - end - - for i = 9:-1:0 - print(" "^(10 - i)) - println("*"^(i * 2 + 1)) - end -end - -main() - -``` - -{% endraw %} - -Baklava in [Julia](/languages/julia) was written by: - -- germmand -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/kitten/index.md b/docs/projects/baklava/kitten/index.md deleted file mode 100644 index 8dca142e24..0000000000 --- a/docs/projects/baklava/kitten/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-31 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-31 -layout: default -tags: -- baklava -- kitten -title: Baklava in Kitten -title1: Baklava -title2: in Kitten ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Kitten](/languages/kitten) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kitten -define repeat_string (List, Int32 -> List): - -> s, n; - if (n > 0) { - s s n 1 (-) repeat_string (+) - } else { - "" - } - -define baklava_line (Int32 -> List): - -> n; - n abs -> num_spaces; - 21 2 num_spaces (*) (-) -> num_stars; - " " num_spaces repeat_string - "*" num_stars repeat_string (+) - -define baklava (Int32, Int32 -> +IO): - -> n, ne; - if (n <= ne) { - n baklava_line say - n 1 (+) ne baklava - } - --10 10 baklava - -``` - -{% endraw %} - -Baklava in [Kitten](/languages/kitten) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/koka/index.md b/docs/projects/baklava/koka/index.md deleted file mode 100644 index 8b47348a9c..0000000000 --- a/docs/projects/baklava/koka/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-31 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-31 -layout: default -tags: -- baklava -- koka -title: Baklava in Koka -title1: Baklava -title2: in Koka ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Koka](/languages/koka) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```koka -fun repeat_string(s : string, n : int) { - var result := "" - list(1, n).foreach(fn(_) { result := result + s }) - result -} - -fun main() { - list(-10, 10).foreach(fn(n) { - var num_spaces := abs(n) - var num_stars := 21 - 2 * num_spaces - println(repeat_string(" ", num_spaces) + repeat_string("*", num_stars)) - }) -} - -``` - -{% endraw %} - -Baklava in [Koka](/languages/koka) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/kotlin/index.md b/docs/projects/baklava/kotlin/index.md deleted file mode 100644 index 3e34b18a12..0000000000 --- a/docs/projects/baklava/kotlin/index.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Stuart Irwin -date: 2018-09-17 -featured-image: baklava-in-kotlin.jpg -last-modified: 2023-05-15 -layout: default -tags: -- baklava -- kotlin -title: Baklava in Kotlin -title1: Baklava -title2: in Kotlin ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main (args: Array) -{ - for (i in 0..9) - println (" ".repeat (10 - i) + "*".repeat (i * 2 + 1)); - - for (i in 10 downTo 0) - println (" ".repeat (10 - i) + "*".repeat (i * 2 + 1)); -} - -``` - -{% endraw %} - -Baklava in [Kotlin](/languages/kotlin) was written by: - -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -``` - * - *** - ***** - ******* - ********* - *********** - ************* - *************** - ***************** - ******************* - ********************* - ******************* - ***************** - *************** - ************* - *********** - ********* - ******* - ***** - *** - * -``` - -1. The shape should be symmetrical both horizontally and vertically -2. Each subsequent line should either add or remove padding by one character on both sides -3. Whitespace should be adjusted accordingly in order to properly output the shape - -### First loop - -Kotlin is structured similarly to Java, but the syntax is designed to be helpful and easy, so the first line is all that is needed to get the program started. - -The top half of the diamond is created here, and is comparitively easy to read: - -```kotlin -for (i in 0..9) - println (" ".repeat (10 - i) + "*".repeat (i * 2 + 1)); -``` -The first line sets up a basic loop, iterating the variable i from 0 to 9 - -The next line of code is then run 10 times, each time outputing a new line to the screen. -Each line contains (10 - i)` spaces, followed by `(2i + 1)` stars. As i rises from 0 to 9, the number of spaces shrinks and the number of stars increases. - -In the end, this loop of code will produce a large pyramid like this: - -``` - * - *** - ***** - ******* - ********* - *********** - ************* - *************** - ***************** - ******************* -``` - -### Second loop - -The second for loop is almost identical, and creates the same pyramid as before, but upside down. - -```kotlin -for (i in 10 downTo 0) - println (" ".repeat (10 - i) + "*".repeat (i * 2 + 1)); -``` - -Instead of starting at 0 and ending at 9, this loop starts at 10 and ends when i is 0. - -Nothing else is changed in the loop, so it adds the bottom half of the diamond and finishes the program. - - -## How to Run the Solution - - -To run on a personal computer, the ideal environment is [IntelliJ IDEA][4], as it and kotlin were both created by JetBrains. -If you decide to install the command line version however, save the program to Baklava.kt and run with these commands. - -```bash -kotlinc Baklava.kt -include-runtime -d Baklava.jar -java -jar Baklava.jar -``` - -[4]: https://www.jetbrains.com/idea/ diff --git a/docs/projects/baklava/latte/index.md b/docs/projects/baklava/latte/index.md deleted file mode 100644 index d81fced9fa..0000000000 --- a/docs/projects/baklava/latte/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-30 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-30 -layout: default -tags: -- baklava -- latte -title: Baklava in Latte -title1: Baklava -title2: in Latte ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Latte](/languages/latte) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```latte -def printRepeatString(s:String, n:int) - if n > 0 - for i in 1.to(n) - print(s) - -for i in (-10).to(10) - numSpaces:int = i - if numSpaces < 0 - numSpaces = -numSpaces - - printRepeatString(" ", numSpaces) - printRepeatString("*" , 21 - 2*numSpaces) - println() - -``` - -{% endraw %} - -Baklava in [Latte](/languages/latte) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/lily/index.md b/docs/projects/baklava/lily/index.md deleted file mode 100644 index 199f22251e..0000000000 --- a/docs/projects/baklava/lily/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-27 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-27 -layout: default -tags: -- baklava -- lily -title: Baklava in Lily -title1: Baklava -title2: in Lily ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Lily](/languages/lily) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lily -import math - -define repeatString(s: String, n: Integer): String -{ - var result = "" - if n > 0: { - for i in 1...n: { - result = "{0}{1}".format(result, s) - } - } - - return result -} - -for n in -10...10: { - var num_spaces = math.abs(n) - var num_stars = 21 - 2 * num_spaces - print("{0}{1}".format(repeatString(" ", num_spaces), repeatString("*", num_stars))) -} - -``` - -{% endraw %} - -Baklava in [Lily](/languages/lily) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/lisp/index.md b/docs/projects/baklava/lisp/index.md deleted file mode 100644 index f623e07bef..0000000000 --- a/docs/projects/baklava/lisp/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Parker Johansen -- Stuart Irwin -date: 2019-11-09 -featured-image: baklava-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- baklava -- lisp -title: Baklava in Lisp -title1: Baklava -title2: in Lisp ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(defparameter space_list '(#\space)) -(defparameter star_list '(#\*)) -(dotimes (run 9) - (push #\space space_list)) -(dotimes (run 10) - (write-line (concatenate 'string space_list star_list)) - (pop space_list) - (push #\* star_list) - (push #\* star_list) -) -(dotimes (run 11) - (write-line (concatenate 'string space_list star_list)) - (pop star_list) - (pop star_list) - (push #\space space_list) -) -``` - -{% endraw %} - -Baklava in [Lisp](/languages/lisp) was written by: - -- Parker Johansen -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/little/index.md b/docs/projects/baklava/little/index.md deleted file mode 100644 index 26b3a42cee..0000000000 --- a/docs/projects/baklava/little/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-27 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-27 -layout: default -tags: -- baklava -- little -title: Baklava in Little -title1: Baklava -title2: in Little ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Little](/languages/little) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```little -string repeat_string(string s, int n) { - int i; - string result = ""; - for (i = 0; i < n; i++) { - result[END + 1] = s; - } - - return result; -} - -int n, numSpaces, numStars; -for (n = -10; n <= 10; n++) { - numSpaces = abs(n); - numStars = 21 - 2 * numSpaces; - printf("%s%s\n", repeat_string(" ", numSpaces), repeat_string("*", numStars)); -} - -``` - -{% endraw %} - -Baklava in [Little](/languages/little) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/livescript/index.md b/docs/projects/baklava/livescript/index.md deleted file mode 100644 index 0beb9be250..0000000000 --- a/docs/projects/baklava/livescript/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-27 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-27 -layout: default -tags: -- baklava -- livescript -title: Baklava in LiveScript -title1: Baklava in -title2: LiveScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [LiveScript](/languages/livescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```livescript -for n from -10 to 10 - num_spaces = Math.abs(n) - num_stars = 21 - 2 * num_spaces - console.log ' '.repeat(num_spaces) + '*'.repeat(num_stars) - -``` - -{% endraw %} - -Baklava in [LiveScript](/languages/livescript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/lobster/index.md b/docs/projects/baklava/lobster/index.md deleted file mode 100644 index 61274acec7..0000000000 --- a/docs/projects/baklava/lobster/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-27 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-27 -layout: default -tags: -- baklava -- lobster -title: Baklava in Lobster -title1: Baklava in -title2: Lobster ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Lobster](/languages/lobster) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lobster -for (21) n: - let num_spaces = abs(n - 10) - let num_stars = 21 - 2 * num_spaces - let spaces = repeat_string(" ", num_spaces) - let stars = repeat_string("*", num_stars) - print "{spaces}{stars}" - -``` - -{% endraw %} - -Baklava in [Lobster](/languages/lobster) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/lolcode/index.md b/docs/projects/baklava/lolcode/index.md deleted file mode 100644 index afe6f3b6ff..0000000000 --- a/docs/projects/baklava/lolcode/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-27 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-27 -layout: default -tags: -- baklava -- lolcode -title: Baklava in LOLCODE -title1: Baklava in -title2: LOLCODE ---- - - - -Welcome to the [Baklava](/projects/baklava) in [LOLCODE](/languages/lolcode) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lolcode -HAI 1.2 - -BTW Function to output a string n times -HOW IZ I OUTPUT_N_TIMES_FOR YR string AN YR n - IM IN YR loop UPPIN YR i TIL BOTH SAEM i AN BIGGR OF i AN n - VISIBLE ":{string}"! - IM OUTTA YR loop -IF U SAY SO - -BTW For n = 0 to 20 -IM IN YR loop UPPIN YR n TIL BOTH SAEM n AN BIGGR OF n AN 21 - BTW num_spaces = abs(n - 10) - I HAS A num_spaces ITZ DIFF OF n AN 10 - DIFFRINT num_spaces AN BIGGR OF 0 AN num_spaces - O RLY? - YA RLY - num_spaces R PRODUKT OF -1 AN num_spaces - OIC - - BTW num_stars = 21 - 2 * num_spaces - I HAS A num_stars ITZ DIFF OF 21 AN PRODUKT OF 2 AN num_spaces - - BTW Output " " num_spaces times - I IZ OUTPUT_N_TIMES_FOR YR " " AN YR num_spaces MKAY - - BTW Output "*" num_stars times - I IZ OUTPUT_N_TIMES_FOR YR "*" AN YR num_stars MKAY - - BTW Output newline - VISIBLE "" -IM OUTTA YR loop - -KTHXBYE - -``` - -{% endraw %} - -Baklava in [LOLCODE](/languages/lolcode) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/lua/index.md b/docs/projects/baklava/lua/index.md deleted file mode 100644 index 8fe3119317..0000000000 --- a/docs/projects/baklava/lua/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- bhaskar_datta -- Jeremy Grifski -date: 2019-10-28 -featured-image: baklava-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- baklava -- lua -title: Baklava in Lua -title1: Baklava -title2: in Lua ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -function diamondStarPattern(height) - for i = 1, height do -- loop for printing the upper half of the baklava - for j = i, height - 1 do io.write(" ") end --to print the leading spaces - for j = 1, (2*i-1) do io.write("*") end -- to print the * for the upper half - io.write("\n") -- to move pointer to next line - end - for i = height - 1,1,-1 do -- loop for printing the lower half of the baklava - for j = i, height - 1 do io.write(" ") end -- to print the spaces - for j = 1, (2*i-1) do io.write("*") end -- to print the * for the lower half - io.write("\n") -- to move pointer to next line - end -end - -diamondStarPattern(11) - -``` - -{% endraw %} - -Baklava in [Lua](/languages/lua) was written by: - -- bhaskar_datta -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/lucee/index.md b/docs/projects/baklava/lucee/index.md deleted file mode 100644 index 153765324d..0000000000 --- a/docs/projects/baklava/lucee/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-27 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-27 -layout: default -tags: -- baklava -- lucee -title: Baklava in Lucee -title1: Baklava -title2: in Lucee ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Lucee](/languages/lucee) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lucee - - - Baklava - - -

-for (n = -10; n <= 10; n++) {
-    numSpaces = abs(n);
-    numStars = 21 - 2 * numSpaces;
-    spaces = repeatString(" ", numSpaces);
-    stars = repeatString("*", numStars);
-    writeOutput(spaces & stars & "
"); -} -
- - - -``` - -{% endraw %} - -Baklava in [Lucee](/languages/lucee) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/m4/index.md b/docs/projects/baklava/m4/index.md deleted file mode 100644 index 81cd158626..0000000000 --- a/docs/projects/baklava/m4/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-09 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-08-09 -layout: default -tags: -- baklava -- m4 -title: Baklava in m4 -title1: Baklava -title2: in m4 ---- - - - -Welcome to the [Baklava](/projects/baklava) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -dnl repeat(string, count) -define(`repeat', `ifelse(eval(($2) > 0), 1, `$1'`'`repeat($1, eval(($2) - 1))', )') -dnl indent(count, string) -define(`indent', `ifelse(eval(($1) > 0), 1, `format(`%$1s%s', `', $2)', $2)') -dnl abs(n) -define(`abs', `ifelse(eval(($1) >= 0), 1, eval($1), eval(0 - $1))') -dnl baklava(n, stop) -define(`baklava', -`ifelse(eval($1 <= $2), 1, `baklava_line($1) -baklava(eval($1 + 1), $2)', )'dnl -) -dnl baklava_line(n) -define(`baklava_line', `indent(abs($1), repeat(`*', 21 - 2 * abs($1)))') -divert(0)dnl -baklava(-10, 10)dnl - -``` - -{% endraw %} - -Baklava in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/malbolge/index.md b/docs/projects/baklava/malbolge/index.md deleted file mode 100644 index 2a05a91559..0000000000 --- a/docs/projects/baklava/malbolge/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- Auberon López -date: 2024-10-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-23 -layout: default -tags: -- baklava -- malbolge -title: Baklava in Malbolge -title1: Baklava in -title2: Malbolge ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Malbolge](/languages/malbolge) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```malbolge -D'`N$">7mYX{V7UB43cs=<_:]\I6jigg$B"ybP_N):[qpotsrk10/.-,+*)(`H^cba`Y}W?[ZSRv9ONSRQJImlkjihgfe?'=BA:^]\<;492V6v43,+ONMLKJIH('gf|#z@?>==<;:9876tsrqpRQ.fN+*)(`H^cba`Y}|{zyxwvutsrqQ3IHlLE-IBAedc&%A:?8\[ZYXWVUTSRQPON.-m%*#G'&feBAbx}|{t:9876543210/.-,+*hg`H^c\"CB^W\UyYX:VONrqponmlkjihgfedcba`#9>=6Z{32VUTSRQPONMLKJIHGFEDCB"b~}|{ts9Zvutsrkpi/gfejc)('&%$#"!~}|{zyxwvuUTSR4o2NGFjiI+AFEDCB;_^]\[ZYXWVUTSRQPO/.-m%*#G'&feBA@a`v{zyr876543210/.-,+*hg`H^c\"CB^W\UyxwvVU7SRQPIHlkjihgfedcba`#9>=6Z:9876v43,+ONMLK%$#(!~%|BA@?>=<;:98vXnm3qponmfN+*)('&^cbaZ_X]\UyxwvutsrqQ3IHlLE-IBAedcba`_?>=<|{32VUTSRQP0/.-m%*#G'&feBA@?>=<;yxwvunV3210/POedchg`&dFb[`Y}|{zyxwvu8NMLKonm0/KJCHG@d'=BA:?87[ZYXWVUTSR210/.nmJ7 -``` - -{% endraw %} - -Baklava in [Malbolge](/languages/malbolge) was written by: - -- Auberon López - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/mathematica/index.md b/docs/projects/baklava/mathematica/index.md deleted file mode 100644 index a77c129851..0000000000 --- a/docs/projects/baklava/mathematica/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-16 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-01-16 -layout: default -tags: -- baklava -- mathematica -title: Baklava in Mathematica -title1: Baklava in -title2: Mathematica ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -TableForm[ - Table[ - Table[ - (* asterisk or space depending on Manhattan distance *) - If[Abs[i] + Abs[j] <= #, "*", " "], - {i, -#, +#}], - {j, -#, +#}], - TableSpacing -> {0, 0}] &[10] -``` - -{% endraw %} - -Baklava in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/mirth/index.md b/docs/projects/baklava/mirth/index.md deleted file mode 100644 index 4039686f7d..0000000000 --- a/docs/projects/baklava/mirth/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-25 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-25 -layout: default -tags: -- baklava -- mirth -title: Baklava in Mirth -title1: Baklava -title2: in Mirth ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Mirth](/languages/mirth) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mirth -module sample-programs.baklava - -import std.prelude -import std.world -import std.list -import std.str - -||| stack: n -def abs [Int -- Nat] { - ||| if n < 0 then -n else n - dup 0 < if(-1 *, dup drop) Int.>Nat-clamp -} - -||| stack: n (count), s (string) -def repeat-string [Nat Str -- Str] { - "" ||| stack: n, s, result = "" - rotl ||| stack: s, result, n - repeat( ||| stack: s, result - ||| repeat n times: - over ||| stack: s, result, s - cat ||| stack: s, result = result + s - ) - dip(drop) ||| stack: result -} - -||| stack: n -def baklava-line [Int -- Str] { - abs ||| stack: num-spaces = abs(n) - dup ||| stack: num-spaces, num-spaces - " " repeat-string ||| stack: num-spaces, spaces = num-spaces " " - swap ||| stack: spaces, num-spaces - Nat.>Int -2 * 21 + Int.>Nat-clamp ||| stack: spaces, num-stars = 21 - 2 * num-spaces - "*" repeat-string ||| stack: spaces, stars = num-stars "*" - cat ||| stack: spaces + stars -} - -def main { - ||| for n = -10 to 10: - ||| print baklava-line(n) - -10 10 range for(baklava-line print) -} - -``` - -{% endraw %} - -Baklava in [Mirth](/languages/mirth) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/modula2/index.md b/docs/projects/baklava/modula2/index.md deleted file mode 100644 index 8036cf7b46..0000000000 --- a/docs/projects/baklava/modula2/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- modula2 -title: Baklava in Modula-2 -title1: Baklava in -title2: Modula-2 ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Modula-2](/languages/modula2) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```modula-2 -MODULE Baklava; - -FROM StrIO IMPORT WriteString, WriteLn; - -PROCEDURE WriteRepeatString(s: ARRAY OF CHAR; n: CARDINAL); -VAR i: CARDINAL; -BEGIN - FOR i := 1 TO n DO - WriteString(s); - END -END WriteRepeatString; - -VAR - n: INTEGER; - numSpaces: CARDINAL; - numStars: CARDINAL; - -BEGIN - FOR n := -10 TO 10 DO - numSpaces := ABS(n); - numStars := 21 - 2 * numSpaces; - WriteRepeatString(' ', numSpaces); - WriteRepeatString('*', numStars); - WriteLn; - END; -END Baklava. - -``` - -{% endraw %} - -Baklava in [Modula-2](/languages/modula2) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/mojiscript/index.md b/docs/projects/baklava/mojiscript/index.md deleted file mode 100644 index 716c42f525..0000000000 --- a/docs/projects/baklava/mojiscript/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-30 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-30 -layout: default -tags: -- baklava -- mojiscript -title: Baklava in MojiScript -title1: Baklava in -title2: MojiScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [MojiScript](/languages/mojiscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mojiscript -import log from 'mojiscript/console/log' -import pipe from 'mojiscript/core/pipe' -import run from 'mojiscript/core/run' -import map from 'mojiscript/list/map' -import range from 'mojiscript/list/range' - -const numSpaces = n => Math.abs(n) -const numStars = n => 21 - 2 * numSpaces (n) -const baklavaLine = n => ' '.repeat(numSpaces (n)) + '*'.repeat(numStars (n)) - -const main = pipe([ - range (-10) (11), - map (baklavaLine), - map (log) -]) - -run({main}) - -``` - -{% endraw %} - -Baklava in [MojiScript](/languages/mojiscript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/moonscript/index.md b/docs/projects/baklava/moonscript/index.md deleted file mode 100644 index b91aa43da0..0000000000 --- a/docs/projects/baklava/moonscript/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-30 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-30 -layout: default -tags: -- baklava -- moonscript -title: Baklava in MoonScript -title1: Baklava in -title2: MoonScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [MoonScript](/languages/moonscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```moonscript -string_repeat = (s, n) -> - result = "" - for i = 1, n - result ..= s - return result - -for i = -10, 10 - num_spaces = math.abs i - num_stars = 21 - 2 * num_spaces - print string_repeat(" ", num_spaces) .. string_repeat("*", num_stars) - -``` - -{% endraw %} - -Baklava in [MoonScript](/languages/moonscript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/never/index.md b/docs/projects/baklava/never/index.md deleted file mode 100644 index 29a6cd45c0..0000000000 --- a/docs/projects/baklava/never/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- never -title: Baklava in Never -title1: Baklava -title2: in Never ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Never](/languages/never) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```never -func abs(n: int) -> int { - (n < 0) ? -n : n -} - -func repeat_string(s: string, n: int) -> string { - var result = ""; - var i = 0; - for (i = 0; i < n; i = i + 1) { - result = result + s - }; - - result -} - -func main() -> int { - var i = 0; - for (i = -10; i <= 10; i = i + 1) { - var num_spaces = abs(i); - var num_stars = 21 - 2 * num_spaces; - prints(repeat_string(" ", num_spaces) + repeat_string("*", num_stars) + "\n") - }; - - 0 -} - -``` - -{% endraw %} - -Baklava in [Never](/languages/never) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/nim/index.md b/docs/projects/baklava/nim/index.md deleted file mode 100644 index 1e4407dcac..0000000000 --- a/docs/projects/baklava/nim/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- nim -title: Baklava in Nim -title1: Baklava -title2: in Nim ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Nim](/languages/nim) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nim -import strutils - -for n in -10..10: - var numSpaces: int = abs(n) - var numStars: int = 21 - 2 * numSpaces - echo repeat(" ", numSpaces), repeat("*", numStars) - -``` - -{% endraw %} - -Baklava in [Nim](/languages/nim) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/nit/index.md b/docs/projects/baklava/nit/index.md deleted file mode 100644 index 015a704161..0000000000 --- a/docs/projects/baklava/nit/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- nit -title: Baklava in Nit -title1: Baklava -title2: in Nit ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Nit](/languages/nit) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nit -for n in [-10..10] do - var num_spaces = n.abs - var num_stars = 21 - 2 * num_spaces - print " " * num_spaces + "*" * num_stars -end - -``` - -{% endraw %} - -Baklava in [Nit](/languages/nit) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/objective-c/index.md b/docs/projects/baklava/objective-c/index.md deleted file mode 100644 index 25f427e38e..0000000000 --- a/docs/projects/baklava/objective-c/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- rzuckerm -- Ștefan-Iulian Alecu -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- baklava -- objective-c -title: Baklava in Objective-C -title1: Baklava in -title2: Objective-C ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -int main() { - @autoreleasepool { - const NSInteger radius = 10; - - for (NSInteger i = -radius; i <= radius; i++) { - NSUInteger paddingCount = (NSUInteger)labs(i); - NSUInteger starCount = (radius - paddingCount) * 2 + 1; - - NSString* padding = [@"" stringByPaddingToLength:paddingCount - withString:@" " - startingAtIndex:0]; - - NSString* stars = [@"" stringByPaddingToLength:starCount - withString:@"*" - startingAtIndex:0]; - - NSString* line = [padding stringByAppendingString:stars]; - - puts(line.UTF8String); - } - } - return 0; -} -``` - -{% endraw %} - -Baklava in [Objective-C](/languages/objective-c) was written by: - -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/ocaml/index.md b/docs/projects/baklava/ocaml/index.md deleted file mode 100644 index 1b87c33e65..0000000000 --- a/docs/projects/baklava/ocaml/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- ocaml -title: Baklava in OCaml -title1: Baklava -title2: in OCaml ---- - - - -Welcome to the [Baklava](/projects/baklava) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -(** https://rosettacode.org/wiki/Repeat_a_string#OCaml **) -let string_repeat n s = - String.concat "" (Array.to_list (Array.make n s));; - -for n = -10 to 10 do - let num_spaces = abs n in - let num_stars = 21 - 2 * num_spaces in - Printf.printf "%s%s\n" (string_repeat num_spaces " ") (string_repeat num_stars "*"); -done - -``` - -{% endraw %} - -Baklava in [OCaml](/languages/ocaml) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/octave/index.md b/docs/projects/baklava/octave/index.md deleted file mode 100644 index 32dac520d3..0000000000 --- a/docs/projects/baklava/octave/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- octave -title: Baklava in Octave -title1: Baklava -title2: in Octave ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function baklava() - for n = -10:10 - num_spaces = abs(n); - num_stars = 21 - 2 * num_spaces; - disp([repmat(' ', 1, num_spaces), repmat('*', 1, num_stars)]); - end -end - -``` - -{% endraw %} - -Baklava in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/odin/index.md b/docs/projects/baklava/odin/index.md deleted file mode 100644 index a9afab0dcd..0000000000 --- a/docs/projects/baklava/odin/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- odin -title: Baklava in Odin -title1: Baklava -title2: in Odin ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main; - -import "core:fmt" -import "core:strings" - -main :: proc() { - for i := -10; i <= 10; i += 1 { - num_spaces := abs(i) - num_stars := 21 - 2 * num_spaces - spaces, _ := strings.repeat(" ", num_spaces) - stars, _ := strings.repeat("*", num_stars) - fmt.println(strings.concatenate({spaces, stars})) - } -} - -``` - -{% endraw %} - -Baklava in [Odin](/languages/odin) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/opa/index.md b/docs/projects/baklava/opa/index.md deleted file mode 100644 index fe047d5f98..0000000000 --- a/docs/projects/baklava/opa/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-22 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-22 -layout: default -tags: -- baklava -- opa -title: Baklava in Opa -title1: Baklava -title2: in Opa ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Opa](/languages/opa) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```opa -function page() { -
{baklava()}
-} - -function baklava() { - recursive function baklava_rec(lines, n) { - if (n > 0) lines + baklava_line(n) + baklava_rec(lines, n - 1) else lines + baklava_line(n) - } - - baklava_rec("", 20) -} - -function baklava_line(n) { - num_spaces = Int.abs(n - 10) - num_stars = 21 - 2 * num_spaces - String.repeat(num_spaces, " ") + String.repeat(num_stars, "*") + "\n" -} - -Server.start( - Server.http, - { title: "Baklava", page: page} -) - -``` - -{% endraw %} - -Baklava in [Opa](/languages/opa) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/orc/index.md b/docs/projects/baklava/orc/index.md deleted file mode 100644 index bc067d32c1..0000000000 --- a/docs/projects/baklava/orc/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- orc -title: Baklava in Orc -title1: Baklava -title2: in Orc ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Orc](/languages/orc) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```orc -def Baklava(start, end) = - Ift(start <= end) >> - Println(BaklavaLine(start)) >> - Baklava(start + 1, end) - -def BaklavaLine(n) = - val num_spaces = abs(n) - val num_stars = 21 - 2 * num_spaces - RepeatString(" ", num_spaces) + RepeatString("*", num_stars) - -def RepeatString(s, n) = if n <: 1 then "" else s + RepeatString(s, n - 1) - -Baklava(-10, 10) >> -stop - -``` - -{% endraw %} - -Baklava in [Orc](/languages/orc) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/owl-lisp/index.md b/docs/projects/baklava/owl-lisp/index.md deleted file mode 100644 index 9b393eb7f4..0000000000 --- a/docs/projects/baklava/owl-lisp/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- owl-lisp -title: Baklava in Owl Lisp -title1: Baklava in -title2: Owl Lisp ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Owl Lisp](/languages/owl-lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```owl_lisp -(define (string-repeat n str) - (fold string-append "" (make-list n str)) -) - -(define (baklava-line n) - (define num-spaces (abs n)) - (define num-stars (- 21 (* 2 num-spaces))) - (print (string-repeat num-spaces " ") (string-repeat num-stars "*")) -) - -(define (baklava n ne) - (if (<= n ne) - (begin - (baklava-line n) - (baklava (+ n 1) ne) - ) - ) -) - -(λ (args) (baklava -10 10)) - -``` - -{% endraw %} - -Baklava in [Owl Lisp](/languages/owl-lisp) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/pascal/index.md b/docs/projects/baklava/pascal/index.md deleted file mode 100644 index aa66468025..0000000000 --- a/docs/projects/baklava/pascal/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2023-10-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-10-23 -layout: default -tags: -- baklava -- pascal -title: Baklava in Pascal -title1: Baklava -title2: in Pascal ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program Baklava; - -var - n, i, j, k, space: integer; -begin - n := 11; - space := n - 1; - for i := 1 to n do - begin - for j := 1 to space do - write(' '); - space := space - 1; - for k := 1 to (2 * i - 1) do - write('*'); - writeln; - end; - space := 1; - for i := (n - 1) downto 1 do - begin - for j := 1 to space do - write(' '); - space := space + 1; - for k := (2 * i - 1) downto 1 do - write('*'); - writeln; - end; -end. - -``` - -{% endraw %} - -Baklava in [Pascal](/languages/pascal) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/perl/index.md b/docs/projects/baklava/perl/index.md deleted file mode 100644 index daa9b484fb..0000000000 --- a/docs/projects/baklava/perl/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Kateryna Tokar -- Ștefan-Iulian Alecu -date: 2019-10-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- baklava -- perl -title: Baklava in Perl -title1: Baklava -title2: in Perl ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -my $size = 10; - -for my $i ( -$size .. $size ) { - my $spaces = abs($i); - my $stars = 2 * ( $size - $spaces ) + 1; - - say ' ' x $spaces, '*' x $stars; -} - -``` - -{% endraw %} - -Baklava in [Perl](/languages/perl) was written by: - -- Kateryna Tokar -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/phix/index.md b/docs/projects/baklava/phix/index.md deleted file mode 100644 index efe5037710..0000000000 --- a/docs/projects/baklava/phix/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- Pete Lomax -date: 2021-05-07 -featured-image: baklava-in-every-language.jpg -last-modified: 2021-05-07 -layout: default -tags: -- baklava -- phix -title: Baklava in Phix -title1: Baklava -title2: in Phix ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Phix](/languages/phix) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```phix -for i=-10 to 10 do - printf(1,"%s%s\n",{repeat(' ',abs(i)),repeat('*',21-abs(i)*2)}) -end for - -``` - -{% endraw %} - -Baklava in [Phix](/languages/phix) was written by: - -- Pete Lomax - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/php/index.md b/docs/projects/baklava/php/index.md deleted file mode 100644 index 0e59b886a8..0000000000 --- a/docs/projects/baklava/php/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- baklava -- php -title: Baklava in PHP -title1: Baklava -title2: in PHP ---- - - - -Welcome to the [Baklava](/projects/baklava) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Baklava](/projects/baklava) in [PicoLisp](/languages/picolisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```picolisp -(de repeat_string (S N) - (if (> N 0) - (pack S (repeat_string S (- N 1))) - "" - ) -) - -(for X 21 - (setq N (- X 11)) - (setq NSP (abs N)) - (setq NST (- 21 (* 2 NSP))) - (prinl (pack (repeat_string " " NSP) (repeat_string "*" NST))) -) -(bye) - -``` - -{% endraw %} - -Baklava in [PicoLisp](/languages/picolisp) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/piet/baklava.png b/docs/projects/baklava/piet/baklava.png deleted file mode 100755 index 1198778911..0000000000 Binary files a/docs/projects/baklava/piet/baklava.png and /dev/null differ diff --git a/docs/projects/baklava/piet/index.md b/docs/projects/baklava/piet/index.md deleted file mode 100644 index c116bf484c..0000000000 --- a/docs/projects/baklava/piet/index.md +++ /dev/null @@ -1,518 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-30 -featured-image: baklava-in-piet.jpg -last-modified: 2023-05-02 -layout: default -tags: -- baklava -- piet -title: Baklava in Piet -title1: Baklava -title2: in Piet ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Piet](/languages/piet) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -Baklava in Piet - -Baklava in [Piet](/languages/piet) was written by: - -- rzuckerm - -This article was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -## Introduction - -Piet is an [esoteric programming language][4]. Esoteric programming languages -make it difficult to implement even the simplest task, and this was my first -foray into such languages. If that wasn't difficult enough, Piet is a -graphical language, so you can't just pop into a text editor to create a -program. Instead, you have to use an [online editor][6] to even create a -program. To make things even more interesting, Piet uses a rotating color -palette, where the color of the next instruction depends upon the current -instruction. Finally, it is a stack-based language, so programming in it is -akin to programming an old [Hewlett-Packard calculator][5]. If you'd like to -learn more about the Piet language, see the [Official Site][3]. - -Without further ado, let's dive in the implementation! - -## High-Level Overview - -This sample program implements Baklava using two main loops: - -1. Output the top 10 lines: - - - Output `n` spaces. - - Output `21 - 2*n` asterisks. - - Output a newline. - - where `n` equals 1, 2, ..., 10. - -2. Output the bottom 11 lines: - - - Output 21 asterisks. - - Output a newline. - - then: - - - Output `10 - floor(m / 2)` spaces. - - Output `m` asterisks. - - Output a newline. - - where `m` equals 19, 17, ..., 1. - -If this is enough for you, then just jump to the [Credits section](#credits). -Otherwise, strap yourself in, and prepare for a very detailed description that -goes through what each codel (code element) does. - -## Very Detailed Description - -ASCII characters need to be encoded as numbers. The following numbers are -used: - -- space: 32 -- asterisk: 42 -- newline: 10 - -Instructions are shown in the following format: - -- X/Y coordinates of the program counter -- Instruction -- Stack contents - -The direction pointer (DP), controls the flow of the program. The program -starts at `(0, 0)`, and DP points to the right. When DP hits an edge or black -cell, it rotates clockwise. The program terminates when there is nowhere to -go. - -White cells are considered to be no-ops (do-nothing instructions). - -The program is divided into a number parts which are detailed in subsequent -sections of this article. The parts are annotated with letters as follows: - -![Annotated Baklava in Piet](/assets/images/projects/baklava/piet/baklava-annotated.png) - -Click -here -to open the diagram in a separate page so that you can refer back to it. - -### Output Top 10 Lines (A thru G) - -#### Space Loop Initialization (A) - -`n = 10`: - -``` -( 0, 0): push 2 # 2 -( 2, 0): push 5 # 2, 5 -( 4, 0): mult # 10 (n) -``` - -`k = n`: - -``` -( 5, 0): dup # 10 (n), 10 (k) -``` - -#### Space Loop (B) - -Output `" "`: - -``` -( 6, 0): push 4 # n, k, 4 -(10, 0): dup # n, k, 4, 4 -(11, 0): mult # n, k, 16 -(12, 0): dup # n, k, 16, 16 -(13, 0): add # n, k, 32 -(14, 0): outc # n, k -``` - -`k = k - 1`: - -``` -(15, 0): push 1 # n, k, 1 -(16, 0): sub # n, k - 1 -``` - -Check whether the `k` is greater than `0` and branch accordingly: - -``` -(17, 0): dup # n, k, k -(18, 0): push 1 # n, k, k, 1 -(19, 0): not # n, k, k, 0 -(20, 0): gt # n, k, 1 if k > 0 else 0 -(21, 0): DP+ # n, k -``` - -If `k` is greater than `0`, DP rotates clockwise, so a bunch of no-ops are -executed, and the program goes back to the beginning of B. Otherwise, DP is -unchanged, so the program continues on to the beginning of C. - -#### Asterisk Loop Initialization (C) - -Drop `k`: - -``` -(22, 0): pop # n -``` - -`m = 21 - 2 * n`: - -``` -(23, 0): dup # n, n -(24, 0): push 1 # n, n, 1 -(25, 0): not # n, n, 0 -(26, 0): push 1 # n, n, 0, 1 -(27, 0): sub # n, n, -1 -(28, 0): mult # n, -n -(29, 0): dup # n, -n, -n -(30, 0): add # n, -2 * n -(31, 0): push 3 # n, -2 * n, 3 -(32, 1): push 7 # n, -2 * n, 3, 7 -(34, 0): mult # n, -2 * n, 21 -(35, 0): add # n, 21 - 2 * n (m) -``` - -#### Asterisk Loop (D) - -Output `"*"`: - -``` -(36, 0): push 3 # n, m, 3 -(39, 0): dup # n, m, 3, 3 -(40, 0): add # n, m, 6 -(41, 0): dup # n, m, 6, 6 -(42, 0): dup # n, m, 6, 6, 6 -(43, 0): mult # n, m, 6, 36 -(44, 0): add # n, m, 42 -(45, 0): outc # n, m -``` - -`m = m - 1`: - -``` -(46, 0): push 1 # n, m, 1 -(47, 0): sub # n, m - 1 -``` - -Check whether `m` is greater than `0` and branch accordingly: - -``` -(48, 0): dup # n, m, m -(49, 0): push 1 # n, m, m , 1 -(50, 0): not # n, m, m , 0 -(51, 0): gt # n, m, 1 if m > 0 else 0 -(52, 0): DP+ # n, m -``` - -If `m` is greater than `0`, DP rotates clockwise, so a bunch of no-ops are -executed, and the program goes back to the beginning of D. Otherwise, DP is -unchanged, so the program continues on to the beginning of E. - -#### Output Newline (E) - -Drop `m`: - -``` -(53, 0): pop # n -``` - -Output `"\n"`: - -``` -(54, 0): push 2 # n, 2 -(55, 1): push 5 # n, 2, 5 -(53, 3): mult # n, 10 -(52, 3): outc # n -``` - -#### Check If Last Line (F) - -`n = n - 1`: - -``` -(51, 3): push 1 # n, 1 -(50, 3): sub # n - 1 -``` - -Check if `n` is greater than `0` and branch accordingly: - -``` -(49, 3): dup # n, n -(48, 3): push 1 # n, n, 1 -(47, 3): not # n, n, 0 -(46, 3): gt # n, 1 if n > 0 else 0 (q) -(45, 3): not # n, 1 - q -(44, 3): dup # n, 1 - q, 1 - q -(43, 3): dup # n, 1 - q, 1 - q, 1 - q -(42, 3): add # n, 1 - q, 2 * (1 - q) -(41, 3): add # n, 3 * (1 - q) -(40, 3): DP+ # n -``` - -where: - -``` -3 * (1 - q) = 0 if n > 0 else 3 -``` - -If `n` is greater than `0`, DP is unchanged, so the program goes to the -beginning of G. Otherwise, DP is rotated 3 steps clockwise, which is the same -as 1 step counter-clockwise, so the program goes to the beginning of H. - -#### Set Up For Next Iteration (G) - -`k = n`: - -``` -(39, 3): dup # n, k -``` - -The program then executes a bunch of no-ops and goes back to the beginning of B. - -### Output Bottom 11 Lines (H thru N) - -#### Asterisk Loop Initialization (H) - -Drop `n`: - -``` -(39, 4): pop # empty -``` - -Skip through a bunch of no-ops. Then, rotate DP 3 steps clockwise (1 step -counter-clockwise): - -``` -( 4, 5): push 3 # 3 -( 1, 5): DP+ # empty -``` - -Skip through a no-op. Then, set `m = 21`: - -``` -( 0, 7): push 3 # 3 -( 0, 8): push 7 # 3, 7 -( 5, 7): mult # 21 (m) -``` - -`k = m`: - -``` -( 6, 7): dup # m, k -``` - -#### Asterisk Loop (I) - -Output `"*"`: - -``` -( 7, 7): push 3 # m, k, 3 -(10, 7): dup # m, k, 3, 3 -(11, 7): add # m, k, 6 -(12, 7): dup # m, k, 6, 6 -(13, 7): dup # m, k, 6, 6, 6 -(14, 7): mult # m, k, 6, 36 -(15, 7): add # m, k, 42 -(16, 7): outc # m, k -``` - -`k = k - 1`: - -``` -(17, 7): push 1 # m, k, 1 -(18, 7): sub # m, k - 1 -``` - -Check if `k` is greater than `0` and branch accordingly: - -``` -(19, 7): dup # m, k, k -(20, 7): push 1 # m, k, k, 1 -(21, 7): not # m, k, k, 0 -(22, 7): gt # m, k, 1 if k > 0 else 0 -(23, 7): DP+ # m, k -``` - -If `k` is greater than `0`, DP rotates clockwise, so a bunch of no-ops are -executed, and the program goes back to the beginning of I. Otherwise, DP is -unchanged, so the program continues on to the beginning of J. - -#### Output Newline and Check If Last Line (J) - -Drop `k`: - -``` -(24, 7): pop # m -``` -Output `"\n"`: - -``` -(25, 7): push 2 # m, 2 -(27, 7): push 5 # m, 2, 5 -(29, 7): mult # m, 10 -(30, 7): outc # m -``` - -`m = m - 2`: - -``` -(31, 7): push 2 # m, 2 -(33, 7): sub # m - 2 -``` - -Check if `m` is greater than `0` and branch accordingly: - -``` -(34, 7): dup # m, m -(35, 7): push 1 # m, m, 1 -(36, 7): not # m, m, 0 -(37, 7): gt # m, 1 if m > 0 else 0 -(38, 7): not # m, 0 if m > 0 else 1 -(39, 7): DP+ # m -``` - -If `m` is greater than 0, DP is unchanged, so continue on to the beginning of -K. Otherwise, DP is rotated clockwise, so go to the beginning of N. - -#### Space Loop Initialization (K) - -`n = 10 - floor(m / 2)`: - -``` -(40, 7): dup # m, m -(41, 7): push 2 # m, m, 2 -(43, 7): div # m, floor(m / 2) -(44, 7): push 1 # m, floor(m / 2), 1 -(45, 7): not # m, floor(m / 2), 0 -(46, 7): push 1 # m, floor(m / 2), 0, 1 -(47, 7): sub # m, floor(m / 2), -1 -(48, 7): mult # m, -floor(m / 2) -(49, 7): push 2 # m, -floor(m / 2), 2 -(51, 7): push 5 # m, -floor(m / 2), 2, 5 -(53, 7): mult # m, -floor(m / 2), 10 -(54, 7): add # m, 10 - floor(m / 2) (n) -``` - -#### Space Loop (L) - -Output `" "`: - -``` -(55, 7): push 4 # m, n, 4 -(59, 7): dup # m, n, 4, 4 -(60, 7): mult # m, n, 16 -(61, 7): dup # m, n, 16, 16 -(62, 7): add # m, n, 32 -(63, 7): outc # m, n -``` - -`n = n - 1`: - -``` -(64, 7): push 1 # m, n, 1 -(65, 7): sub # m, n - 1 -``` - -Check if `n` is greater than `0` and branch accordingly: - -``` -(66, 7): dup # m, n, n -(67, 7): push 1 # m, n, n, 1 -(68, 7): not # m, n, n, 0 -(69, 7): gt # m, n, 1 if n > 0 else 0 -(70, 7): DP+ # m, n -``` - -If `n` is greater than `0`, DP is rotated clockwise, so a bunch of no-ops -are executed, and the program goes back to the beginning of L. Otherwise, -DP is unchanged, and the program continues on to the beginning of M. - -### Setup For Next Line (M) - -Drop `n`: - -``` -(71, 7): pop # m -``` - -`k = m`: - -``` -(71, 8): dup # m, k -``` - -After that a bunch of no-ops are executed, and the program goes back to the -beginning of I. - -#### Termination (N) - -Drop `n`: - -``` -(40, 7): pop # empty -``` - -After that the program will terminate since there is nowhere else to go. I -struggled with this, trying different shapes. Finally, the cross shape seemed -to do the trick. - -## Credits - -The image for this article is based on a painting by [Piet Mondrian][2] called -[Victory Boogie-Woogie][1]. He painted this in 1944 in expectation of victory -in World War II. I chose this painting because its shape matches the output -of the program. I copied it to the left and right just to fill in the empty -spaces, and I think it looks cool! - -## Thanks - -Thanks to `alope107` for introducing me to the Piet esoteric language and -for helping me fix a termination issue with this program (in other words, -I couldn't get the silly thing to stop running!). - -[1]: https://www.piet-mondrian.org/victory-boogie-woogie.jsp -[2]: https://en.wikipedia.org/wiki/Piet_Mondrian -[3]: https://www.dangermouse.net/esoteric/piet.html -[4]: https://en.wikipedia.org/wiki/Esoteric_programming_language -[5]: https://en.wikipedia.org/wiki/HP_calculators -[6]: https://piet.bubbler.one/ - - -## How to Run the Solution - -Go to the [npiet interpreter site](https://www.bertnase.de/npiet/). On Linux, -download `.tar.gz` and extract the contents. Follow the instructions in the -`README` file. On Windows, download the `.zip` file and extract the contents. -Follow the instructions in the `README` file. - -To run the code, use this: - -``` -npiet baklava.png -``` - -Alternatively, you can go to the -[Online Piet Editor and Interpreter site](https://piet.bubbler.one/), -import `baklava.png`, and execute it. diff --git a/docs/projects/baklava/pineapple/index.md b/docs/projects/baklava/pineapple/index.md deleted file mode 100644 index a85776df37..0000000000 --- a/docs/projects/baklava/pineapple/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-11-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-11-20 -layout: default -tags: -- baklava -- pineapple -title: Baklava in Pineapple -title1: Baklava in -title2: Pineapple ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Pineapple](/languages/pineapple) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pineapple -def (this String).repeat(times Number) -> String - let i mutable = times - let s mutable = "" - while i > 0 - s = "$(s)$(this)" - i = i - 1 - - return s - -def .main - let i mutable = -10 - while i <= 10 - let numSpaces mutable = i - if numSpaces < 0 - numSpaces = -numSpaces - - let spaces = " ".repeat(numSpaces) - let stars = "*".repeat(21 - (2 * numSpaces)) - "$(spaces)$(stars)".show - i = i + 1 - -``` - -{% endraw %} - -Baklava in [Pineapple](/languages/pineapple) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/pinecone/index.md b/docs/projects/baklava/pinecone/index.md deleted file mode 100644 index 78b6dde24d..0000000000 --- a/docs/projects/baklava/pinecone/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-02 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-02 -layout: default -tags: -- baklava -- pinecone -title: Baklava in Pinecone -title1: Baklava in -title2: Pinecone ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Pinecone](/languages/pinecone) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pinecone -repeatStr :: {n: Int, c: String} -> {String}: ( - s: "" - i: 0 | i < in.n | i: i + 1 @ ( - s: s + in.c - ) - - s -) - -i: 0 - 10 | i <= 10 | i: i + 1 @ ( - numSpaces: i - i < 0 ? ( - numSpaces: 0 - i - ) - print: (repeatStr: numSpaces, " ") + (repeatStr: 21 - 2 * numSpaces, "*") -) - -``` - -{% endraw %} - -Baklava in [Pinecone](/languages/pinecone) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/pony/index.md b/docs/projects/baklava/pony/index.md deleted file mode 100644 index a28b607bea..0000000000 --- a/docs/projects/baklava/pony/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-21 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-21 -layout: default -tags: -- baklava -- pony -title: Baklava in Pony -title1: Baklava -title2: in Pony ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Pony](/languages/pony) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pony -actor Main - new create(env: Env) => - var n: I32 = -10 - while n <= 10 do - let numSpaces: I32 = if n >= 0 then n else -n end - let numStars: I32 = 21 - (2 * numSpaces) - env.out.print(repeatString(" ", numSpaces) + repeatString("*", numStars)) - n = n + 1 - end - - fun repeatString(s: String, n: I32): String => - var result = "" - var i: I32 = 0 - while i < n do - result = result + s - i = i + 1 - end - result - -``` - -{% endraw %} - -Baklava in [Pony](/languages/pony) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/powershell/index.md b/docs/projects/baklava/powershell/index.md deleted file mode 100644 index f63e3d34bf..0000000000 --- a/docs/projects/baklava/powershell/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-28 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-28 -layout: default -tags: -- baklava -- powershell -title: Baklava in PowerShell -title1: Baklava in -title2: PowerShell ---- - - - -Welcome to the [Baklava](/projects/baklava) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -for ($X = -10; $X -le 10; $X++) { - $NumSpaces = [Math]::Abs($X) - $Line = " " * $NumSpaces + "*" * (21 - 2 * $NumSpaces) - Write-Output $Line -} - -``` - -{% endraw %} - -Baklava in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/prolog/index.md b/docs/projects/baklava/prolog/index.md deleted file mode 100644 index cd8ec80718..0000000000 --- a/docs/projects/baklava/prolog/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-21 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-21 -layout: default -tags: -- baklava -- prolog -title: Baklava in Prolog -title1: Baklava -title2: in Prolog ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Prolog](/languages/prolog) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```prolog -:- initialization(main). - -baklava(N, NE) :- - forall(between(N, NE, X), baklava_line(X)). - -baklava_line(N) :- - NSP is abs(N), - NST is 21 - 2 * NSP, - output_repeat(" ", NSP), - output_repeat("*", NST), - nl. - -output_repeat(S, N) :- - forall(between(1, N, _), write(S)). - -main() :- - baklava(-10, 10), - halt. - -``` - -{% endraw %} - -Baklava in [Prolog](/languages/prolog) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/purescript/index.md b/docs/projects/baklava/purescript/index.md deleted file mode 100644 index e6324c2396..0000000000 --- a/docs/projects/baklava/purescript/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-23 -layout: default -tags: -- baklava -- purescript -title: Baklava in PureScript -title1: Baklava in -title2: PureScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [PureScript](/languages/purescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```purescript -module Main where - -import Prelude -import Effect (Effect) -import Effect.Console (log) - -main :: Effect Unit -main = do - baklava (-10) 10 - -baklava :: Int -> Int -> Effect Unit -baklava n ne - | n > ne = pure unit - | otherwise = do - log (baklavaLine n) - baklava (n + 1) ne - -baklavaLine :: Int -> String -baklavaLine n = do - let numSpaces = abs n - let numStars = 21 - 2 * numSpaces - (repeatString numSpaces " ") <> (repeatString numStars "*") - -abs :: Int -> Int -abs n - | n < 0 = -n - | otherwise = n - -repeatString :: Int -> String -> String -repeatString n s - | n < 1 = "" - | otherwise = s <> repeatString (n - 1) s - -``` - -{% endraw %} - -Baklava in [PureScript](/languages/purescript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/pyret/index.md b/docs/projects/baklava/pyret/index.md deleted file mode 100644 index 933abda93a..0000000000 --- a/docs/projects/baklava/pyret/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2023-10-16 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-10-16 -layout: default -tags: -- baklava -- pyret -title: Baklava in Pyret -title1: Baklava -title2: in Pyret ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Pyret](/languages/pyret) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pyret -fun print-row(n :: Number): - spaces = string-repeat(" ", 10 - n) - stars = string-repeat("*", (n * 2) + 1) - print(spaces + stars + "\n") -end - -range-by(0, 11, 1).each(print-row) -range-by(9, -1, -1).each(print-row) -``` - -{% endraw %} - -Baklava in [Pyret](/languages/pyret) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/python/index.md b/docs/projects/baklava/python/index.md deleted file mode 100644 index 47e323c95a..0000000000 --- a/docs/projects/baklava/python/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-12-22 -layout: default -tags: -- baklava -- python -title: Baklava in Python -title1: Baklava -title2: in Python ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -for i in range(0, 10, 1): - print((" " * (10 - i)) + ("*" * (i * 2 + 1))) - -for i in range(10, -1, -1): - print((" " * (10 - i)) + ("*" * (i * 2 + 1))) - -``` - -{% endraw %} - -Baklava in [Python](/languages/python) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/quackery/index.md b/docs/projects/baklava/quackery/index.md deleted file mode 100644 index 27a42c8bd7..0000000000 --- a/docs/projects/baklava/quackery/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-23 -layout: default -tags: -- baklava -- quackery -title: Baklava in Quackery -title1: Baklava in -title2: Quackery ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Quackery](/languages/quackery) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```quackery -21 times [ - i^ 10 - abs dup - times [ say " " ] - -2 * 21 + times [ say "*" ] - cr -] - -``` - -{% endraw %} - -Baklava in [Quackery](/languages/quackery) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/r/index.md b/docs/projects/baklava/r/index.md deleted file mode 100644 index 3a6b4e6a2c..0000000000 --- a/docs/projects/baklava/r/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-22 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-22 -layout: default -tags: -- baklava -- r -title: Baklava in R -title1: Baklava -title2: in R ---- - - - -Welcome to the [Baklava](/projects/baklava) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -for (i in -10:10) { - numSpaces = abs(i) - s <- strrep(" ", numSpaces) - s = paste0(s, strrep("*", 21 - 2 * numSpaces)) - cat(s, "\n", sep="") -} - -``` - -{% endraw %} - -Baklava in [R](/languages/r) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/racket/index.md b/docs/projects/baklava/racket/index.md deleted file mode 100644 index f73a60b8c7..0000000000 --- a/docs/projects/baklava/racket/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-19 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-19 -layout: default -tags: -- baklava -- racket -title: Baklava in Racket -title1: Baklava -title2: in Racket ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Racket](/languages/racket) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```racket -#lang racket -(for ([i (in-range -10 11)]) - (define numSpaces (abs i)) - (define numStars (- 21 (* numSpaces 2))) - (define s (make-string numSpaces #\ )) - (define t (make-string numStars #\*)) - (printf "~a~a\n" s t) -) - -``` - -{% endraw %} - -Baklava in [Racket](/languages/racket) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/raku/index.md b/docs/projects/baklava/raku/index.md deleted file mode 100644 index a6db784dd2..0000000000 --- a/docs/projects/baklava/raku/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-19 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-19 -layout: default -tags: -- baklava -- raku -title: Baklava in Raku -title1: Baklava -title2: in Raku ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Raku](/languages/raku) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```raku -for -10 .. 10 { - my $numSpaces = $_.abs; - say (" " x $numSpaces) ~ ("*" x (21 - 2 * $numSpaces)); -} - -``` - -{% endraw %} - -Baklava in [Raku](/languages/raku) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/red/index.md b/docs/projects/baklava/red/index.md deleted file mode 100644 index bc78c7b6a4..0000000000 --- a/docs/projects/baklava/red/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-17 -layout: default -tags: -- baklava -- red -title: Baklava in Red -title1: Baklava -title2: in Red ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Red](/languages/red) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```red -Red [Title: "Bakalava"] - -s: "" -repeat i 21 [ - numSpaces: i - 11 - if numSpaces < 0 [numSpaces: 0 - numSpaces] - clear s - insert/dup tail s " " numSpaces - insert/dup tail s "*" (21 - (2 * numSpaces)) - print s -] - -``` - -{% endraw %} - -Baklava in [Red](/languages/red) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/rexx/index.md b/docs/projects/baklava/rexx/index.md deleted file mode 100644 index 594aeecbcd..0000000000 --- a/docs/projects/baklava/rexx/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-02 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-02 -layout: default -tags: -- baklava -- rexx -title: Baklava in Rexx -title1: Baklava -title2: in Rexx ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Rexx](/languages/rexx) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rexx -do i = -10 to 10 - numSpaces = abs(i) - say strRepeat(numSpaces, " ") || strRepeat(21 - 2 * numSpaces, "*") -end - -strRepeat: - arg n, s - result = "" - do while n > 0 - result = result || s - n = n - 1 - end - - return result - -``` - -{% endraw %} - -Baklava in [Rexx](/languages/rexx) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/ring/index.md b/docs/projects/baklava/ring/index.md deleted file mode 100644 index 24755a5349..0000000000 --- a/docs/projects/baklava/ring/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-01 -layout: default -tags: -- baklava -- ring -title: Baklava in Ring -title1: Baklava -title2: in Ring ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Ring](/languages/ring) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ring -for i = -10 to 10 - numSpaces = fabs(i) - see copy(" ", numSpaces) + copy("*", 21 - 2 * numSpaces) + nl -next - -``` - -{% endraw %} - -Baklava in [Ring](/languages/ring) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/ruby/index.md b/docs/projects/baklava/ruby/index.md deleted file mode 100644 index 90d7f20635..0000000000 --- a/docs/projects/baklava/ruby/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- baklava -- ruby -title: Baklava in Ruby -title1: Baklava -title2: in Ruby ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -HEIGHT = 10 - -(0..HEIGHT).each do |i| - puts "#{" " * (HEIGHT - i)}#{"*" * (2 * i + 1)}" -end - -(HEIGHT - 1).downto(0) do |i| - puts "#{" " * (HEIGHT - i)}#{"*" * (2 * i + 1)}" -end - -``` - -{% endraw %} - -Baklava in [Ruby](/languages/ruby) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/rust/index.md b/docs/projects/baklava/rust/index.md deleted file mode 100644 index e8e919212c..0000000000 --- a/docs/projects/baklava/rust/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-06 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-04-06 -layout: default -tags: -- baklava -- rust -title: Baklava in Rust -title1: Baklava -title2: in Rust ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -fn main() { - for i in -10i32..11i32 { - let num_spaces: usize = i.abs() as usize; - println!("{}{}", " ".repeat(num_spaces), "*".repeat(21 - 2 * num_spaces)); - } -} - -``` - -{% endraw %} - -Baklava in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/sather/index.md b/docs/projects/baklava/sather/index.md deleted file mode 100644 index da9d43b18b..0000000000 --- a/docs/projects/baklava/sather/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-02 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-02 -layout: default -tags: -- baklava -- sather -title: Baklava in Sather -title1: Baklava -title2: in Sather ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Sather](/languages/sather) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```sather -class BAKLAVA is - main is - i:INT := -10; - loop while!(i <= 10); - numSpaces:INT := i; - if (numSpaces < 0) then - numSpaces := -numSpaces; - end; - - #OUT + strRepeat(numSpaces, " ") + strRepeat(21 - 2 * numSpaces, "*") +"\n"; - i := i + 1; - end; - end; - - strRepeat(n:INT, s:STR):STR is - r:STR := ""; - loop n.times!; - r := r + s; - end; - - return r; - end; -end; - -``` - -{% endraw %} - -Baklava in [Sather](/languages/sather) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/scala/index.md b/docs/projects/baklava/scala/index.md deleted file mode 100644 index dac8bcd2f8..0000000000 --- a/docs/projects/baklava/scala/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -- Ștefan-Iulian Alecu -date: 2024-10-02 -featured-image: baklava-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- baklava -- scala -title: Baklava in Scala -title1: Baklava -title2: in Scala ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -object Baklava: - def generate(size: Int): Seq[String] = - for i <- -size to size yield - val spaces = i.abs - val stars = (size * 2 + 1) - 2 * spaces - " " * spaces + "*" * stars - - def main(args: Array[String]): Unit = - val size = - if args.nonEmpty then args(0).toInt - else 10 - - generate(size).foreach(println) -``` - -{% endraw %} - -Baklava in [Scala](/languages/scala) was written by: - -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/scheme/index.md b/docs/projects/baklava/scheme/index.md deleted file mode 100644 index 39ac1aae03..0000000000 --- a/docs/projects/baklava/scheme/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-28 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-28 -layout: default -tags: -- baklava -- scheme -title: Baklava in Scheme -title1: Baklava -title2: in Scheme ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Scheme](/languages/scheme) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scheme -(define (string-repeat n str) - (fold string-append "" (make-list n str)) -) - -(define (baklava-line i) - (define numSpaces (abs i)) - (define numStars (- 21 (* 2 numSpaces))) - (when (<= i 10) - (display (string-repeat numSpaces " ")) - (display (string-repeat numStars "*")) - (newline) - (baklava-line (+ i 1)) - ) -) - -(baklava-line -10) - -``` - -{% endraw %} - -Baklava in [Scheme](/languages/scheme) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/scilab/index.md b/docs/projects/baklava/scilab/index.md deleted file mode 100644 index d61f56f93b..0000000000 --- a/docs/projects/baklava/scilab/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-02 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-02 -layout: default -tags: -- baklava -- scilab -title: Baklava in Scilab -title1: Baklava -title2: in Scilab ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Scilab](/languages/scilab) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scilab -function [result] = strRepeat(n, s) - result = '' - for i = 1:n - result = result + s - end -endfunction - -for i = -10:10 - numSpaces = abs(i) - mprintf('%s%s\n', strRepeat(numSpaces, ' '), strRepeat(21 - 2 * numSpaces, '*')) -end - -``` - -{% endraw %} - -Baklava in [Scilab](/languages/scilab) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/shen/index.md b/docs/projects/baklava/shen/index.md deleted file mode 100644 index 03a47612b0..0000000000 --- a/docs/projects/baklava/shen/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-28 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-28 -layout: default -tags: -- baklava -- shen -title: Baklava in Shen -title1: Baklava -title2: in Shen ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Shen](/languages/shen) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```shen -(define string-repeat - N C -> (if (> N 0) (cn C (string-repeat (- N 1) C)) "") -) - -(define abs - N -> (if (< N 0) (- 0 N) N) -) - -(define spaces - N -> (string-repeat (abs N) " ") -) - -(define stars - N -> (string-repeat (- 21 (* 2 (abs N))) "*") -) - -(define baklava - N -> (if (<= N 10) - (do - (output "~A~A~%" (spaces N) (stars N)) - (baklava (+ 1 N)) - ) - (output "") - ) -) - -(baklava -10) - -``` - -{% endraw %} - -Baklava in [Shen](/languages/shen) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/smalltalk/index.md b/docs/projects/baklava/smalltalk/index.md deleted file mode 100644 index 7db466c307..0000000000 --- a/docs/projects/baklava/smalltalk/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-22 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-22 -layout: default -tags: -- baklava -- smalltalk -title: Baklava in Smalltalk -title1: Baklava in -title2: Smalltalk ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Smalltalk](/languages/smalltalk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```smalltalk --10 to: 10 do: [ :i | - numSpaces := i abs. - numSpaces timesRepeat: [ ' ' display ]. - (21 - (2 * numSpaces)) timesRepeat: [ '*' display ]. - Character nl display. -] - -``` - -{% endraw %} - -Baklava in [Smalltalk](/languages/smalltalk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/solidity/index.md b/docs/projects/baklava/solidity/index.md deleted file mode 100644 index 71b0fae126..0000000000 --- a/docs/projects/baklava/solidity/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-07 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-07 -layout: default -tags: -- baklava -- solidity -title: Baklava in Solidity -title1: Baklava in -title2: Solidity ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Solidity](/languages/solidity) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8; - -contract Baklava { - function main (string memory) public pure returns (string memory) { - string memory output = ''; - for (int i = -10; i <= 10; i++) { - int numSpaces = (i >= 0) ? i : -i; - output = string.concat(output, strRepeat(numSpaces, ' ')); - output = string.concat(output, strRepeat(21 - 2 * numSpaces, '*')); - output = string.concat(output, '\n'); - } - - return output; - } - - function strRepeat(int n, string memory s) private pure returns (string memory) { - string memory r = ''; - for (int i = 0; i < n; i++) { - r = string.concat(r, s); - } - - return r; - } -} - -``` - -{% endraw %} - -Baklava in [Solidity](/languages/solidity) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/solisp/index.md b/docs/projects/baklava/solisp/index.md deleted file mode 100644 index d0567e13c1..0000000000 --- a/docs/projects/baklava/solisp/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- rzuckerm -- Stuart Irwin -date: 2020-03-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-09-24 -layout: default -tags: -- baklava -- solisp -title: Baklava in Solisp -title1: Baklava -title2: in Solisp ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Solisp](/languages/solisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```solisp -(JoinD newline (Map x (Append (Seq 0 10) (Reverse (Seq 0 9))) - (Append - (Clone (- 10 x) " ") - (Clone (+ (* x 2) 1) (Force Char 42)) - ) -)) -``` - -{% endraw %} - -Baklava in [Solisp](/languages/solisp) was written by: - -- rzuckerm -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/spry/index.md b/docs/projects/baklava/spry/index.md deleted file mode 100644 index 564252dce4..0000000000 --- a/docs/projects/baklava/spry/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-21 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-12-21 -layout: default -tags: -- baklava -- spry -title: Baklava in Spry -title1: Baklava -title2: in Spry ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Spry](/languages/spry) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```spry -abs = func [:x - ($x >= 0) then: [ $x ] else: [ 0 - $x ] -] - -repeat_string:times: = func [:s :n - ($n > 0) then: [ $s, repeat_string: $s times: ($n - 1) ] else: [ "" ] -] - --10 to: 10 do: [ - num_spaces = abs :i - num_stars = (21 - (num_spaces * 2)) - echo (repeat_string: " " times: num_spaces, repeat_string: "*" times: num_stars) -] - -``` - -{% endraw %} - -Baklava in [Spry](/languages/spry) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/swift/index.md b/docs/projects/baklava/swift/index.md deleted file mode 100644 index 0a7b2198c2..0000000000 --- a/docs/projects/baklava/swift/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Mark Magahis -date: 2018-10-20 -featured-image: baklava-in-every-language.jpg -last-modified: 2018-10-22 -layout: default -tags: -- baklava -- swift -title: Baklava in Swift -title1: Baklava -title2: in Swift ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -func baklava(maxWidth: Int) -> Void { - for number in 0...maxWidth { - print(String(repeatElement(" ", count:maxWidth-number)) + String(repeatElement("*", count:number*2+1))) - } - for number in (0...maxWidth-1).reversed() { - print(String(repeatElement(" ", count:maxWidth-number)) + String(repeatElement("*", count:number*2+1))) - } -} -baklava(maxWidth: 10) - -``` - -{% endraw %} - -Baklava in [Swift](/languages/swift) was written by: - -- Mark Magahis - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/tcl/index.md b/docs/projects/baklava/tcl/index.md deleted file mode 100644 index 5ca3fa25d8..0000000000 --- a/docs/projects/baklava/tcl/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-02 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-02 -layout: default -tags: -- baklava -- tcl -title: Baklava in Tcl -title1: Baklava -title2: in Tcl ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -for {set i -10} {$i <= 10} {incr i} { - set numSpaces [expr { abs($i) }] - set numStars [expr 21 - 2 * $numSpaces] - puts "[string repeat { } $numSpaces][string repeat * $numStars]" -} - -``` - -{% endraw %} - -Baklava in [Tcl](/languages/tcl) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/terra/index.md b/docs/projects/baklava/terra/index.md deleted file mode 100644 index f5e7ea1450..0000000000 --- a/docs/projects/baklava/terra/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-03 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-03 -layout: default -tags: -- baklava -- terra -title: Baklava in Terra -title1: Baklava -title2: in Terra ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Terra](/languages/terra) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```terra -local function strRepeat(n, s) - local r = "" - for i = 1, n do - r = r .. s - end - - return r -end - -local function baklava() - for i = -10, 10 do - local numSpaces = i - if i < 0 then - numSpaces = -numSpaces - end - - print(strRepeat(numSpaces, " ") .. strRepeat(21 - 2 * numSpaces, "*")) - end -end - -baklava() - -``` - -{% endraw %} - -Baklava in [Terra](/languages/terra) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/tex/index.md b/docs/projects/baklava/tex/index.md deleted file mode 100644 index 3da6dd4cc8..0000000000 --- a/docs/projects/baklava/tex/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-29 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-01-29 -layout: default -tags: -- baklava -- tex -title: Baklava in TeX -title1: Baklava -title2: in TeX ---- - - - -Welcome to the [Baklava](/projects/baklava) in [TeX](/languages/tex) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tex -% Source: https://rosettacode.org/wiki/String_append#Plain_TeX -\def\addtomacro#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}} - -\obeyspaces -\newwrite\out -\immediate\openout\out=baklava.txt - -% TeX doesn't seem to support nested loops; therefore, this needs to be -% flattened out to a single loop that runs from 0 to 330, where 331 -% is the total number of characters if you add the length of all the -% lines together. This was determined by the following python code: -% -% >>> lines = [" " * abs(n) + "*" * (21 - 2 * abs(n)) for n in range(-10,11)] -% >>> sum(len(line) for line in lines) -% 331 -% -% The general algorithm is as follows (prototyped in python): -% -% linecounter = -10 -% linelen = 0 -% for charcounter = 0 to 330: -% # If start of line, reset all variables -% if linelen < 1: -% line = "" -% numspaces = abs(linecounter) -% numstars = 21 - 2 *numspaces -% linelen = numspaces + numstars -% # If not done with spaces, append space to line -% if linelen > numstars: -% line += " " -% # Else, append star to line -% else: -% line += "*" -% # If end of line, output line and increment line counter -% linelen -= 1 -% if linelen < 1: -% print(line) -% linecounter += 1 - -\newcount\charcounter -\newcount\linecounter -\newcount\numspaces -\newcount\numstars -\newcount\linelen - -\linecounter=-10 -\linelen=0 -\charcounter=0 -\loop - \ifnum\linelen<1 - \def\line{} - % numspaces = abs(linecounter) - \numspaces=\linecounter - \ifnum\numspaces<0 - \multiply\numspaces -1 - \fi - % numstars = 21 - 2 *numspaces - \numstars=\numspaces - \multiply\numstars -2 - \advance\numstars 21 - % linelen = \numspaces + \numstars - \linelen=\numspaces - \advance\linelen \numstars - \fi - \ifnum\linelen>\numstars - \addtomacro\line{ } - \else - \addtomacro\line{*} - \fi - \advance\linelen -1 - \ifnum\linelen<1 - \immediate\write\out{\line} - \advance\linecounter 1 - \fi - \advance\charcounter 1 -\ifnum \charcounter<331 -\repeat -\end - -``` - -{% endraw %} - -Baklava in [TeX](/languages/tex) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/ti-basic/index.md b/docs/projects/baklava/ti-basic/index.md deleted file mode 100644 index 68e8b07696..0000000000 --- a/docs/projects/baklava/ti-basic/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-01 -featured-image: baklava-in-every-language.jpg -last-modified: 2025-02-01 -layout: default -tags: -- baklava -- ti-basic -title: Baklava in TI-BASIC -title1: Baklava in -title2: TI-BASIC ---- - - - -Welcome to the [Baklava](/projects/baklava) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -For(N,0,20) - abs(10-N)->S - 21-2*S->T - ""->Str1 - For(I,1,S) - Str1+" "->Str1 - End - For(I,1,T) - Str1+"*"->Str1 - End - Disp Str1 -End - -``` - -{% endraw %} - -Baklava in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/typescript/index.md b/docs/projects/baklava/typescript/index.md deleted file mode 100644 index 5973c7642f..0000000000 --- a/docs/projects/baklava/typescript/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-09-17 -featured-image: baklava-in-every-language.jpg -last-modified: 2018-09-17 -layout: default -tags: -- baklava -- typescript -title: Baklava in TypeScript -title1: Baklava in -title2: TypeScript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -for (var i = 0; i < 10; i++) - console.log ( - " ".repeat (10 - i) + "*".repeat (i * 2 + 1) - ); - -for (var i = 10; -1 < i; i--) - console.log ( - " ".repeat (10 - i) + "*".repeat (i * 2 + 1) - ); - -``` - -{% endraw %} - -Baklava in [TypeScript](/languages/typescript) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/unicat/index.md b/docs/projects/baklava/unicat/index.md deleted file mode 100644 index b7449a4b95..0000000000 --- a/docs/projects/baklava/unicat/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-28 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-08-28 -layout: default -tags: -- baklava -- unicat -title: Baklava in Unicat -title1: Baklava -title2: in Unicat ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Unicat](/languages/unicat) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```unicat -# Set up characters -0o00 😻😹😸🙀🙀😼😸🙀🙀 Memory 0 = 0o40 (32 = ' ') -0o01 😻😹😹🙀🙀😽😺🙀🙀 Memory 1 = 0o52 (42 = '*') -0o02 😻😹😺🙀🙀😹😺🙀🙀 Memory 2 = 0o12 (10 = '\n') - -# Set up constants -0o03 😻😹😻🙀🙀😹🙀🙀 Memory 3 = 1 -0o04 😻😹😼🙀🙀😹🙀😿 Memory 4 = -1 - -# Set up varibles -0o05 😻😹😽🙀🙀😹😺🙀😿 Memory 5 = -0o12 (-10) (loop_counter) - -# Loop start: num_spaces = absolute value of loop_counter -0o06 😻😹😾🙀🙀😸🙀🙀 Memory 6 = 0 -0o07 😿🙀😸😾🙀🙀😽🙀🙀 Memory 6 += Memory 5 (num_spaces = loop_count) -0o10 😽😿😾🙀🙀😹😹🙀🙀 If Memory 6 > 0, jump to 0x12 (0o11 + 1) (if num_spaces > 0) -0o11 😿🙀🙀😾🙀🙀😼🙀🙀 Memory 6 *= Memory 4 (negate num_spaces) - -# num_stars = 21 - 2*num_spaces -0o12 😻😹😿🙀🙀😺😽🙀🙀 Memory 7 = 0o25 (21) -0o13 😿🙀😺😿🙀🙀😾🙀🙀 Memory 7 -= Memory 6 (21 - num_spaces) -0o14 😿🙀😺😿🙀🙀😾🙀🙀 Memory 7 -= Memory 6 (num_stars = 21 - 2*num_spaces) - -# Display spaces -0o15 😻😹😹🙀😿😹😿🙀🙀 Jump to 0o20 (0o17 + 1) (jump to check for num_spaces > 0) -0o16 😽😼😸🙀🙀 Output Memory 0 (' ') -0o17 😿🙀😺😾🙀🙀😻🙀🙀 Memory 6 -= Memory 3 (decrement num_spaces) -0o20 😽😿😾🙀🙀😹😽🙀🙀 If Memory 6 > 0, jump to 0o16 (0o15 + 1) (if num_spaces > 0) - -# Display stars -0o21 😽😼😹🙀🙀 Output Memory 1 ('*') -0o22 😿🙀😺😿🙀🙀😻🙀🙀 Memory 7 -= Memory 3 (decrement num_stars) -0o23 😽😿😿🙀🙀😺😸🙀🙀 If Memory 7 > 0, jump to 0o21 (0o20 + 1) - -# Output newline -0o24 😽😼😺🙀🙀 Output Memory 2 ('\n') - -# If loop_counter > 10, jump to Loop start -0o25 😻😹😹😸🙀🙀😹😺🙀🙀 Memory 8 (0o10) = 10 (0o12) -0o26 😿🙀😺😹😸🙀🙀😽🙀🙀 Memory 8 (0o10) -= Memory 5 (10 - loop_counter) -0o27 😿🙀😸😽🙀🙀😻🙀🙀 Memory 5 += Memory 3 (increment loop_counter) -0o30 😽😿😹😸🙀🙀😽🙀🙀 If Memory 8 (0o10) > 0, jump to 0o06 (0o05 + 1) (if loop_counter > 10, jump to Loop start) - -0o31 🙀🙀 Exit - -``` - -{% endraw %} - -Baklava in [Unicat](/languages/unicat) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/v/index.md b/docs/projects/baklava/v/index.md deleted file mode 100644 index 17debad6f8..0000000000 --- a/docs/projects/baklava/v/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-02 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-02 -layout: default -tags: -- baklava -- v -title: Baklava in V -title1: Baklava -title2: in V ---- - - - -Welcome to the [Baklava](/projects/baklava) in [V](/languages/v) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```v -module main - -fn str_repeat(n int, s string) string { - mut result := "" - for _ in 0 .. n { - result += s - } - - return result -} - -fn main() { - for i in -10 .. 11 { - num_spaces := if i >= 0 { i } else { -i } - println(str_repeat(num_spaces, " ") + str_repeat(21 - 2 *num_spaces, "*")) - } -} - -``` - -{% endraw %} - -Baklava in [V](/languages/v) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/verilog/index.md b/docs/projects/baklava/verilog/index.md deleted file mode 100644 index b2ed76055f..0000000000 --- a/docs/projects/baklava/verilog/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-02 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-02 -layout: default -tags: -- baklava -- verilog -title: Baklava in Verilog -title1: Baklava in -title2: Verilog ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Verilog](/languages/verilog) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```verilog -module main; - integer i, j, numSpaces, numStars; - initial begin - for (i = -10; i <= 10; i += 1) begin - numSpaces = i; - if (numSpaces < 0) begin - numSpaces = -numSpaces; - end - - for (j = 0; j < numSpaces; j += 1) begin - $write(" "); - end - - numStars = 21 - 2 * numSpaces; - for (j = 0; j < numStars; j += 1) begin - $write("*"); - end - - $write("\n"); - end - $finish(0); - end -endmodule - -``` - -{% endraw %} - -Baklava in [Verilog](/languages/verilog) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/verve/index.md b/docs/projects/baklava/verve/index.md deleted file mode 100644 index 8d46a70db1..0000000000 --- a/docs/projects/baklava/verve/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-21 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-12-21 -layout: default -tags: -- baklava -- verve -title: Baklava in Verve -title1: Baklava -title2: in Verve ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Verve](/languages/verve) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```verve -fn abs(n: Int) -> Int { - if (n < 0) { -n } else { n } -} - -let baklava_str = " *********************" - -fn baklava_line(n: Int) -> String { - let num_spaces = abs(n) - let num_stars = 21 - 2 * num_spaces - substr(baklava_str, 10 - num_spaces, num_spaces + num_stars) -} - -fn baklava(start: Int, end: Int) { - if not(start > end) { - print(baklava_line(start)) - baklava(start + 1, end) - } -} - -baklava(-10, 10) - -``` - -{% endraw %} - -Baklava in [Verve](/languages/verve) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/vimscript/index.md b/docs/projects/baklava/vimscript/index.md deleted file mode 100644 index 696d1190c3..0000000000 --- a/docs/projects/baklava/vimscript/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-09-26 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-09-26 -layout: default -tags: -- baklava -- vimscript -title: Baklava in Vimscript -title1: Baklava in -title2: Vimscript ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Vimscript](/languages/vimscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```vimscript -func! Baklava() - for l:i in range(-10, 10) - let l:numSpaces = abs(l:i) - echo repeat(' ', l:numSpaces) . repeat('*', 21 - 2 * l:numSpaces) - endfor -endfunc - -func! Main() - call Baklava() -endfunc - -``` - -{% endraw %} - -Baklava in [Vimscript](/languages/vimscript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/visual-basic/index.md b/docs/projects/baklava/visual-basic/index.md deleted file mode 100644 index 012e01abd9..0000000000 --- a/docs/projects/baklava/visual-basic/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-03 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-03 -layout: default -tags: -- baklava -- visual-basic -title: Baklava in Visual Basic -title1: Baklava in -title2: Visual Basic ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module Baklava - Public Sub Main() - Dim numSpaces As Integer - For i As Integer = -10 To 10 - numSpaces = Math.Abs(i) - System.Console.WriteLine(StrDup(numSpaces, " ") + StrDup(21 - 2 * numSpaces, "*")) - Next i - End Sub -End Module - -``` - -{% endraw %} - -Baklava in [Visual Basic](/languages/visual-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/whitespace/index.md b/docs/projects/baklava/whitespace/index.md deleted file mode 100644 index 89f1d27a22..0000000000 --- a/docs/projects/baklava/whitespace/index.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-14 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-14 -layout: default -tags: -- baklava -- whitespace -title: Baklava in Whitespace -title1: Baklava in -title2: Whitespace ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Whitespace](/languages/whitespace) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```whitespace -S S T T S T S L -L -S S S L -S L -S S L -S L -T T T L -L -S L -T S L -L -S S T L -S S S S L -S L -T T S S T L -S S T S L -S L -S S S S T S S S S S L -L -S T T S S L -S L -L -S L -L -S L -S S S S T S T S T L -S L -T S S S T S L -T S S L -T S S T S S S T S T S T S L -L -S T T S S L -S L -L -S L -L -S S S T S T S L -T L -S S S L -L -S S S T L -T S S S S L -S S S S T S T T L -T S S T L -T S T T L -L -S L -S L -L -S S T T L -S L -L -L -L -L -L -S S T S S L -S L -T S S S T L -T S S T S L -S L -T T T S T L -S L -T S L -S T L -S S L -S L -T S S L -L -S S T S T L -L -T L - -``` - -{% endraw %} - -Baklava in [Whitespace](/languages/whitespace) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/wren/index.md b/docs/projects/baklava/wren/index.md deleted file mode 100644 index 6b34e69c2b..0000000000 --- a/docs/projects/baklava/wren/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-03 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-03 -layout: default -tags: -- baklava -- wren -title: Baklava in Wren -title1: Baklava -title2: in Wren ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -for (i in (-10..10)) { - var numSpaces = (i >= 0) ? i : -i - System.print(" " * numSpaces + "*" * (21 - 2 *numSpaces)) -} - -``` - -{% endraw %} - -Baklava in [Wren](/languages/wren) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/wu/index.md b/docs/projects/baklava/wu/index.md deleted file mode 100644 index feda56d58a..0000000000 --- a/docs/projects/baklava/wu/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-03 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-03 -layout: default -tags: -- baklava -- wu -title: Baklava in Wu -title1: Baklava -title2: in Wu ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Wu](/languages/wu) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wu -repeatString: fun(c: str, count: int) -> str { - s: str = "" - while count > 0 { - s ++= c - count -= 1 - } - - s -} - -i: int = -10 -while i <= 10 { - numSpaces: int = if i >= 0 { i } else { -i } - print(repeatString(" ", numSpaces) ++ repeatString("*", 21 - 2 * numSpaces)) - i += 1 -} - -``` - -{% endraw %} - -Baklava in [Wu](/languages/wu) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/wyvern/index.md b/docs/projects/baklava/wyvern/index.md deleted file mode 100644 index bd73e86b13..0000000000 --- a/docs/projects/baklava/wyvern/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-03 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-03 -layout: default -tags: -- baklava -- wyvern -title: Baklava in Wyvern -title1: Baklava -title2: in Wyvern ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Wyvern](/languages/wyvern) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wyvern -require stdout - -def strRepeat(n:Int, s:String): String - if (n < 1) { "" } else { s + strRepeat(n - 1, s) } - -def abs(n:Int): Int - if (n < 0) { -n } else { n } - -def baklava(n:Int, end:Int): Unit - // This is definitely the weirdest formatting for an if-else statement that I've ever seen - if (n > end) - unit - else - val numSpaces:Int = abs(n) - stdout.print(strRepeat(numSpaces, " ") + strRepeat(21 - 2 * numSpaces, "*") + "\n") - baklava(n + 1, end) - -baklava(-10, 10) - -``` - -{% endraw %} - -Baklava in [Wyvern](/languages/wyvern) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/x86-64/index.md b/docs/projects/baklava/x86-64/index.md deleted file mode 100644 index 4a97d4af1a..0000000000 --- a/docs/projects/baklava/x86-64/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- alope107 -date: 2023-05-04 -featured-image: baklava-in-every-language.jpg -last-modified: 2023-05-04 -layout: default -tags: -- baklava -- x86-64 -title: Baklava in x86-64 -title1: Baklava -title2: in x86-64 ---- - - - -Welcome to the [Baklava](/projects/baklava) in [x86-64](/languages/x86-64) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```x86-64 -section .data - star db "*" - space db " " - newline db 10 - -section .text - global _start - - -; Stack order (top-to-bottom) - -; Inner loop counter (inner_i) -; Outer loop counter (outer_i) -; Target (11 or -1) -; Incrementor (+1 or -1) - -_start: - mov rax, 1 ; Incrementor is positive for forward pass - push rax - mov rax, 11 ; Target of 11 (exclusive) - push rax - xor rax, rax ; Start outer counter at 0 - -outer_loop: - pop rdx - push rdx ; Peek at the target - cmp rax, rdx - je end_outer ; Exit the loop if we've met the target - - push rax ; Save outer counter - - mov rbx, 10 - sub rbx, rax ; Pad with 10 - outer_i spaces - - space_loop: - cmp rbx, 0 - je end_space ; Exit the loop if we've done the required number of loops - - push rbx ; Save inner counter - - ; print space - mov rax, 1 - mov rdi, 1 - mov rsi, space - mov rdx, 1 - syscall - - pop rbx - dec rbx - jmp space_loop ; Decrement inner counter and keep looping - - end_space: - pop rbx - push rbx ; Peek at the outer counter - - shl rbx, 1 - inc rbx ; Loop 2 * outer_i + 1 times - - star_loop: - cmp rbx, 0 - je end_star ; Exit the loop if we've done the required number of loops - - push rbx ; Save inner counter - - ; print star - mov rax, 1 - mov rdi, 1 - mov rsi, star - mov rdx, 1 - syscall - - pop rbx - dec rbx - jmp star_loop ; Decrement inner counter and keep looping - - end_star: - ; print newline - mov rax, 1 - mov rdi, 1 - mov rsi, newline - mov rdx, 1 - syscall - - - pop rax ; outer_i - pop rdx ; target - pop rdi ; incrementor - push rdi - push rdx ; put target and incremenetor back on stack in the same place - - add rax, rdi ; increment in the current direction - jmp outer_loop ; keep looping - -end_outer: - pop rdx - cmp rdx, -1 - je end ; If our target is negative, then we've done both passes and can jump to end - - pop rax - mov rax, -1 - push rax ; Set incrmentor to negative for backwards pass - - mov rax, -1 - push rax ; Set target to -1 for backwards pass - - mov rax, 9 - jmp outer_loop ; Start outer_i at 9. The forward pass handled 10 - -end: - ; Exit with return value of 0 - mov rax, 60 - xor rdi, rdi - syscall -``` - -{% endraw %} - -Baklava in [x86-64](/languages/x86-64) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/yoix/index.md b/docs/projects/baklava/yoix/index.md deleted file mode 100644 index 622b9d8650..0000000000 --- a/docs/projects/baklava/yoix/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-03 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-10-03 -layout: default -tags: -- baklava -- yoix -title: Baklava in Yoix -title1: Baklava -title2: in Yoix ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Yoix](/languages/yoix) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```yoix -import yoix.stdio.putchar; -import yoix.math.abs; - -printRepeat(int c, int count) { - int i; - for (i = 0; i < count; i++) { - putchar(c); - } -} - -int i; -for (i = -10; i <= 10; i++) { - int numSpaces = abs(i); - int numStars = 21 - 2 * numSpaces; - printRepeat(' ', numSpaces); - printRepeat('*', numStars); - putchar('\n'); -} - -``` - -{% endraw %} - -Baklava in [Yoix](/languages/yoix) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/baklava/zig/index.md b/docs/projects/baklava/zig/index.md deleted file mode 100644 index 54ed0ff0e3..0000000000 --- a/docs/projects/baklava/zig/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-09-23 -featured-image: baklava-in-every-language.jpg -last-modified: 2024-09-23 -layout: default -tags: -- baklava -- zig -title: Baklava in Zig -title1: Baklava -title2: in Zig ---- - - - -Welcome to the [Baklava](/projects/baklava) in [Zig](/languages/zig) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```zig -const std = @import("std"); - -pub fn main() !void { - const stdout = std.io.getStdOut().writer(); - const spaces = " " ** 10; - const stars = "*" ** 21; - var i: i32 = -10; - while (i <= 10): (i += 1) { - const numSpaces: usize = @intCast(@abs(i)); - const numStars: usize = 21 - numSpaces * 2; - try stdout.print("{s}{s}\n", .{spaces[0..numSpaces], stars[0..numStars]}); - } -} - -``` - -{% endraw %} - -Baklava in [Zig](/languages/zig) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/ada/index.md b/docs/projects/base64-encode-decode/ada/index.md deleted file mode 100644 index 2e5c44d314..0000000000 --- a/docs/projects/base64-encode-decode/ada/index.md +++ /dev/null @@ -1,361 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-09 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-05-09 -layout: default -tags: -- ada -- base64-encode-decode -title: Base64 Encode Decode in Ada -title1: Base64 Encode -title2: Decode in Ada ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Interfaces; use Interfaces; - -procedure Base64_Encode_Decode is - - ------------------------------------------------------------ - -- PUBLIC BASE64 API - ------------------------------------------------------------ - package Base64 is - - -- Validate input - procedure Validate_Input (Input : String; Is_Decode : Boolean); - - -- Encode a raw string into Base64 representation - function Encode (Input : String) return String; - - -- Decode a Base64 string back into raw bytes - function Decode (Input : String) return String; - - -- Raised when input is invalid (bad characters, wrong format) - Encoding_Error : exception; - - end; - - package body Base64 is - - ------------------------------------------------------------ - -- CONSTANTS - ------------------------------------------------------------ - - -- Standard Base64 alphabet (RFC 4648) - Alphabet : constant String := - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - subtype Decode_Value is Integer range -1 .. 63; - - -- Lookup table: maps ASCII characters to Base64 values - type Decode_Table_Type is array (Character) of Decode_Value; - - Decode_Table : Decode_Table_Type := (others => -1); - - ------------------------------------------------------------ - -- INITIALIZATION - ------------------------------------------------------------ - - -- Build decode lookup table once at package initialization - procedure Init_Table is - begin - for I in Alphabet'Range loop - Decode_Table (Alphabet (I)) := I - Alphabet'First; - end loop; - end Init_Table; - - ------------------------------------------------------------ - -- VALIDATION - ------------------------------------------------------------ - - procedure Validate_Input (Input : String; Is_Decode : Boolean) is - - Padding_Seen : Boolean := False; - - function Is_Base64_Char (C : Character) return Boolean is - begin - return - (C in 'A' .. 'Z') - or else (C in 'a' .. 'z') - or else (C in '0' .. '9') - or else C = '+' - or else C = '/' - or else C = '='; - end Is_Base64_Char; - - begin - -- Fail on empty strings for both encode and decode - if Input'Length = 0 then - raise Encoding_Error; - end if; - - -- If not decode, then that's the only check we'll do. - if not Is_Decode then - return; - end if; - - if Input'Length mod 4 /= 0 then - raise Encoding_Error; - end if; - - for I in Input'Range loop - - if not Is_Base64_Char (Input (I)) then - raise Encoding_Error; - end if; - - -- once padding starts, everything after must be '=' - if Input (I) = '=' then - Padding_Seen := True; - elsif Padding_Seen then - raise Encoding_Error; - end if; - - end loop; - end Validate_Input; - - ------------------------------------------------------------ - -- LOW-LEVEL HELPERS - ------------------------------------------------------------ - - -- Convert a Base64 character into its 6-bit numeric value - -- Raises Encoding_Error if character is not valid Base64 - function To_Value (C : Character) return Unsigned_8 is - Value : constant Integer := Decode_Table (C); - begin - if Value < 0 then - raise Encoding_Error; - end if; - return Unsigned_8 (Value); - end To_Value; - - -- Check whether a character is padding ('=') - function Is_Padding (C : Character) return Boolean - is (C = '='); - - ------------------------------------------------------------ - -- ENCODE HELPERS - ------------------------------------------------------------ - - -- Extract up to 3 bytes from input safely (zero-padded if needed) - procedure Get_Block - (Input : String; Index : Positive; B1, B2, B3 : out Unsigned_8) is - begin - B1 := Character'Pos (Input (Index)); - - if Index + 1 <= Input'Last then - B2 := Character'Pos (Input (Index + 1)); - else - B2 := 0; - end if; - - if Index + 2 <= Input'Last then - B3 := Character'Pos (Input (Index + 2)); - else - B3 := 0; - end if; - end Get_Block; - - -- Encode a 3-byte block into 4 Base64 characters - -- Handles padding depending on input availability - procedure Encode_Block - (B1, B2, B3 : Unsigned_8; - Has_B2, Has_B3 : Boolean; - Result : in out String; - Out_Idx : in out Positive) - is - - T1, T2, T3, T4 : Natural; - begin - -- Split 24-bit block into four 6-bit chunks - T1 := Natural (Shift_Right (B1, 2)); - T2 := Natural (Shift_Left (B1 and 3, 4) or Shift_Right (B2, 4)); - T3 := Natural (Shift_Left (B2 and 15, 2) or Shift_Right (B3, 6)); - T4 := Natural (B3 and 63); - - -- Map each chunk into Base64 alphabet - Result (Out_Idx + 0) := Alphabet (T1 + 1); - Result (Out_Idx + 1) := Alphabet (T2 + 1); - - -- Apply padding rules when input is incomplete - Result (Out_Idx + 2) := (if Has_B2 then Alphabet (T3 + 1) else '='); - Result (Out_Idx + 3) := (if Has_B3 then Alphabet (T4 + 1) else '='); - - Out_Idx := Out_Idx + 4; - end Encode_Block; - - ------------------------------------------------------------ - -- DECODE HELPERS - ------------------------------------------------------------ - - -- Decode a single 4-character Base64 block into 1–3 bytes - procedure Decode_Block - (Input : String; - Index : Positive; - Out_Str : in out String; - Out_Idx : in out Positive) - is - C1, C2, C3, C4 : Unsigned_8; - B1, B2, B3 : Unsigned_8; - Has_C3, Has_C4 : Boolean; - begin - C1 := To_Value (Input (Index)); - C2 := To_Value (Input (Index + 1)); - - Has_C3 := not Is_Padding (Input (Index + 2)); - Has_C4 := not Is_Padding (Input (Index + 3)); - - -- First byte (always) - B1 := Shift_Left (C1, 2) or Shift_Right (C2, 4); - Out_Str (Out_Idx) := Character'Val (B1); - Out_Idx := Out_Idx + 1; - - -- Second byte - if Has_C3 then - C3 := To_Value (Input (Index + 2)); - B2 := Shift_Left (C2 and 15, 4) or Shift_Right (C3, 2); - - Out_Str (Out_Idx) := Character'Val (B2); - Out_Idx := Out_Idx + 1; - - if Has_C4 then - C4 := To_Value (Input (Index + 3)); - B3 := Shift_Left (C3 and 3, 6) or C4; - - Out_Str (Out_Idx) := Character'Val (B3); - Out_Idx := Out_Idx + 1; - end if; - end if; - end Decode_Block; - - ------------------------------------------------------------ - -- PUBLIC ENCODE FUNCTION - ------------------------------------------------------------ - function Encode (Input : String) return String is - Result : String (1 .. ((Input'Length + 2) / 3) * 4); - Out_Idx : Positive := Result'First; - In_Idx : Positive := Input'First; - - B1, B2, B3 : Unsigned_8; - begin - Validate_Input (Input, Is_Decode => False); - - -- Process input in 3-byte blocks - while In_Idx <= Input'Last loop - - Get_Block (Input, In_Idx, B1, B2, B3); - - Encode_Block - (B1, - B2, - B3, - Has_B2 => (In_Idx + 1 <= Input'Last), - Has_B3 => (In_Idx + 2 <= Input'Last), - Result => Result, - Out_Idx => Out_Idx); - - In_Idx := In_Idx + 3; - end loop; - - return Result; - end Encode; - - ------------------------------------------------------------ - -- PUBLIC DECODE FUNCTION - ------------------------------------------------------------ - function Decode (Input : String) return String is - Result : String (1 .. (Input'Length / 4) * 3); - Out_Idx : Positive := Result'First; - In_Idx : Positive := Input'First; - begin - Validate_Input (Input, Is_Decode => True); - - -- Process input in 4-character blocks - while In_Idx <= Input'Last loop - Decode_Block (Input, In_Idx, Result, Out_Idx); - In_Idx := In_Idx + 4; - end loop; - - return Result (Result'First .. Out_Idx - 1); - end Decode; - - begin - - -- Initialize lookup table once at package elaboration - Init_Table; - - end Base64; - - procedure Print_Usage is - begin - Put_Line ("Usage: please provide a mode and a string to encode/decode"); - end Print_Usage; - -begin - if Argument_Count /= 2 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - declare - Mode : constant String := Argument (1); - Text : constant String := Argument (2); - begin - if Mode = "encode" then - Put_Line (Base64.Encode (Text)); - - elsif Mode = "decode" then - Put_Line (Base64.Decode (Text)); - - else - Print_Usage; - Set_Exit_Status (Failure); - end if; - - exception - when Base64.Encoding_Error => - Print_Usage; - Set_Exit_Status (Failure); - end; - -end Base64_Encode_Decode; - -``` - -{% endraw %} - -Base64 Encode Decode in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/algol60/index.md b/docs/projects/base64-encode-decode/algol60/index.md deleted file mode 100644 index dbfdd4404f..0000000000 --- a/docs/projects/base64-encode-decode/algol60/index.md +++ /dev/null @@ -1,351 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-10 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-04-10 -layout: default -tags: -- algol60 -- base64-encode-decode -title: Base64 Encode Decode in ALGOL 60 -title1: Base64 Encode -title2: Decode in ALGOL 60 ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please provide a mode and a string to encode/decode\n"); - stop - end usage; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - procedure outAsciiChar(ch); - value ch; - integer ch; - begin - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - outchar( - 1, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ) - end outAsciiChar; - - procedure outCharArray(s, len); - value len; - integer array s; - integer len; - begin - integer i; - for i := 1 step 1 until len do outAsciiChar(s[i]) - end outCharArray; - - comment Input mode. Return the following: - - -1 if invalid mode - - 0 if decode - - 1 if encode; - integer procedure inMode(s, len); - value len; - integer array s; - integer len; - begin - integer mode; - - comment Assume invalid mode; - mode := -1; - - comment Length must be 6 and the last 4 characters must be - c (99) o (111) d (100) e(101); - if len = 6 & s[3] = 99 & s[4] = 111 & s[5] = 100 & s[6] = 101 then - begin - comment Indicate encode if first 2 characters are e (101) and n (110). - Indicate decode if first 2 characters are d (100) and e (101); - if s[1] = 101 & s[2] = 110 then mode := 1 - else if s[1] = 100 & s[2] = 101 then mode := 0 - end; - - inMode := mode - end inMode; - - comment Returns output length; - integer procedure base64Encode(inStr, inLen, outStr); - value inLen; - integer array inStr, outStr; - integer inLen; - begin - integer outLen, i, n1, n2, n3, u; - - outLen := 0; - for i := 1 step 3 until inLen do - begin - comment Convert current 3 characters into 24-bit word, using zero - if past end of string; - n1 := inStr[i]; - n2 := if i + 1 <= inLen then inStr[i + 1] else 0; - n3 := if i + 2 <= inLen then inStr[i + 2] else 0; - u := 65536 * n1 + 256 * n2 + n3; comment (n1 << 16) | (n2 << 8) | n3; - - comment Convert 24-bit word to 4 character code and append to output - string, using pad if past end of string; - outStr[outLen + 1] := codeToBase64Char(inLen, i, u % 262144); comment u >> 18; - outStr[outLen + 2] := codeToBase64Char(inLen, i, u % 4096); comment u >> 12; - outStr[outLen + 3] := codeToBase64Char(inLen, i + 1, u % 64); comment u >> 6; - outStr[outLen + 4] := codeToBase64Char(inLen, i + 2, u); - outLen := outLen + 4 - end; - - base64Encode := outLen - end base64Encode; - - integer procedure mod(x, n); - value x, n; - integer x, n; - begin - mod := x - n * (x % n) - end mod; - - integer procedure codeToBase64Char(inLen, inIdx, u); - value inLen, inIdx, u; - integer inLen, inIdx, u; - begin - integer idx, ch; - - comment Get 6-bit index from code; - idx := mod(u, 64); - - comment - If past end of string, use pad character, = (61) - Else use the following: - - 0 ... 25 -> A (65) ... Z (90) - - 26 ... 51 -> a (97) ... z (122) - - 52 ... 61 -> 0 (48) ... 9 (57) - - 62 -> + (43) - - 63 -> / (47); - if inIdx > inLen then ch := 61 - else if idx >= 0 & idx <= 25 then ch := 65 + idx - else if idx >= 26 & idx <= 51 then ch := 97 - 26 + idx - else if idx >= 52 & idx <= 61 then ch := 48 - 52 + idx - else if idx = 62 then ch := 43 - else ch := 47; - - codeToBase64Char := ch - end codeToBase64Char; - - comment Returns output length if valid Base64 string, negative otherwise; - integer procedure base64Decode(inStr, inLen, outStr); - value inLen; - integer array inStr, outStr; - integer inLen; - begin - integer outLen, padLen, i, n1, n2, n3, n4, u; - - comment Assume invalid Base64 string; - outLen := -1; - - comment Validate input length and number of trailing pad characters; - padLen := countTrailingPads(inStr, inLen); - if mod(inLen, 4) = 0 & padLen <= 2 then - begin - outLen := 0; - i := 1; - inLen := inLen - padLen; - decloop: - if i <= inLen - 1 & outLen >= 0 then - begin - comment Convert current 3 characters into 24-bit word, using zero - if past end of string. If any invalid characters, indicate - invalid input; - n1 := base64CharToIndex(inStr[i]); - n2 := base64CharToIndex(inStr[i + 1]); - n3 := if i + 2 <= inLen then base64CharToIndex(inStr[i + 2]) else 0; - n4 := if i + 3 <= inLen then base64CharToIndex(inStr[i + 3]) else 0; - if n1 < 0 | n2 < 0 | n3 < 0 | n4 < 0 then outLen := -1 - else - begin - comment (n1 << 18) | (n2 << 12) | (n3 << 6) | n4; - u := 262144 * n1 + 4096 * n2 + 64 * n3 + n4; - - comment Convert 24-bit code to characters and append to output - string; - codeToOutStr(outStr, outLen, inLen, i, u % 65536); comment u >> 16; - codeToOutStr(outStr, outLen, inLen, i + 2, u % 256); comment u >> 8; - codeToOutStr(outStr, outLen, inLen, i + 3, u) - end; - - i := i + 4; - goto decloop - end - end; - - base64Decode := outLen - end base64Decode; - - comment Returns Base64 index if valid Base64 character, negative otherwise; - integer procedure base64CharToIndex(ch); - value ch; - integer ch; - begin - integer idx; - - comment - - A (65) ... Z (90) -> 0 ... 25 - - a (97) ... z (122) -> 26 ... 51 - - 0 (48) ... 9 (57) -> 52 ... 61 - - + (43) -> 62 - - / (47) -> 63 - - else -> -1; - if ch >= 65 & ch <= 90 then idx := ch - 65 - else if ch >= 97 & ch <= 122 then idx := ch - 97 + 26 - else if ch >= 48 & ch <= 57 then idx := ch - 48 + 52 - else if ch = 43 then idx := 62 - else if ch = 47 then idx := 63 - else idx := -1; - - base64CharToIndex := idx - end base64CharToIndex; - - integer procedure countTrailingPads(s, len); - value len; - integer array s; - integer len; - begin - integer padLen, i; - - comment Pad character is = (61); - padLen := 0; - i := len; - padloop: - if i >= 1 & s[i] = 61 then - begin - padLen := padLen + 1; - i := i - 1; - goto padloop - end; - - countTrailingPads := padLen - end countTrailingPads; - - procedure codeToOutStr(outStr, outLen, inLen, idx, u); - value u; - integer array outStr; - integer outLen, inLen, idx, u; - begin - if idx <= inLen then - begin - outLen := outLen + 1; - outStr[outLen] := mod(u, 256) - end - end codeToOutStr; - - integer argc, inLen, outLen, mode; - - comment inStr is the input array, outStr is the output array. - outStr must be big enough to hold the longest decode string - (ceil[256 * 4 / 3] = 342); - integer array inStr[1:256], outStr[1:342]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 2 then usage; - - comment Get mode as a string as integer array. Exit if invalid; - inLen := inCharArray(inStr, 256); - mode := inMode(inStr, inLen); - if mode < 0 then usage; - - comment Get string to encode or decode as integer array. Exit if empty; - inLen := inCharArray(inStr, 256); - if inLen < 1 then usage; - - comment If encode mode, Base64 encode string; - if mode = 1 then outLen := base64Encode(inStr, inLen, outStr) - else - begin - comment Base64 decode string. Exit if invalid Base64 string; - outLen := base64Decode(inStr, inLen, outStr); - if outLen < 0 then usage - end; - - comment Output Base64 encode/decode string; - outCharArray(outStr, outLen); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Base64 Encode Decode in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/algol68/index.md b/docs/projects/base64-encode-decode/algol68/index.md deleted file mode 100644 index 0dbb7ca8a9..0000000000 --- a/docs/projects/base64-encode-decode/algol68/index.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-03-28 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-03-28 -layout: default -tags: -- algol68 -- base64-encode-decode -title: Base64 Encode Decode in ALGOL 68 -title1: Base64 Encode -title2: Decode in ALGOL 68 ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a mode and a string to encode/decode")) -); - -STRING base64 chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[@0]; -MODE DECODE_RESULTS = STRUCT(BOOL valid, STRING result); - -PROC base64 encode = (STRING s) STRING: -( - STRING result := ""; - INT s len = UPB s; - BITS n1, n2, n3, u; - FOR n BY 3 TO s len - DO - n1 := BIN ABS s[n]; - n2 := BIN (n + 1 <= s len | ABS s[n + 1] | 0); - n3 := BIN (n + 2 <= s len | ABS s[n + 2] | 0); - u := (n1 SHL 16) OR (n2 SHL 8) OR n3; - result +:= base64 chars[ABS (u SHR 18)]; - result +:= base64 chars[ABS (u SHR 12 AND 16r3f)]; - result +:= (n + 1 <= s len | base64 chars[ABS (u SHR 6 AND 16r3f)] | "="); - result +:= (n + 2 <= s len | base64 chars[ABS (u AND 16r3f)] | "=") - OD; - - result -); - -PROC base64 decode = (STRING s) DECODE_RESULTS: -( - STRING result := ""; - INT s len := UPB s; - INT pad count := count trailing pads(s); - BOOL valid := s len MOD 4 = 0 AND pad count <= 2; - - INT n1, n2, n3, n4; - BITS u; - s len -:= pad count; - FOR n BY 4 TO s len - WHILE valid - DO - n1 := index of(s[n], base64 chars); - n2 := index of(s[n + 1], base64 chars); - n3 := (n + 2 <= s len | index of(s[n + 2], base64 chars) | 0); - n4 := (n + 3 <= s len | index of(s[n + 3], base64 chars) | 0); - valid := n1 >= 0 AND n2 >= 0 AND n3 >= 0 AND n4 >= 0; - IF valid - THEN - u:= (BIN n1 SHL 18) OR (BIN n2 SHL 12) OR (BIN n3 SHL 6) OR BIN n4; - result +:= REPR ABS (u SHR 16); - result +:= (n + 2 <= s len | REPR ABS (u SHR 8 AND 16rff)); - result +:= (n + 3 <= s len | REPR ABS (u AND 16rff) | "") - FI - OD; - - DECODE_RESULTS(valid, result) -); - -PROC count trailing pads = (STRING s) INT: -( - INT s len := UPB s; - INT n := s len; - INT pad count := 0; - WHILE n >= 1 AND n <= s len AND s[n] = "=" - DO - pad count +:= 1; - n -:= 1 - OD; - - pad count -); - -PROC index of = (CHAR c, STRING s) INT: -( - INT start index = LWB s; - INT result := start index - 1; - FOR n FROM start index TO UPB s - WHILE result < start index - DO - IF s[n] = c - THEN - result := n - FI - OD; - - result -); - -# Parse command-line arguments # -STRING mode := argv(4); -STRING s := argv(5); -IF UPB s = 0 -THEN - usage; - stop -FI; - -STRING result; -IF mode = "encode" -THEN - result := base64 encode(s) -ELIF mode = "decode" -THEN - DECODE_RESULTS decode result := base64 decode(s); - IF NOT (valid OF decode result) - THEN - usage; - stop - FI; - - result := result OF decode result -ELSE - usage; - stop -FI; - -printf(($gl$, result)) - -``` - -{% endraw %} - -Base64 Encode Decode in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/awk/index.md b/docs/projects/base64-encode-decode/awk/index.md deleted file mode 100644 index 7ee3fd80ee..0000000000 --- a/docs/projects/base64-encode-decode/awk/index.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-27 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-04-27 -layout: default -tags: -- awk -- base64-encode-decode -title: Base64 Encode Decode in AWK -title1: Base64 Encode -title2: Decode in AWK ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a mode and a string to encode/decode" - exit(1) -} - -# Awk doesn't have an ord() function, so create a global table from -# character to ASCII value -function init_ord_table( i) { - for (i = 0; i <= 255; i++) { - ord_table[sprintf("%c", i)] = i - } -} - -function ord(s) { - return (length(s) > 0) ? ord_table[s] : 0 -} - -function chr(i) { - return sprintf("%c", i) -} - -function init_base64_chars() { - base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -} - -function base64_encode(s, i, result, len, n, u) { - result = "" - len = length(s) - for (i = 1; i <= len; i += 3) { - n[1] = ord(substr(s, i, 1)) - n[2] = ord(substr(s, i + 1, 1)) - n[3] = ord(substr(s, i + 2, 1)) - u = or(lshift(n[1], 16), lshift(n[2], 8), n[3]) - result = result base64_encode_char(u, i, len, 18) - result = result base64_encode_char(u, i, len, 12) - result = result base64_encode_char(u, i + 1, len, 6) - result = result base64_encode_char(u, i + 2, len, 0) - } - - return result -} - -function base64_encode_char(u, idx, len, shifts) { - return (idx <= len) ? substr(base64_chars, 1 + and(rshift(u, shifts), 0x3f), 1) : "=" -} - -# Return Base64 decoded string or 0 if invalid input -function base64_decode(s, len, result, num_pads, c, i, k) { - len = length(s) - if ((len % 4) != 0) { - return 0 - } - - num_pads = 0 - while (len > 0 && substr(s, len, 1) == "=") { - num_pads++ - len-- - } - - if (num_pads > 2) { - return 0 - } - - result = "" - for (i = 1; i <= len; i += 4) { - for (k = 1; k <= 4; k++) { - c[k] = base64_decode_index(s, i + k - 1, len) - if (c[k] < 0) { - return 0 - } - } - - u = or(lshift(c[1], 18), lshift(c[2], 12), lshift(c[3], 6), c[4]) - result = result base64_decode_char(u, i, len, 16) - result = result base64_decode_char(u, i + 2, len, 8) - result = result base64_decode_char(u, i + 3, len, 0) - } - - return result -} - -# Return Base64 index if valid character, -1 otherwise -function base64_decode_index(s, idx, len) { - return (idx <= len) ? index(base64_chars, substr(s, idx, 1)) - 1 : 0 -} - -function base64_decode_char(u, idx, len, shifts) { - return (idx <= len) ? chr(and(rshift(u, shifts), 0xff)) : "" -} - -BEGIN { - if (ARGC < 3 || !ARGV[2]) { - usage() - } - - init_ord_table() - init_base64_chars() - - mode = ARGV[1] - s = ARGV[2] - switch (mode) { - case "encode": - result = base64_encode(s) - break - case "decode": - result = base64_decode(s) - if (result == 0) { - usage() - } - break - default: - usage() - } - - print result -} - -``` - -{% endraw %} - -Base64 Encode Decode in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/bash/index.md b/docs/projects/base64-encode-decode/bash/index.md deleted file mode 100644 index 2c398d6256..0000000000 --- a/docs/projects/base64-encode-decode/bash/index.md +++ /dev/null @@ -1,273 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-06 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-04-06 -layout: default -tags: -- base64-encode-decode -- bash -title: Base64 Encode Decode in Bash -title1: Base64 Encode -title2: Decode in Bash ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -# References: -# - Convert character to ASCII code, and ASCII code to character: -# https://unix.stackexchange.com/questions/92447/bash-script-to-get-ascii-values-for-alphabet - -BASE64_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - -function usage() { - echo "Usage: please provide a mode and a string to encode/decode" - exit 1 -} - -# Base64 encode string -# -# Input: -# - $1 = string to encode -# Output: Base64 encoded string -function base64_encode() { - local result="" - local len=${#1} - for ((n=0; n<${len}; n+=3)) - do - # Convert 3-character chunk into 24-bit value - local n1=$(ord "${1:${n}:1}") - local n2=$(ord "${1:$((${n}+1)):1}") - local n3=$(ord "${1:$((${n}+2)):1}") - local u=$(( (${n1}<<16)|(${n2}<<8)|${n3} )) - - # Convert 24-bit value to 4 Base64 characters - c1="$(base64_encode_char ${u} 18 ${n} 0 ${len})" - c2="$(base64_encode_char ${u} 12 ${n} 0 ${len})" - c3="$(base64_encode_char ${u} 6 ${n} 1 ${len})" - c4="$(base64_encode_char ${u} 0 ${n} 2 ${len})" - result="${result}${c1}${c2}${c3}${c4}" - done - - echo "${result}" -} - -# Base64 encode character -# -# Inputs: -# - $1 = 24-bit value -# - $2 = number of shifts -# - $3 = string index -# - $4 = string index offset (0 - 2) -# - $5 = length of string -# Output: Base64 encoded character -function base64_encode_char() { - local u=${1} - local shifts=${2} - local index=$((${3}+${4})) - local len=${5} - local result="=" - if [[ ${index} -lt ${len} ]] - then - result="${BASE64_CHARS:$(( (${u}>>${shifts})&0x3f )):1}" - fi - - echo "${result}" -} - -# Base64 decode string -# -# Input: -# - $1 = Base64 string to decode -# Output: Base64 decoded string -# Exits if invalid Base64 string is invalid -function base64_decode() { - # Error if string not a multiple of 4 - local s="${1}" - local len=${#s} - if [[ $((${len}%4)) -ne 0 ]] - then - usage - fi - - # Trim trailing pad characters - local pads=0 - while [[ ${len} -gt 0 ]] && [ "${s:$((${len}-1)):1}" = "=" ] - do - len=$((${len}-1)) - pads=$((${pads}+1)) - done - s="${s:0:${len}}" - - # Error if too many pad characters - if [[ ${pads} -gt 2 ]] - then - usage - fi - - local result="" - for ((n=0; n<${len}; n+=4)) - do - # Convert 4-character chunk into indices - local n1=$(base64_decode_index "${s:${n}:1}") - local n2=$(base64_decode_index "${s:$((${n}+1)):1}") - local n3=$(base64_decode_index "${s:$((${n}+2)):1}") - local n4=$(base64_decode_index "${s:$((${n}+3)):1}") - - # Exit if any invalid Base64 characters - if [[ ${n1} -lt 0 ]] || [[ ${n2} -lt 0 ]] || [[ ${n3} -lt 0 ]] || [[ ${n4} -lt 0 ]] - then - usage - fi - - # Convert indices to 24-bit value - local u=$(( (${n1}<<18)|(${n2}<<12)|(${n3}<<6)|${n4} )) - - # Convert 24-bit value to Base64 decoded characters - c1="$(base64_decode_char ${u} 16 ${n} 0 ${len})" - c2="$(base64_decode_char ${u} 8 ${n} 2 ${len})" - c3="$(base64_decode_char ${u} 0 ${n} 3 ${len})" - result="${result}${c1}${c2}${c3}" - done - - echo "${result}" -} - -# Convert character to Base64 decode index -# -# Input: -# - $1 = character -# Output: -# - Base64 decode index if character is a valid Base64 character, -# 0 if empty string, -1 otherwise -function base64_decode_index() { - result=$(ord "${1}") - case "${1}" in - "") - result=0 - ;; - [A-Z]) - # result = ord(char) - ord("A") - result=$((${result}-65)) - ;; - [a-z]) - # result = ord(char) - ord("a") + 26 - result=$((${result}-97+26)) - ;; - [0-9]) - # result = ord(char) - ord("0") + 52 - result=$((${result}-48+52)) - ;; - +) - result=62 - ;; - /) - result=63 - ;; - *) - result=-1 - ;; - esac - - echo ${result} -} - -# Base64 decode character -# -# Inputs: -# - $1 = 24-bit value -# - $2 = number of shifts -# - $3 = string index -# - $4 = string index offset (0 - 3) -# - $5 = length of string -# Output: Base64 decoded character -function base64_decode_char() { - local u=${1} - local shifts=${2} - local index=$((${3}+${4})) - local len=${5} - local result="" - if [[ ${index} -lt ${len} ]] - then - result="$(chr $(( (${u}>>${shifts})&0xff )) )" - fi - - echo "${result}" -} - -# Convert ASCII code to character -# -# Input: -# - $1 = ASCII code -# Output: character -function chr() { - printf "\\$(printf '%03o' "${1}")" -} - -# Convert character to ASCII code -# -# Input: -# - $1 = character -# Output: -# - ASCII code if character is not empty, 0 otherwise -function ord() { - LC_CTYPE=C printf '%d' "'${1}" -} - -# Error if string -if [ -z "$2" ] -then - usage -fi - -# Base64 encode/decode string if valid mode, error otherwise -case "$1" in - encode) - base64_encode "$2" - ;; - - decode) - base64_decode "$2" - ;; - - *) - usage - ;; -esac - -``` - -{% endraw %} - -Base64 Encode Decode in [Bash](/languages/bash) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/beef/index.md b/docs/projects/base64-encode-decode/beef/index.md deleted file mode 100644 index efeb8f06b7..0000000000 --- a/docs/projects/base64-encode-decode/beef/index.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-03-30 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-03-30 -layout: default -tags: -- base64-encode-decode -- beef -title: Base64 Encode Decode in Beef -title1: Base64 Encode -title2: Decode in Beef ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace Base64EncodeDecode; - -class Program -{ - static String base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - public static void Usage() - { - Console.WriteLine("Usage: please provide a mode and a string to encode/decode"); - Environment.Exit(0); - } - - public static void Base64Encode(StringView str, ref String result) - { - int len = str.Length; - result.Clear(); - int numChunks = (len + 2) / 3; - result.Reserve(4 * numChunks); - for (int n = 0; n < len; n += 3) - { - int n1 = (int)str[n]; - int n2 = (n + 1 < len) ? (int)str[n + 1] : 0; - int n3 = (n + 2 < len) ? (int)str[n + 2] : 0; - int u = (n1 << 16) | (n2 << 8) | n3; - result += base64Chars[u >> 18]; - result += base64Chars[(u >> 12) & 0x3f]; - result += (n + 1 < len) ? base64Chars[(u >> 6) & 0x3f] : '='; - result += (n + 2 < len) ? base64Chars[u & 0x3f] : '='; - } - } - - public static bool Base64Decode(StringView str, ref String result) - { - int len = str.Length; - int padCount = countTrailingPads(str); - result.Clear(); - bool valid = len % 4 == 0 && padCount <= 2; - if (valid) - { - int numChunks = len / 4; - result.Reserve(3 * numChunks - padCount); - len -= padCount; - for (int n = 0; n < len && valid; n += 4) - { - int n1 = base64Index(str[n]); - int n2 = base64Index(str[n + 1]); - int n3 = (n + 2 < len) ? base64Index(str[n + 2]) : 0; - int n4 = (n + 3 < len) ? base64Index(str[n + 3]) : 0; - int u = (n1 << 18) | (n2 << 12) | (n3 << 6) | n4; - valid = (n1 >= 0) && (n2 >= 0) && (n3 >= 0) && (n4 >= 0); - if (valid) - { - result += (char8)(u >> 16); - result.Append( - (n + 2 < len) ? - scope String((char8)((u >> 8) & 0xff), 1) : - "" - ); - result.Append( - (n + 3 < len) ? - scope String((char8)(u & 0xff), 1) : - "" - ); - } - } - } - - return valid; - } - - static int countTrailingPads(StringView str) - { - int padCount = 0; - int index = str.Length - 1; - while (index >= 0 && str[index] == '=') - { - padCount += 1; - index -= 1; - } - - return padCount; - } - - static int base64Index(char8 ch) - { - int n = -1; - if (ch >= 'A' && ch <= 'Z') - { - n = ch - 'A'; - } - else if (ch >= 'a' && ch <= 'z') - { - n = ch - 'a' + 26; - } - else if (ch >= '0' && ch <= '9') - { - n = ch - '0' + 52; - } - else if (ch == '+') - { - n = 62; - } - else if (ch == '/') - { - n = 63; - } - - return n; - } - - public static int Main(String[] args) - { - if (args.Count < 2 || args[1].Length < 1) - { - Usage(); - } - - String result = scope String(); - switch (args[0]) - { - case "encode": - Base64Encode(args[1], ref result); - case "decode": - if (!Base64Decode(args[1], ref result)) - { - Usage(); - } - default: - Usage(); - } - - Console.WriteLine(result); - return 0; - } -} - -``` - -{% endraw %} - -Base64 Encode Decode in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/c-plus-plus/index.md b/docs/projects/base64-encode-decode/c-plus-plus/index.md deleted file mode 100644 index 3e4f5409b3..0000000000 --- a/docs/projects/base64-encode-decode/c-plus-plus/index.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-04 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-05-05 -layout: default -tags: -- base64-encode-decode -- c-plus-plus -title: Base64 Encode Decode in C++ -title1: Base64 Encode -title2: Decode in C++ ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include - -enum class Mode { encode, decode }; - -namespace base64 { - -constexpr std::string_view alphabet = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - -constexpr auto make_table() { - std::array t{}; - t.fill(-1); - - for (std::size_t i = 0; i < alphabet.size(); ++i) - t[static_cast(alphabet[i])] = - static_cast(i); - - return t; -} - -constexpr auto table = make_table(); - -constexpr bool is_b64(unsigned char c) { return table[c] != -1; } -constexpr bool is_pad(char c) { return c == '='; } - -bool valid(std::string_view s) { - using std::all_of; - - if (s.empty() || s.size() % 4 != 0) return false; - - const auto first_pad = s.find('='); - - if (first_pad == std::string_view::npos) { - return all_of(s.begin(), s.end(), is_b64); - } - - // padding must be in last 2 chars only - if (s.size() - first_pad > 2) return false; - - return all_of(s.begin(), s.begin() + first_pad, is_b64) && - all_of(s.begin() + first_pad, s.end(), is_pad); -} - -} // namespace base64 - -std::string encode(std::string_view input) { - std::string out; - out.reserve(((input.size() + 2) / 3) * 4); - - std::uint32_t buffer = 0; - int bits = 0; - - for (unsigned char c : input) { - buffer = (buffer << 8) | c; - bits += 8; - - while (bits >= 6) { - bits -= 6; - out.push_back(base64::alphabet[(buffer >> bits) & 0x3F]); - } - } - - if (bits > 0) { - out.push_back(base64::alphabet[(buffer << (6 - bits)) & 0x3F]); - } - - while (out.size() % 4 != 0) out.push_back('='); - - return out; -} - -struct DecodeResult { - bool ok{}; - std::string value; - std::string_view error; -}; - -DecodeResult decode(std::string_view input) { - if (!base64::valid(input)) return {false, {}, "invalid base64"}; - - std::string out; - out.reserve((input.size() / 4) * 3); - - std::uint32_t buffer = 0; - int bits = 0; - - for (unsigned char c : input) { - if (c == '=') break; - - int v = base64::table[c]; - if (v < 0) return {false, {}, "invalid character"}; - - buffer = (buffer << 6) | static_cast(v); - bits += 6; - - while (bits >= 8) { - bits -= 8; - out.push_back(static_cast((buffer >> bits) & 0xFF)); - } - } - - return {true, std::move(out), {}}; -} - -void usage() { - std::cerr << "Usage: please provide a mode and a string to encode/decode\n"; - std::exit(1); -} - -int main(int argc, char** argv) { - if (argc != 3) usage(); - - std::string_view mode = argv[1]; - std::string_view text = argv[2]; - - if (text.empty()) usage(); - - if (mode == "encode") { - std::cout << encode(text) << '\n'; - } else if (mode == "decode") { - auto res = decode(text); - if (!res.ok) usage(); - std::cout << res.value << '\n'; - } else { - usage(); - } -} -``` - -{% endraw %} - -Base64 Encode Decode in [C++](/languages/c-plus-plus) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/c-sharp/index.md b/docs/projects/base64-encode-decode/c-sharp/index.md deleted file mode 100644 index 828e7e4e5d..0000000000 --- a/docs/projects/base64-encode-decode/c-sharp/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-29 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-05-13 -layout: default -tags: -- base64-encode-decode -- c-sharp -title: Base64 Encode Decode in C# -title1: Base64 Encode -title2: Decode in C# ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Text; - -return args switch -{ - ["encode", var value] when !string.IsNullOrWhiteSpace(value) - => Encode(value), - - ["decode", var value] when !string.IsNullOrWhiteSpace(value) - => Decode(value), - - _ => Usage() -}; - -static int Encode(string value) -{ - Console.WriteLine(Convert.ToBase64String(Encoding.ASCII.GetBytes(value))); - return 0; -} - -static int Decode(string value) -{ - byte[] buffer = new byte[value.Length]; - if (!Convert.TryFromBase64String(value, buffer, out int written)) - return Usage(); - - Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, written)); - return 0; -} - -static int Usage() -{ - Console.Error.WriteLine("Usage: please provide a mode and a string to encode/decode"); - return 1; -} -``` - -{% endraw %} - -Base64 Encode Decode in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/c/index.md b/docs/projects/base64-encode-decode/c/index.md deleted file mode 100644 index fc60ca5df9..0000000000 --- a/docs/projects/base64-encode-decode/c/index.md +++ /dev/null @@ -1,267 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-28 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-04-15 -layout: default -tags: -- base64-encode-decode -- c -title: Base64 Encode Decode in C -title1: Base64 Encode -title2: Decode in C ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include -#include - -static const unsigned char base64_alphabet[65] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -static unsigned char *base64_encode(const unsigned char *input, size_t length, - size_t *output_length); -static unsigned char *base64_decode(const unsigned char *input, size_t length, - size_t *output_length); -static int is_valid_base64(const char *string); -static void show_usage(void); - -int main(int argc, char *argv[]) -{ - if (argc != 3) - show_usage(); - - const char *mode = argv[1]; - const char *input_text = argv[2]; - - if (strcmp(mode, "encode") == 0) - { - if (strlen(input_text) == 0) - show_usage(); - - size_t input_length = strlen(input_text); - unsigned char *data = base64_encode((const unsigned char *)input_text, - input_length, NULL); - if (!data) - show_usage(); - - printf("%s\n", data); - free(data); - } - else if (strcmp(mode, "decode") == 0) - { - if (strlen(input_text) == 0 || !is_valid_base64(input_text)) - show_usage(); - - size_t input_length = strlen(input_text); - size_t decoded_length; - unsigned char *data = base64_decode((const unsigned char *)input_text, - input_length, &decoded_length); - if (!data || decoded_length == 0) - show_usage(); - - fwrite(data, 1, decoded_length, stdout); - fflush(stdout); - free(data); - } - else - { - show_usage(); - } - - return 0; -} - -static void show_usage(void) -{ - fprintf(stderr, - "Usage: please provide a mode and a string to encode/decode\n"); - exit(EXIT_FAILURE); -} - -static int is_valid_base64(const char *str) -{ - if (!str) - return 0; - - size_t length = strlen(str); - - // Base64 strings must have length multiple of 4 - if (length == 0 || length % 4 != 0) - return 0; - - // Each character must be alphanumeric, '+' or '/', or '=' for padding - for (size_t i = 0; i < length; i++) - { - unsigned char c = (unsigned char)str[i]; - if (!isalnum(c) && c != '+' && c != '/' && c != '=') - return 0; - } - - // Padding '=' only allowed at the end (max two) - size_t padding_count = 0; - if (length >= 1 && str[length - 1] == '=') - padding_count++; - if (length >= 2 && str[length - 2] == '=') - padding_count++; - // '=' should not appear before the padding section - for (size_t i = 0; i < length - padding_count; i++) - if (str[i] == '=') - return 0; - - return 1; -} - -static unsigned char *base64_encode(const unsigned char *input, size_t length, - size_t *output_length) -{ - if (!input) - return NULL; - - // 4 chars for every 3 bytes, rounded up - size_t encoded_length = 4 * ((length + 2) / 3); - unsigned char *data = malloc(encoded_length + 1); // +1 for NUL terminator - if (!data) - return NULL; - - size_t input_index = 0, encoded_index = 0; - while (input_index < length) - { - uint32_t buffer = 0; - int remaining = (int)(length - input_index); - - // Pack up to 3 bytes into 24 bits buffer - buffer |= ((uint32_t)input[input_index++]) << 16; - if (remaining > 1) - buffer |= ((uint32_t)input[input_index++]) << 8; - if (remaining > 2) - buffer |= (uint32_t)input[input_index++]; - - // Extract 6-bit groups and map to Base64 chars - data[encoded_index++] = base64_alphabet[(buffer >> 18) & 0x3F]; - data[encoded_index++] = base64_alphabet[(buffer >> 12) & 0x3F]; - data[encoded_index++] = - (remaining > 1) ? base64_alphabet[(buffer >> 6) & 0x3F] : '='; - data[encoded_index++] = - (remaining > 2) ? base64_alphabet[buffer & 0x3F] : '='; - } - - data[encoded_index] = '\0'; // Null-terminate output string - - if (output_length) - *output_length = encoded_index; - return data; -} - -static unsigned char *base64_decode(const unsigned char *input, size_t length, - size_t *output_length) -{ - if (!input) - return NULL; - - unsigned char decoding_table[256]; - memset(decoding_table, 0x80, 256); // 0x80 marks invalid chars - - for (int i = 0; i < 64; i++) - decoding_table[base64_alphabet[i]] = (unsigned char)i; - decoding_table['='] = 0; - - // Count valid base64 characters (ignore whitespace or invalid chars) - size_t valid_char_count = 0; - for (size_t i = 0; i < length; i++) - if (decoding_table[input[i]] != 0x80) - valid_char_count++; - - if (valid_char_count == 0 || valid_char_count % 4 != 0) - return NULL; - - size_t decoded_length = valid_char_count / 4 * 3; - unsigned char *data = malloc(decoded_length); - if (!data) - return NULL; - - size_t input_index = 0, decoded_index = 0; - unsigned char block[4]; - int padding_count = 0; - size_t block_char_count = 0; - - while (input_index < length) - { - unsigned char val = decoding_table[input[input_index++]]; - if (val == 0x80) - continue; // skip invalid chars (including whitespace) - - if (input[input_index - 1] == '=') - padding_count++; - block[block_char_count++] = val; - - if (block_char_count == 4) - { - data[decoded_index++] = (block[0] << 2) | (block[1] >> 4); - data[decoded_index++] = (block[1] << 4) | (block[2] >> 2); - data[decoded_index++] = (block[2] << 6) | block[3]; - block_char_count = 0; - - if (padding_count) - { - if (padding_count == 1) - { - decoded_index--; - } - else if (padding_count == 2) - { - decoded_index -= 2; - } - else - { - free(data); - return NULL; // invalid padding length - } - break; - } - } - } - - if (output_length) - *output_length = decoded_index; - return data; -} - -``` - -{% endraw %} - -Base64 Encode Decode in [C](/languages/c) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/cobol/index.md b/docs/projects/base64-encode-decode/cobol/index.md deleted file mode 100644 index 2d332ba94e..0000000000 --- a/docs/projects/base64-encode-decode/cobol/index.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-01 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-05-01 -layout: default -tags: -- base64-encode-decode -- cobol -title: Base64 Encode Decode in COBOL -title1: Base64 Encode -title2: Decode in COBOL ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. base64-util. - -data division. -working-storage section. - -01 cmd-args. - 05 arg-count pic 9(4) comp. - 05 execution-mode pic x(10). - 05 input-text pic x(4096). - -01 text-work-area. - 05 output-text pic x(8192). - 05 input-len pic 9(5) comp. - 05 str-idx pic 9(5) comp. - 05 out-pos pic 9(5) comp value 0. - 05 char-val pic 9(4) comp. - 05 out-char pic x. - -01 raw-bytes. - 05 byte-1 pic 9(4) comp. - 05 byte-2 pic 9(4) comp. - 05 byte-3 pic 9(4) comp. - -01 b64-indices. - 05 idx-1 pic 9(4) comp. - 05 idx-2 pic 9(4) comp. - 05 idx-3 pic 9(4) comp. - 05 idx-4 pic 9(4) comp. - 05 table-idx pic 9(4) comp. - -01 base64-table pic x(64) value - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/". - -01 decode-map. - 05 decode-val occurs 256 times pic s9(4) comp. - -procedure division. - -main. - accept arg-count from argument-number - - if arg-count < 2 - perform show-usage - end-if - - accept execution-mode from argument-value - accept input-text from argument-value - - move function length(function trim(input-text)) to input-len - - if input-len = 0 - perform show-usage - end-if - - perform build-decode-table - - evaluate function lower-case(execution-mode) - when "encode" - perform do-encode - when "decode" - perform do-decode - when other - perform show-usage - end-evaluate - - if out-pos > 0 - display output-text(1:out-pos) - end-if - - move 0 to return-code - goback. - -build-decode-table. - perform varying table-idx from 1 by 1 until table-idx > 256 - move -1 to decode-val(table-idx) - end-perform - - perform varying table-idx from 1 by 1 until table-idx > 64 - move function ord(base64-table(table-idx:1)) to char-val - compute decode-val(char-val) = table-idx - 1 - end-perform. - -do-encode. - move 1 to str-idx - move 0 to out-pos - - perform until str-idx > input-len - move 0 to byte-1 byte-2 byte-3 - - compute byte-1 = function ord(input-text(str-idx:1)) - 1 - - if str-idx + 1 <= input-len - compute byte-2 = function ord(input-text(str-idx + 1:1)) - 1 - end-if - - if str-idx + 2 <= input-len - compute byte-3 = function ord(input-text(str-idx + 2:1)) - 1 - end-if - - compute idx-1 = byte-1 / 4 - compute idx-2 = function mod(byte-1, 4) * 16 + byte-2 / 16 - compute idx-3 = function mod(byte-2, 16) * 4 + byte-3 / 64 - compute idx-4 = function mod(byte-3, 64) - - move base64-table(idx-1 + 1:1) to out-char - perform append-char - move base64-table(idx-2 + 1:1) to out-char - perform append-char - - if str-idx + 1 <= input-len - move base64-table(idx-3 + 1:1) to out-char - else - move "=" to out-char - end-if - perform append-char - - if str-idx + 2 <= input-len - move base64-table(idx-4 + 1:1) to out-char - else - move "=" to out-char - end-if - perform append-char - - add 3 to str-idx - end-perform. - -do-decode. - if function mod(input-len, 4) not = 0 - perform show-usage - end-if - - move 1 to str-idx - move 0 to out-pos - - perform until str-idx > input-len - perform validate-block - - move function ord(input-text(str-idx:1)) to char-val - move decode-val(char-val) to idx-1 - - move function ord(input-text(str-idx + 1:1)) to char-val - move decode-val(char-val) to idx-2 - - compute byte-1 = idx-1 * 4 + idx-2 / 16 - move function char(byte-1 + 1) to out-char - perform append-char - - if input-text(str-idx + 2:1) not = "=" - move function ord(input-text(str-idx + 2:1)) to char-val - move decode-val(char-val) to idx-3 - compute byte-2 = function mod(idx-2, 16) * 16 + idx-3 / 4 - move function char(byte-2 + 1) to out-char - perform append-char - end-if - - if input-text(str-idx + 3:1) not = "=" - move function ord(input-text(str-idx + 3:1)) to char-val - move decode-val(char-val) to idx-4 - compute byte-3 = function mod(idx-3, 4) * 64 + idx-4 - move function char(byte-3 + 1) to out-char - perform append-char - end-if - - add 4 to str-idx - end-perform. - -validate-block. - if input-text(str-idx:1) = "=" or input-text(str-idx + 1:1) = "=" - perform show-usage - end-if - - perform varying char-val from 0 by 1 until char-val > 3 - move function ord(input-text(str-idx + char-val:1)) to byte-1 - if decode-val(byte-1) = -1 and input-text(str-idx + char-val:1) not = "=" - perform show-usage - end-if - end-perform - - if input-text(str-idx + 2:1) = "=" - if input-text(str-idx + 3:1) not = "=" or str-idx + 4 <= input-len - perform show-usage - end-if - end-if - - if input-text(str-idx + 3:1) = "=" - if str-idx + 4 <= input-len - perform show-usage - end-if - end-if. - -append-char. - add 1 to out-pos - move out-char to output-text(out-pos:1). - -show-usage. - display "Usage: please provide a mode and a string to encode/decode" - move 1 to return-code - stop run. -``` - -{% endraw %} - -Base64 Encode Decode in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/commodore-basic/index.md b/docs/projects/base64-encode-decode/commodore-basic/index.md deleted file mode 100644 index f5dc9e13ff..0000000000 --- a/docs/projects/base64-encode-decode/commodore-basic/index.md +++ /dev/null @@ -1,207 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-03-30 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-03-30 -layout: default -tags: -- base64-encode-decode -- commodore-basic -title: Base64 Encode Decode in Commodore BASIC -title1: Base64 Encode Decode -title2: in Commodore BASIC ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 C$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -20 GOSUB 1000: REM Get mode -30 M$ = S$ -40 GOSUB 1000: REM Get string -50 IF S$ = "" THEN GOTO 170 -60 IF M$ = "encode" THEN GOTO 90 -70 IF M$ = "decode" THEN GOTO 120 -80 GOTO 170 -90 REM Base64 encode string -100 GOSUB 2000 -110 GOTO 150 -120 REM Base64 decode string -130 GOSUB 3000 -140 IF E <> 0 THEN GOTO 170 -150 PRINT R$ -160 END -170 PRINT "Usage: please provide a mode and a string to encode/decode" -180 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of value or input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 13 OR C = 255 THEN RETURN: REM end of value or input -1050 S$ = S$ + A$ -1060 GOTO 1020 -2000 REM Base64 encode string -2001 REM Inputs: -2002 REM - C$ = Base64 characters -2003 REM - S$ = string to encode -2004 REM Output: R$ = encoded string -2010 R$ = "" -2020 L = LEN(S$) -2030 FOR N = 1 TO L STEP 3 -2031 REM N1 = char code(S$[N]) -2032 REM N2 = char code(S$[N + 1]) if N + 1 <= L else 0 -2033 REM N3 = char code(S$[N + 2]) if N + 2 <= L else 0 -2040 N1 = ASC(MID$(S$, N, 1)) -2050 N2 = 0: IF N + 1 <= L THEN N2 = ASC(MID$(S$, N + 1, 1)) -2060 N3 = 0: IF N + 2 <= L THEN N3 = ASC(MID$(S$, N + 2, 1)) -2065 REM U = (N1 << 16) | (N2 << 8) | N3 -2070 U = (N1 * 65536) + (N2 * 256) + N3 -2071 REM R$ += Base64 chars[1 + (U >> 18)] -2072 REM R$ += Base64 chars[1 + ((U >> 12) & 0x3f)] -2073 REM R$ += Base64 chars[1 + ((U >> 6) & 0x3f)] if N + 1 <= L else "=" -2074 REM R$ += Base64 chars[1 + (U & 0x3f)] if N + 2 <= L else "=" -2080 D = 262144: REM D = 1 << 18 -2090 FOR B = 0 TO 23 STEP 6 -2100 GOSUB 2200 -2110 D = INT(D / 64): REM D >>= 6 -2120 NEXT B -2130 NEXT N -2140 RETURN -2200 REM Append Base64 character to result -2201 REM Inputs: -2202 REM - C$ = Base64 characters -2203 REM - U = 24-bit representation of 3 characters of input string -2204 REM - N = current string index -2205 REM - L = length of string to encode -2206 REM - D = divisor (2 ** number of shifts) -2207 REM - B = input string index in bits -2208 REM - R$ = current Base64 encoded string -2209 REM Output: R$ = new Base64 encoded string -2210 A$ = "=" -2220 IF N + INT(B / 8) > L THEN GOTO 2250 -2230 T = INT(U / D) -2240 A$ = MID$(C$, 1 + T - 64 * INT(T / 64), 1) -2250 R$ = R$ + A$ -2260 RETURN -3000 REM Base64 decode string -3001 REM Inputs: -3002 REM - C$ = Base64 characters -3003 REM - S$ = string to decode -3004 REM Outputs: -3005 REM - R$ = encode string -3006 REM - E = 0 if no errors, 1 otherwise -3010 R$ = "" -3020 L = LEN(S$) -3025 REM P = number of trailing pad chars -3030 GOSUB 3300 -3035 REM Error if string length not a multiple of 4 or more than 2 pad chars -3040 E = (L AND 3) <> 0 OR P > 2 -3045 REM Trim trailing pad characters -3050 L = L - P -3060 N = 1 -3070 IF N > L OR E <> 0 THEN GOTO 3220 -3071 REM N1 = base64 index(S$[N]) -3072 REM N2 = base64 index(S$[N + 1]) if N + 1 <= L else 0 -3073 REM N3 = base64 index(S$[N + 2]) if N + 2 <= L else 0 -3074 REM N4 = base64 index(S$[N + 3]) if N + 3 <= L else 0 -3080 I = 0: GOSUB 3400: N1 = K -3090 I = 1: GOSUB 3400: N2 = K -3100 I = 2: GOSUB 3400: N3 = K -3110 I = 3: GOSUB 3400: N4 = K -3115 REM Error if invalid Base64 character -3120 E = (N1 < 0) OR (N2 < 0) OR (N3 < 0) OR (N4 < 0) -3130 IF E <> 0 THEN GOTO 3070 -3135 REM U = (N1 << 18) | (N2 << 12) | (N3 << 6) | N4 -3140 U = N1 * 262144 + N2 * 4096 + N3 * 64 + N4 -3141 REM R$ += char(U >> 16) -3142 REM R$ += char((U >> 8) & 0xff) if N + 2 <= L else "" -3143 REM R$ += char(U & 0xff) if N + 3 <= L else "" -3150 D = 65536: REM D = 1 << 16 -3160 FOR I = 1 TO 3 -3170 GOSUB 3600 -3180 D = INT(D / 256): REM D = D >> 8 -3190 NEXT I -3200 N = N + 4 -3210 GOTO 3070 -3220 RETURN -3300 REM Count number of trailing pad characters -3301 REM Inputs: -3302 REM - S$ = Base64 string to decode -3303 REM - L = length of string -3304 REM Output: P = number of trailing pad characters -3310 I = L -3320 P = 0 -3330 IF I < 1 OR MID$(S$, I, 1) <> "=" THEN GOTO 3370 -3340 P = P + 1 -3350 I = I - 1 -3360 GOTO 3330 -3370 RETURN -3400 REM Get Base64 index -3401 REM Inputs: -3402 REM - S$ = Base64 string to decode -3403 REM - N = current string index -3404 REM - I = input string offset in bytes -3405 REM - L = length in string -3406 REM Output: K = Base64 index if valid, -1 otherwise -3410 K = 0 -3420 IF N + I > L THEN GOTO 3510 -3430 A$ = MID$(S$, N + I, 1) -3440 K = ASC(A$) -3450 IF A$ >= "A" AND A$ <= "Z" THEN K = K - ASC("A"): GOTO 3510 -3460 IF A$ >= "a" AND A$ <= "z" THEN K = K - ASC("a") + 26: GOTO 3510 -3470 IF A$ >= "0" AND A$ <= "9" THEN K = K - ASC("0") + 52: GOTO 3510 -3480 IF A$ = "+" THEN K = 62: GOTO 3510 -3490 IF A$ = "/" THEN K = 63: GOTO 3510 -3500 K = -1 -3510 RETURN -3600 REM Append Base64 decoded character to result -3601 REM Inputs: -3602 REM - U = 24-bit representation of 4 Base64 indices of input string -3603 REM - N = current string index -3604 REM - L = length of string to encode -3605 REM - D = divisor (2 ** number of shifts) -3606 REM - I = input string index in bytes -3607 REM - R$ = current Base64 decoded string -3608 REM Output: R$ = new Base64 decoded string -3610 IF N + I > L THEN GOTO 3640 -3620 T = INT(U / D) -3630 R$ = R$ + CHR$(T - 256 * INT(T / 256)) -3640 RETURN - -``` - -{% endraw %} - -Base64 Encode Decode in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/euphoria/index.md b/docs/projects/base64-encode-decode/euphoria/index.md deleted file mode 100644 index 919c4fccb6..0000000000 --- a/docs/projects/base64-encode-decode/euphoria/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-03-30 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-03-30 -layout: default -tags: -- base64-encode-decode -- euphoria -title: Base64 Encode Decode in Euphoria -title1: Base64 Encode -title2: Decode in Euphoria ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/base64.e -include std/text.e -include std/regex.e as re - -procedure usage() - puts( - STDOUT, - "Usage: please provide a mode and a string to encode/decode\n" - ) - abort(0) -end procedure - -constant re_not_base64_chars = re:new("[^A-Za-z0-9+/]") - --- Base64 decode --- --- Although the built-in Base64 decode is available, it does not do a very good --- job of error checking the input other that making sure that the input length --- is a multiple of 4. The output of this function is -1 if the input string --- is invalid, the Base64 decoded string otherwise. -function base64_decode(sequence str) - -- Error if more than 2 pad trailing characters - atom str_length = length(str) - atom pad_length = str_length - length(trim_tail(str, "=")) - if pad_length > 2 - then - return -1 - end if - - -- Remove trailing pad characters - str_length -= pad_length - - -- Error if invalid Base64 characters - if re:has_match(re_not_base64_chars, str[1..str_length]) - then - return -1 - end if - - -- Use Base64 decode library function - return base64:decode(str) -end function - --- Check command-line arguments -sequence argv = command_line() -if length(argv) < 5 or length(argv[5]) = 0 -then - usage() -end if - -sequence mode = argv[4] -sequence str = argv[5] -object result -switch mode -do - case "encode" - then - result = base64:encode(str) - case "decode" - then - result = base64_decode(str) - if atom(result) - then - usage() - end if - case else - usage() -end switch - -printf(STDOUT, "%s\n", {result}) - -``` - -{% endraw %} - -Base64 Encode Decode in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/f-sharp/index.md b/docs/projects/base64-encode-decode/f-sharp/index.md deleted file mode 100644 index 3064e16501..0000000000 --- a/docs/projects/base64-encode-decode/f-sharp/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-06 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-04-06 -layout: default -tags: -- base64-encode-decode -- f-sharp -title: Base64 Encode Decode in F# -title1: Base64 Encode -title2: Decode in F# ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System -open System.Text - -let usage = "Usage: please provide a mode and a string to encode/decode" - -module Base64 = - let private (|Encode|Decode|InvalidMode|) (s: string) = - match s.Trim().ToLowerInvariant() with - | "encode" -> Encode - | "decode" -> Decode - | _ -> InvalidMode - - let private (|NonEmpty|Empty|) (s: string) = - if String.IsNullOrWhiteSpace s then Empty else NonEmpty s - - let encode = - function - | NonEmpty s -> s |> Encoding.UTF8.GetBytes |> Convert.ToBase64String |> Ok - | Empty -> Error usage - - let decode = - function - | NonEmpty s -> - try - Convert.FromBase64String s |> Encoding.UTF8.GetString |> Ok - with _ -> - Error usage - | Empty -> Error usage - - let choose = - function - | Encode -> Ok encode - | Decode -> Ok decode - | InvalidMode -> Error usage - - let run (mode, input) = choose mode |> Result.bind (fun f -> f input) - -module Helpers = - let parseArgs argv = - match argv with - | [| mode; input |] -> Ok (mode, input) - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.bind Base64.run - |> Helpers.handleResult - -``` - -{% endraw %} - -Base64 Encode Decode in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/go/index.md b/docs/projects/base64-encode-decode/go/index.md deleted file mode 100644 index ee18fdfb43..0000000000 --- a/docs/projects/base64-encode-decode/go/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Zia -date: 2025-03-29 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-03-29 -layout: default -tags: -- base64-encode-decode -- go -title: Base64 Encode Decode in Go -title1: Base64 Encode -title2: Decode in Go ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "encoding/base64" - "fmt" - "os" -) - -func die() { - fmt.Println("Usage: please provide a mode and a string to encode/decode") - os.Exit(1) -} - -func main() { - if len(os.Args) < 3 { - die() - } - - enc := base64.StdEncoding - - if len(os.Args[2]) == 0 { - die() - } - - switch os.Args[1] { - case "encode": - fmt.Println(enc.EncodeToString([]byte(os.Args[2]))) - return - case "decode": - s, err := enc.DecodeString(os.Args[2]) - if err != nil { - die() - } - - fmt.Println(string(s)) - default: - die() - } -} - -``` - -{% endraw %} - -Base64 Encode Decode in [Go](/languages/go) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/haskell/index.md b/docs/projects/base64-encode-decode/haskell/index.md deleted file mode 100644 index bdab982b04..0000000000 --- a/docs/projects/base64-encode-decode/haskell/index.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-17 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-05-17 -layout: default -tags: -- base64-encode-decode -- haskell -title: Base64 Encode Decode in Haskell -title1: Base64 Encode -title2: Decode in Haskell ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import qualified Data.ByteString.Char8 as BC -import qualified Data.ByteString as BS -import Data.ByteString (ByteString) -import Data.Bits -import Data.Word (Word8) -import Data.Maybe (fromMaybe) -import System.Environment - -alphabet :: ByteString -alphabet = BC.pack "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - -chunksOf :: Int -> ByteString -> [ByteString] -chunksOf n bs - | BC.null bs = [] - | otherwise = let (chunk, xs) = BC.splitAt n bs in chunk : chunksOf n xs - -get :: Int -> ByteString -> Word8 -get i bs = if i >= BS.length bs then 0 else bs `BS.index` i - -encode :: String -> String -encode = BC.unpack . BC.concat . map encodeChunk . chunksOf 3 . BC.pack - where - encodeChunk chunk = - let - (b0, b1, b2) = (get 0 chunk, get 1 chunk, get 2 chunk) - c0 = BC.index alphabet $ fromIntegral $ b0 `shiftR` 2 - c1 = BC.index alphabet $ fromIntegral $ (b0 .&. 0x03) `shiftL` 4 .|. b1 `shiftR` 4 - c2 = BC.index alphabet $ fromIntegral $ (b1 .&. 0x0F) `shiftL` 2 .|. b2 `shiftR` 6 - c3 = BC.index alphabet $ fromIntegral $ (b2 .&. 0x3F) - in case BS.length chunk of - 3 -> BC.pack [c0, c1, c2, c3] - 2 -> BC.pack [c0, c1, c2, '='] - 1 -> BC.pack [c0, c1, '=', '='] - _ -> BC.empty - -decode :: String -> String -decode = BC.unpack . BC.concat . map decodeChunk . chunksOf 4 . BC.pack - where - charToVal w = fromIntegral $ fromMaybe 0 (BS.elemIndex w alphabet) - decodeChunk chunk = - let - v0 = charToVal (get 0 chunk) - v1 = charToVal (get 1 chunk) - v2 = charToVal (get 2 chunk) - v3 = charToVal (get 3 chunk) - - b0 = (v0 `shiftL` 2) .|. (v1 `shiftR` 4) - b1 = ((v1 .&. 0x0F) `shiftL` 4) .|. (v2 `shiftR` 2) - b2 = ((v2 .&. 0x03) `shiftL` 6) .|. v3 - in case BC.count '=' chunk of - 0 -> BS.pack [b0, b1, b2] - 1 -> BS.pack [b0, b1] - 2 -> BS.pack [b0] - _ -> BS.empty - -isBase64 :: String -> Bool -isBase64 str = length str `mod` 4 == 0 - && all (`BC.elem` alphabet) b64 - && length padding <= 2 - && all (== '=') padding - where (b64, padding) = break (== '=') str - -main :: IO () -main = do - args <- getArgs - case args of - [_, ""] -> putStrLn usage - ["encode", inputStr] -> putStrLn $ encode inputStr - ["decode", inputStr] -> - if isBase64 inputStr - then putStrLn $ decode inputStr - else putStrLn usage - _ -> putStrLn usage - where usage = "Usage: please provide a mode and a string to encode/decode" - -``` - -{% endraw %} - -Base64 Encode Decode in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/index.md b/docs/projects/base64-encode-decode/index.md deleted file mode 100644 index 728c47365c..0000000000 --- a/docs/projects/base64-encode-decode/index.md +++ /dev/null @@ -1,375 +0,0 @@ ---- -date: 2025-03-25 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-05-17 -layout: default -tags: -- base64-encode-decode -title: Base64 Encode Decode -title1: Base64 Encode -title2: Decode ---- - - - -Welcome to the Base64 Encode Decode page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- rzuckerm -- Zia - -## Description - -### Introduction - -Base64 is a popular method of encoding strings and other data. It can encode -images, text, JSON, and almost any other format as well. It is also URL-safe. - -In this project you will be encoding normal text to Base64-encoded text and -decoding Base64-encoded text into normal text. - -### Base64 Alphabet - -From [Base64 Table from Wikipedia][1], this is the Base64 Alphabet: - -| Index | Binary | Char || Index | Binary | Char || Index | Binary | Char || Index | Binary | Char | -| :---: | :-----: | :--: || :---: | :-----: | :--: || :---: | :-----: | :--: || :---: | :-----: | :--: | -| 0 | 000000 | A || 16 | 010000 | Q || 32 | 100000 | g || 48 | 110000 | w | -| 1 | 000001 | B || 17 | 010001 | R || 33 | 100001 | h || 49 | 110001 | x | -| 2 | 000010 | C || 18 | 010010 | S || 34 | 100010 | i || 50 | 110010 | y | -| 3 | 000011 | D || 19 | 010011 | T || 35 | 100011 | j || 51 | 110011 | z | -| 4 | 000100 | E || 20 | 010100 | U || 36 | 100100 | k || 52 | 110100 | 0 | -| 5 | 000101 | F || 21 | 010101 | V || 37 | 100101 | l || 53 | 110101 | 1 | -| 6 | 000110 | G || 22 | 010110 | W || 38 | 100110 | m || 54 | 110110 | 2 | -| 7 | 000111 | H || 23 | 010111 | X || 39 | 100111 | n || 55 | 110111 | 3 | -| 8 | 001000 | I || 24 | 011000 | Y || 40 | 101000 | o || 56 | 111000 | 4 | -| 9 | 001001 | J || 25 | 011001 | Z || 41 | 101001 | p || 57 | 111001 | 5 | -| 10 | 001010 | K || 26 | 011010 | a || 42 | 101010 | q || 58 | 111010 | 6 | -| 11 | 001011 | L || 27 | 011011 | b || 43 | 101011 | r || 59 | 111011 | 7 | -| 12 | 001100 | M || 28 | 011100 | c || 44 | 101100 | s || 60 | 111100 | 8 | -| 13 | 001101 | N || 29 | 011101 | d || 45 | 101101 | t || 61 | 111101 | 9 | -| 14 | 001110 | O || 30 | 011110 | e || 46 | 101110 | u || 62 | 111110 | + | -| 15 | 001111 | P || 31 | 011111 | f || 47 | 101111 | v || 63 | 111111 | / | -| | | || | | || | | || | Padding | = | - -This alphabet is used for both encode and decode. - -### Encode - -Base64 encode works as follows: - -- Split the data up into 3-byte chunks (let's ignore the case where the last chunk - smaller than 3 bytes; that will be discussed later): -- For each 3-byte chunk: - - Convert each byte to 8-bit binary, 24 bits in total. - - Divide the 24-bit value into 4 groups of 6 bits. - - Use each 6-bit group as an index into the above table to get Base64 characters. - -For example, let's use the string `kitten`. The 3-byte chunks are `kit` and `ten`. Let's -focus on the first chunk: `kit`. Using 8-bit ASCII: - -- `k` = `107` (`01101011`) -- `i` = `105` (`01101001`) -- `t` = `116` (`01110100`) - -So, the 24-bit group is this: - -``` -01101011 01101001 01110100 -``` - -Dividing this in 6-bit groups gives this: - -``` -011010 110110 100101 110100 -``` - -Since it's easier to work with this as decimal, the table indices are these: - -``` -26 54 37 52 -``` - -Looking these indices up in the table results a Base64 string of `a2l0`. -Following the same procedure for `ten` (left as an exercise for the reader), -the Base64 string is `dGVu`. Together, `kitten` encodes to `a2l0dGVu`. - -For the case when the last chunk is not 3 bytes long, extend the last -bits with zeros until it is 6 bits long, and add padding characters until -the last Base64 string is 4 bytes long. - -For example, let's consider the case where the last chunk is `k`: - -- From the above example, `k` is `01101011`. -- Dividing this into 6-bit groups results in `011010 11`. -- Extending the last group results in `011010 110000`. -- Converting this to decimal results in `26 48`. -- Looking up those values in the table results in `aw`. -- Since this is only 2 bytes long, 2 padding characters are added: `aw==`. - -For the final encode example, let's consider the case when the last chunk is -`ki`: - -- From the above example, `ki` is `01101011 01101001`. -- Dividing this into 6-bit groups results in `011010 110110 1001`. -- Extending the last group results in `011010 110110 100100`. -- Convert this to decimal results in `26 54 36`. -- Looking up those values in the table results in `a2k`. -- Since this is only 3 bytes long, 1 padding character is added: `a2k=`. - -### Decode - -Before dividing into the algorithm for how to decode a Base64 string, let's -talk about some rules for what constitutes a valid Base64 string: - -- Its length must be evenly divisible by 4. -- Only the last 4-byte chunk may have padding characters. -- The number of padding characters must be either 1 or 2. -- Each byte in the Base64 string must be in the table or be a padding - character. - -Assuming the Base64 string is valid, and ignoring the case where the last -4-byte chunk has padding characters, decode works as follows: - -- Divide the Base64 string into 4-byte chunks. -- For each 4-byte chunk: - - Look up each byte in the table to get the corresponding index. - - Convert the indices into 4 groups of 6-bit values, 24 bits in total. - - Divide the 24 bits into 3 8-bit bytes. - -Let's use the Base64 string `a2l0dGVu`. The 4-byte chunks are `a2l0` and -`dGVu`. Let's focus on the first chunk: `a2l0`. - -Looking up each byte in the table results in this: - -- `a` is index `26` (`011010`) -- `2` is index `54` (`110110`) -- `l` is index `37` (`100101`) -- `0` is index `52` (`110100`) - -Converting the binary indices to 8-bit groups results in this: - -``` -01101011 01101001 01110100 -``` - -Convert this back to ASCII results in this: - -- `01101011` (`107`) = `k` -- `01101001` (`105`) = `i` -- `01110100` (`116`) = `t` - -Following the same procedure for `dGVu` (left as an exercise for the reader), -decodes to `ten`. Together, `a2l0dGVu` encodes to `kitten`. - -For the case when the last chunk has pad characters, decode any complete -8-bit chunk, and ignore any chunk that is shorter than 8 bits. - -For example, let's consider the case where the last chunk is `aw==`. Looking -up the non-pad characters results in this: - -- `a` is index `26` (`011010`) -- `w` is index `48` (`110000`) - -Dividing this into 8-byte groups results in this: - -``` -01101011 0000 -``` - -Ignoring the last 4 bits results in this: - -- `01101011` (`107`) = `k` - -Therefore, this decodes to `k`. - -For the final decode example, let's consider the case where the last chunk -is `a2k=`. Looking up the non-pad characters results in this: - -- `a` is index `26` (`011010`) -- `2` is index `54` (`110110`) -- `k` is index `36` (`100100`) - -Dividing this into 8-byte groups results in this: - -``` -01101011 01101001 00 -``` - -Ignoring the last 2 bits results in this: - -- `01101011` (107) = `k` -- `01101001` (105) = `i` - -Therefore, this decodes to `ki`. - -### Further Reading - -You can read more about Base64 in [Wikipedia][2]. - -[1]: https://en.wikipedia.org/wiki/Base64#Base64_table_from_RFC_4648 -[2]: https://en.wikipedia.org/wiki/Base64 - - -## Requirements - -Write a program that accepts two parameters: the mode (`encode` or `decode`) and -some text. - -- If the mode is `decode`, it should print the decoded Base64 text. -- If the mode is `encode`, it should print the encoded text. -- It should print an error message and exit with an error when the input is - invalid. - -```console -$ ./base64-encode-decode.lang "encode" "hello world" -aGVsbG8gd29ybGQ= -$ ./base64-encode-decode.lang "decode" "aGVsbG8gd29ybGQ=" -hello world -``` - -Acceptable language utilities include language features and built-in libraries. -External dependencies are unacceptable. Remember, the goal is to show off -language features and utilities. - -In this project, the algorithm must handle ASCII strings. You don't need to -worry about handling a string in the general case. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Base64 Encode Decode. -In order to keep things simple, we split up the testing as follows: - -- Base64 Encode Valid Tests -- Base64 Decode Valid Tests -- Base64 Invalid Inputs Tests -- Base64 Invalid Encode Tests -- Base64 Invalid Decode Tests - -### Base64 Encode Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Lowercase String | "encode" "hello world" | "aGVsbG8gd29ybGQ=" | -| Long String | "encode" "They swam along the boat at incredible speeds." | "VGhleSBzd2FtIGFsb25nIHRoZSBib2F0IGF0IGluY3JlZGlibGUgc3BlZWRzLg==" | -| Numbers | "encode" "1234567890" | "MTIzNDU2Nzg5MA==" | -| Symbols | "encode" "xyz!#$%&()*+,-./:;<=>?@[\\]^_`{\|}~" | "eHl6ISMkJSYoKSorLC0uLzo7PD0+P0BbXF1eX2B7fH1+" | -| All Base64 Characters | "encode" "! }gggIIT55;qqs!!Gjjb??=~~2$$+;;i::x..4kk,ppnoo" | "ISAgfWdnZ0lJVDU1O3FxcyEhR2pqYj8/PX5+MiQkKzs7aTo6eC4uNGtrLHBwbm9v" | - -### Base64 Decode Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Lowercase String | "decode" "aGVsbG8gd29ybGQ=" | "hello world" | -| Long String | "decode" "VGhleSBzd2FtIGFsb25nIHRoZSBib2F0IGF0IGluY3JlZGlibGUgc3BlZWRzLg==" | "They swam along the boat at incredible speeds." | -| Numbers | "decode" "MTIzNDU2Nzg5MA==" | "1234567890" | -| Symbols | "decode" "eHl6ISMkJSYoKSorLC0uLzo7PD0+P0BbXF1eX2B7fH1+" | "xyz!#$%&()*+,-./:;<=>?@[\\]^_`{\|}~" | -| All Base64 Characters | "decode" "ISAgfWdnZ0lJVDU1O3FxcyEhR2pqYj8/PX5+MiQkKzs7aTo6eC4uNGtrLHBwbm9v" | "! }gggIIT55;qqs!!Gjjb??=~~2$$+;;i::x..4kk,ppnoo" | - -### Base64 Invalid Inputs Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Invalid Mode | "blue" "Oh look a Pascal triangle" | - -All of these tests should output the following: - -``` -Usage: please provide a mode and a string to encode/decode -``` - -### Base64 Invalid Encode Tests - -| Description | Input | -| ----------- | ----- | -| Missing String | "encode" | -| Empty String | "encode" "" | - -All of these tests should output the following: - -``` -Usage: please provide a mode and a string to encode/decode -``` - -### Base64 Invalid Decode Tests - -| Description | Input | -| ----------- | ----- | -| Missing String | "decode" | -| Empty String | "decode" "" | -| Length Number Not Multiple Of 4 | "decode" "hello+world" | -| Invalid Characters | "decode" "hello world=" | -| Too Many Pad Characters At End | "decode" "MTIzNDU2Nzg5M===" | -| Pad Characters In Middle | "decode" "MTIzNDU2=Nzg5M==" | - -All of these tests should output the following: - -``` -Usage: please provide a mode and a string to encode/decode -``` - - -## Articles - -There are 29 articles: - -- [Base64 Encode Decode in ALGOL 60](/projects/base64-encode-decode/algol60) -- [Base64 Encode Decode in ALGOL 68](/projects/base64-encode-decode/algol68) -- [Base64 Encode Decode in AWK](/projects/base64-encode-decode/awk) -- [Base64 Encode Decode in Ada](/projects/base64-encode-decode/ada) -- [Base64 Encode Decode in Bash](/projects/base64-encode-decode/bash) -- [Base64 Encode Decode in Beef](/projects/base64-encode-decode/beef) -- [Base64 Encode Decode in C](/projects/base64-encode-decode/c) -- [Base64 Encode Decode in C#](/projects/base64-encode-decode/c-sharp) -- [Base64 Encode Decode in C++](/projects/base64-encode-decode/c-plus-plus) -- [Base64 Encode Decode in COBOL](/projects/base64-encode-decode/cobol) -- [Base64 Encode Decode in Commodore BASIC](/projects/base64-encode-decode/commodore-basic) -- [Base64 Encode Decode in Euphoria](/projects/base64-encode-decode/euphoria) -- [Base64 Encode Decode in F#](/projects/base64-encode-decode/f-sharp) -- [Base64 Encode Decode in Go](/projects/base64-encode-decode/go) -- [Base64 Encode Decode in Haskell](/projects/base64-encode-decode/haskell) -- [Base64 Encode Decode in Java](/projects/base64-encode-decode/java) -- [Base64 Encode Decode in JavaScript](/projects/base64-encode-decode/javascript) -- [Base64 Encode Decode in Mathematica](/projects/base64-encode-decode/mathematica) -- [Base64 Encode Decode in PHP](/projects/base64-encode-decode/php) -- [Base64 Encode Decode in Pascal](/projects/base64-encode-decode/pascal) -- [Base64 Encode Decode in PowerShell](/projects/base64-encode-decode/powershell) -- [Base64 Encode Decode in Python](/projects/base64-encode-decode/python) -- [Base64 Encode Decode in Ruby](/projects/base64-encode-decode/ruby) -- [Base64 Encode Decode in Rust](/projects/base64-encode-decode/rust) -- [Base64 Encode Decode in Swift](/projects/base64-encode-decode/swift) -- [Base64 Encode Decode in Tcl](/projects/base64-encode-decode/tcl) -- [Base64 Encode Decode in TypeScript](/projects/base64-encode-decode/typescript) -- [Base64 Encode Decode in Visual Basic](/projects/base64-encode-decode/visual-basic) -- [Base64 Encode Decode in Zig](/projects/base64-encode-decode/zig) - -*** - - \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/java/index.md b/docs/projects/base64-encode-decode/java/index.md deleted file mode 100644 index bce6d84754..0000000000 --- a/docs/projects/base64-encode-decode/java/index.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-04-10 -layout: default -tags: -- base64-encode-decode -- java -title: Base64 Encode Decode in Java -title1: Base64 Encode -title2: Decode in Java ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.nio.charset.StandardCharsets; -import java.util.Base64; - -public class Base64EncodeDecode { - public static void main(String[] args) { - if (args == null || args.length != 2) { - usage(); - } - - String mode = args[0]; - String input = args[1]; - - if (mode == null || input == null || mode.isEmpty() || input.isEmpty()) { - usage(); - } - - switch (mode) { - case "encode" -> encode(input); - case "decode" -> decode(input); - default -> usage(); - } - } - - private static void encode(String input) { - byte[] bytes = input.getBytes(StandardCharsets.UTF_8); - String encoded = Base64.getEncoder().encodeToString(bytes); - System.out.println(encoded); - } - - - private static void decode(String input) { - if (!looksLikeBase64(input)) { - usage(); - } - - try { - byte[] decoded = Base64.getDecoder().decode(input); - String output = new String(decoded, StandardCharsets.UTF_8); - System.out.println(output); - } catch (IllegalArgumentException ex) { - usage(); - } - } - - private static boolean looksLikeBase64(String input) { - - if (input.isEmpty() || (input.length() % 4 != 0)) { - return false; - } - - int len = input.length(); - int pad = 0; - - for (int i = 0; i < len; i++) { - char c = input.charAt(i); - - if (c == '=') { - pad++; - } else { - if (pad > 0) return false; // padding only at end - if (!isBase64Char(c)) return false; - } - } - - int padCount = 0; - for (int i = input.length() - 1; i >= 0 && input.charAt(i) == '='; i--) { - padCount++; - } - - return padCount <= 2; - } - - private static boolean isBase64Char(char c) { - return (c >= 'A' && c <= 'Z') - || (c >= 'a' && c <= 'z') - || (c >= '0' && c <= '9') - || c == '+' || c == '/'; - } - - private static void usage() { - System.out.println("Usage: please provide a mode and a string to encode/decode"); - System.exit(1); - } -} -``` - -{% endraw %} - -Base64 Encode Decode in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/javascript/index.md b/docs/projects/base64-encode-decode/javascript/index.md deleted file mode 100644 index 5e37d1e7ce..0000000000 --- a/docs/projects/base64-encode-decode/javascript/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Eshaan Walia -date: 2025-10-06 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-10-06 -layout: default -tags: -- base64-encode-decode -- javascript -title: Base64 Encode Decode in JavaScript -title1: Base64 Encode Decode -title2: in JavaScript ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -#!/usr/bin/env node - -function usageAndExit() { - console.error("Usage: please provide a mode and a string to encode/decode"); - process.exit(1); -} - -function isValidBase64(str) { - // Check length multiple of 4 - if (str.length % 4 !== 0) return false; - // Only A–Z, a–z, 0–9, +, /, = allowed - if (!/^[A-Za-z0-9+/]*={0,2}$/.test(str)) return false; - // = only allowed at end, at most two - const idx = str.indexOf("="); - if (idx !== -1 && idx < str.length - 2) { - // e.g. “ab==cd” invalid - return false; - } - return true; -} - -function encodeBase64(input) { - // Use Buffer in Node.js - return Buffer.from(input, "ascii").toString("base64"); -} - -function decodeBase64(input) { - // Validate first - if (!isValidBase64(input)) { - usageAndExit(); - } - // Buffer will ignore invalid trailing bits - return Buffer.from(input, "base64").toString("ascii"); -} - -function main() { - const args = process.argv.slice(2); - if (args.length < 2) { - usageAndExit(); - } - const mode = args[0]; - const text = args[1]; - - if (!text) { - usageAndExit(); - } - - if (mode === "encode") { - console.log(encodeBase64(text)); - } else if (mode === "decode") { - console.log(decodeBase64(text)); - } else { - usageAndExit(); - } -} - -if (require.main === module) { - main(); -} - - -``` - -{% endraw %} - -Base64 Encode Decode in [JavaScript](/languages/javascript) was written by: - -- Eshaan Walia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/mathematica/index.md b/docs/projects/base64-encode-decode/mathematica/index.md deleted file mode 100644 index 35253ef299..0000000000 --- a/docs/projects/base64-encode-decode/mathematica/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-30 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-04-30 -layout: default -tags: -- base64-encode-decode -- mathematica -title: Base64 Encode Decode in Mathematica -title1: Base64 Encode Decode -title2: in Mathematica ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -ClearAll[base64Main]; - -NonEmptyStringQ = StringQ[#] && StringTrim[#] =!= "" &; - -ValidBase64Q[s_String] := - StringLength[s] > 0 && - Mod[StringLength[s], 4] == 0 && - StringMatchQ[s, RegularExpression["^[A-Za-z0-9+/]*={0,2}$"]]; - -base64Main["encode", s_String?NonEmptyStringQ] := - StringTrim[ExportString[s, "Base64"]]; - -base64Main["decode", s_String?ValidBase64Q] := - StringTrim[ImportString[s, "Base64"]]; - -base64Main[___] := "Usage: please provide a mode and a string to encode/decode"; - -validCases = { - {"encode", "hello world"}, - {"encode", "They swam along the boat at incredible speeds."}, - {"encode", "1234567890"}, - {"encode", "xyz!#$%&()*+,-./:;<=>?@[\\]^_`{|}~"}, - {"encode", "! }gggIIT55;qqs!!Gjjb??=~~2$$+;;i::x..4kk,ppnoo"}, - {"decode", "aGVsbG8gd29ybGQ="}, - {"decode", "VGhleSBzd2FtIGFsb25nIHRoZSBib2F0IGF0IGluY3JlZGlibGUgc3BlZWRzLg=="}, - {"decode", "MTIzNDU2Nzg5MA=="}, - {"decode", "eHl6ISMkJSYoKSorLC0uLzo7PD0+P0BbXF1eX2B7fH1+"}, - {"decode", "ISAgfWdnZ0lJVDU1O3FxcyEhR2pqYj8/PX5+MiQkKzs7aTo6eC4uNGtrLHBwbm9v"} -}; - -invalidCases = { - {}, - {""}, - {"encode"}, - {"encode", ""}, - {"decode"}, - {"decode", ""}, - {"blue", "Oh look a Pascal triangle"}, - {"decode", "hello+world"}, - {"decode", "hello world="}, - {"decode", "MTIzNDU2Nzg5M==="}, - {"decode", "MTIzNDU2=Nzg5M=="} -}; - -runTest[{a___}] := Print[base64Main[a]]; -Scan[runTest, Join[validCases, invalidCases]]; -``` - -{% endraw %} - -Base64 Encode Decode in [Mathematica](/languages/mathematica) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/pascal/index.md b/docs/projects/base64-encode-decode/pascal/index.md deleted file mode 100644 index 3bf0295fdf..0000000000 --- a/docs/projects/base64-encode-decode/pascal/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-07-22 -layout: default -tags: -- base64-encode-decode -- pascal -title: Base64 Encode Decode in Pascal -title1: Base64 Encode -title2: Decode in Pascal ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program Base64EncodeDecode; - -{$mode objfpc}{$H+} - -uses - base64, - Classes, - SysUtils; - -procedure Usage; -begin - Writeln('Usage: please provide a mode and a string to encode/decode'); - Halt(1); -end; - -function IsBase64Char(c: char): boolean; -begin - Result := (c in ['A'..'Z', 'a'..'z', '0'..'9', '+', '/', '=']); -end; - -function IsValidBase64(const s: string): boolean; -var - i, L, padCount, firstPadPos: integer; -begin - L := Length(s); - - if (L = 0) or (L mod 4 <> 0) then - Exit(False); - - for i := 1 to L do - if not IsBase64Char(s[i]) then - Exit(False); - - padCount := 0; - for i := L downto 1 do - if s[i] = '=' then - Inc(padCount) - else - Break; - - if padCount > 2 then - Exit(False); - - firstPadPos := Pos('=', s); - if (firstPadPos > 0) and (firstPadPos <= L - padCount) then - Exit(False); - - Result := True; -end; - -var - mode, textarg, outstr: string; -begin - if ParamCount <> 2 then - Usage; - - mode := LowerCase(ParamStr(1)); - textarg := ParamStr(2); - - if textarg = '' then - Usage; - - if mode = 'encode' then - begin - outstr := EncodeStringBase64(textarg); - Writeln(outstr); - end - else if (mode = 'decode') then - begin - if not IsValidBase64(textarg) then - Usage; - - outstr := DecodeStringBase64(textarg); - if outstr = '' then - Usage; - - Writeln(outstr); - end - else - Usage; -end. - -``` - -{% endraw %} - -Base64 Encode Decode in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/php/index.md b/docs/projects/base64-encode-decode/php/index.md deleted file mode 100644 index 830047302c..0000000000 --- a/docs/projects/base64-encode-decode/php/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-03-30 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-03-30 -layout: default -tags: -- base64-encode-decode -- php -title: Base64 Encode Decode in PHP -title1: Base64 Encode -title2: Decode in PHP ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide a mode and a string to encode/decode" - Exit 1 -} - -function Get-Base64Encode([string]$Str) { - $Bytes = [Text.Encoding]::Ascii.GetBytes($Str) - [Convert]::ToBase64String($Bytes) -} - -function Get-Base64Decode([string]$Str) { - $Bytes = [Convert]::FromBase64String($Str) - [Text.Encoding]::Ascii.GetString($Bytes) -} - -if ($args.Length -lt 2 -or -not $args[1]) { - Show-Usage -} - -$Mode = $args[0] -$Str = $args[1] -switch ($Mode) { - "encode" { - $Result = Get-Base64Encode($Str) - } - "decode" { - try { - $Result = Get-Base64Decode($Str) - } catch [Management.Automation.MethodInvocationException] { - Show-Usage - } - } - default { - Show-Usage - } -} - -Write-Host $Result - -``` - -{% endraw %} - -Base64 Encode Decode in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/python/index.md b/docs/projects/base64-encode-decode/python/index.md deleted file mode 100644 index b69d87860d..0000000000 --- a/docs/projects/base64-encode-decode/python/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- rzuckerm -- Zia -date: 2025-03-25 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-04-01 -layout: default -tags: -- base64-encode-decode -- python -title: Base64 Encode Decode in Python -title1: Base64 Encode -title2: Decode in Python ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import base64 -import binascii -import sys -from typing import NoReturn - - -def usage() -> NoReturn: - print("Usage: please provide a mode and a string to encode/decode") - sys.exit(1) - - -def base64_encode(s: str) -> str: - return base64.b64encode(s.encode("ascii")).decode("ascii") - - -def base64_decode(s: str) -> str: - return base64.b64decode(s.encode("ascii"), validate=True).decode("ascii") - - -def main() -> None | NoReturn: - if len(sys.argv) < 3 or not sys.argv[2]: - usage() - - mode = sys.argv[1] - s = sys.argv[2] - if mode == "encode": - result = base64_encode(s) - elif mode == "decode": - try: - result = base64_decode(s) - except binascii.Error: - usage() - else: - usage() - - print(result) - - -if __name__ == "__main__": - main() - -``` - -{% endraw %} - -Base64 Encode Decode in [Python](/languages/python) was written by: - -- rzuckerm -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/ruby/index.md b/docs/projects/base64-encode-decode/ruby/index.md deleted file mode 100644 index 46e551427d..0000000000 --- a/docs/projects/base64-encode-decode/ruby/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-05-14 -layout: default -tags: -- base64-encode-decode -- ruby -title: Base64 Encode Decode in Ruby -title1: Base64 Encode -title2: Decode in Ruby ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -require "base64" - -USAGE = "Usage: please provide a mode and a string to encode/decode" - -mode, input = ARGV - -abort(USAGE) if mode.nil? || input.nil? || input.strip.empty? - -case mode -when "encode" - puts Base64.strict_encode64(input) - -when "decode" - begin - puts Base64.strict_decode64(input) - rescue - abort(USAGE) - end - -else - abort(USAGE) -end - -``` - -{% endraw %} - -Base64 Encode Decode in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/rust/index.md b/docs/projects/base64-encode-decode/rust/index.md deleted file mode 100644 index 33478d17d4..0000000000 --- a/docs/projects/base64-encode-decode/rust/index.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-03-31 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-03-31 -layout: default -tags: -- base64-encode-decode -- rust -title: Base64 Encode Decode in Rust -title1: Base64 Encode -title2: Decode in Rust ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; - -const BASE64_CHARS: [char; 64] = [ - 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', // - 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', // - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', // - 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', // - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', // -]; - -// Each tuple contains string index and number of shifts -const BASE64_ENCODE_TABLE: [(usize, u32); 4] = - [(0usize, 18), (0usize, 12), (1usize, 6), (2usize, 0)]; -const BASE64_DECODE_TABLE: [(usize, u32); 3] = [(0usize, 16), (2usize, 8), (3usize, 0)]; - -fn usage() -> ! { - println!("Usage: please provide a mode and a string to encode/decode"); - exit(0); -} - -fn base64_encode(s: &str) -> String { - // Break up string into 3-byte chunks, Base64 encode each chunk, and concatenate - s.as_bytes().chunks(3).map(base64_encode_chunk).collect() -} - -fn base64_encode_chunk(s: &[u8]) -> String { - // Base64 encode a chunk of 3 bytes, pad with "=" if shorter than 3 bytes - let s_len = s.len(); - let u = s.iter().fold(0u32, |acc, &c| (acc << 8) | (c as u32)) << (24 - 8 * s_len); - BASE64_ENCODE_TABLE - .iter() - .map(|(n, shifts)| match n < &s_len { - true => BASE64_CHARS[((u >> shifts) & 0x3f) as usize], - false => '=', - }) - .collect() -} - -fn base64_decode(s: &str) -> Option { - // Return None if length is not a multiple of 4 or pad length is more than 2 - let s_len = s.len(); - let pad_len = s_len - s.trim_end_matches('=').len(); - if s_len % 4 != 0 || pad_len > 2 { - return None; - } - - // Break string (excluding pad characters) into chunks of 4 bytes, Base64 - // decode each chunk, and concatenate. Return None if any in invalid - // Base64 characters - let mut result = String::from(""); - for chunk in s[..(s_len - pad_len)].as_bytes().chunks(4) { - result += base64_decode_chunk(chunk)?.as_str(); - } - - Some(result) -} - -fn base64_decode_chunk(s: &[u8]) -> Option { - // Convert chunk into Base64 indices. Return None if any invalid Base64 - // characters - let indices = s.iter().map(base64_index).collect::>(); - if indices.iter().any(|&n| n.is_none()) { - return None; - } - - // Base64 decode chunk - let s_len = s.len(); - let u = indices - .iter() - .fold(0u32, |acc, x| (acc << 6) | (x.unwrap() as u32)) - << (24 - 6 * s_len); - Some( - BASE64_DECODE_TABLE - .iter() - .filter(|(n, _)| n < &s_len) - .map(|(n, shifts)| (((u >> shifts) & 0xff) as u8) as char) - .collect(), - ) -} - -fn base64_index(c: &u8) -> Option { - // Convert byte to Base64 index. None is returned when there is an invalid byte - match c { - b'A'..=b'Z' => Some(c - b'A'), - b'a'..=b'z' => Some(c - b'a' + 26), - b'0'..=b'9' => Some(c - b'0' + 52), - b'+' => Some(62), - b'/' => Some(63), - _ => None, - } -} - -fn main() { - let mut args = args().skip(1); - - // Get mode and string to encode/decode - let mode = args.next().unwrap_or_else(|| usage()); - let s = args - .next() - .and_then(|s| if s.len() > 0 { Some(s) } else { None }) - .unwrap_or_else(|| usage()); - - // Encode or decode string - let result = match mode.as_str() { - "encode" => base64_encode(&s), - "decode" => base64_decode(&s).unwrap_or_else(|| usage()), - _ => usage(), - }; - println!("{result}"); -} - -``` - -{% endraw %} - -Base64 Encode Decode in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/swift/index.md b/docs/projects/base64-encode-decode/swift/index.md deleted file mode 100644 index 9028ac5844..0000000000 --- a/docs/projects/base64-encode-decode/swift/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-04-24 -layout: default -tags: -- base64-encode-decode -- swift -title: Base64 Encode Decode in Swift -title1: Base64 Encode -title2: Decode in Swift ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -private enum Base64Processor { - private static let alphabet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=") - - static func isValid(_ string: String) -> Bool { - guard string.count % 4 == 0 else { return false } - - guard string.unicodeScalars.allSatisfy(alphabet.contains) else { return false } - - let paddingCount = string.reversed().prefix(while: { $0 == "=" }).count - guard paddingCount <= 2 else { return false } - - let withoutPadding = string.dropLast(paddingCount) - return !withoutPadding.contains("=") - } -} - -func usage() -> Never { - print("Usage: please provide a mode and a string to encode/decode") - exit(1) -} - -let args = CommandLine.arguments - -guard args.count == 3 else { usage() } - -let mode = args[1] -let input = args[2] - -guard !input.isEmpty else { usage() } - -switch mode { -case "encode": - guard let data = input.data(using: .ascii) else { usage() } - print(data.base64EncodedString()) - -case "decode": - guard Base64Processor.isValid(input), - let data = Data(base64Encoded: input), - let decoded = String(data: data, encoding: .ascii) else { - usage() - } - print(decoded) - -default: - usage() -} -``` - -{% endraw %} - -Base64 Encode Decode in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/tcl/index.md b/docs/projects/base64-encode-decode/tcl/index.md deleted file mode 100644 index 60e690ba99..0000000000 --- a/docs/projects/base64-encode-decode/tcl/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-10-08 -layout: default -tags: -- base64-encode-decode -- tcl -title: Base64 Encode Decode in Tcl -title1: Base64 Encode -title2: Decode in Tcl ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -#!/usr/bin/env tclsh - -proc usage {} { - puts stderr "Usage: please provide a mode and a string to encode/decode" - exit 1 -} - -if {$argc != 2} { - usage -} - -set mode [lindex $argv 0] -set text [lindex $argv 1] - -if {$text eq ""} { - usage -} - - -switch -- $mode { - encode { - set result [binary encode base64 $text] - } - decode { - if {[catch {binary decode base64 $text} result]} { - usage - } - # Tcl’s decoder sometimes tolerates invalid padding, so validate manually - # Check that input length is a multiple of 4 and only contains valid chars - if {![regexp {^[A-Za-z0-9+/]*={0,2}$} $text]} { - usage - } - if {[expr {[string length $text] % 4 != 0}]} { - usage - } - } - default { - usage - } -} - -puts $result - - -``` - -{% endraw %} - -Base64 Encode Decode in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/typescript/index.md b/docs/projects/base64-encode-decode/typescript/index.md deleted file mode 100644 index cd086cbee2..0000000000 --- a/docs/projects/base64-encode-decode/typescript/index.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -authors: -- Arihant Jain -date: 2025-10-14 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-10-14 -layout: default -tags: -- base64-encode-decode -- typescript -title: Base64 Encode Decode in TypeScript -title1: Base64 Encode Decode -title2: in TypeScript ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function usageAndExit(): never { - console.log("Usage: please provide a mode and a string to encode/decode"); - process.exit(1); -} - -/** - * Validates if a string is valid base64 format - * @param str the string to validate - * @returns true if valid base64, false otherwise - */ -function isValidBase64(str: string): boolean { - // Check length is multiple of 4 - if (str.length % 4 !== 0) { - return false; - } - - // Only A-Z, a-z, 0-9, +, /, = allowed - if (!/^[A-Za-z0-9+/]*={0,2}$/.test(str)) { - return false; - } - - // = only allowed at end, at most two - const idx = str.indexOf("="); - if (idx !== -1 && idx < str.length - 2) { - // e.g. "ab==cd" is invalid - return false; - } - - return true; -} - -/** - * Encodes a string to base64 - * @param input the string to encode - * @returns base64 encoded string - */ -function encodeBase64(input: string): string { - // Use Buffer in Node.js - return Buffer.from(input, "ascii").toString("base64"); -} - -/** - * Decodes a base64 string - * @param input the base64 string to decode - * @returns decoded string - */ -function decodeBase64(input: string): string { - // Validate first - if (!isValidBase64(input)) { - usageAndExit(); - } - // Buffer will decode the base64 string - return Buffer.from(input, "base64").toString("ascii"); -} - -/** - * Main function to process command line arguments - */ -function main(): void { - const args = process.argv.slice(2); - - if (args.length < 2) { - usageAndExit(); - } - - const mode = args[0]; - const text = args[1]; - - if (!text) { - usageAndExit(); - } - - if (mode === "encode") { - console.log(encodeBase64(text)); - } else if (mode === "decode") { - console.log(decodeBase64(text)); - } else { - usageAndExit(); - } -} - -// Execute main function -main(); - -``` - -{% endraw %} - -Base64 Encode Decode in [TypeScript](/languages/typescript) was written by: - -- Arihant Jain - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/visual-basic/index.md b/docs/projects/base64-encode-decode/visual-basic/index.md deleted file mode 100644 index 5908d87ceb..0000000000 --- a/docs/projects/base64-encode-decode/visual-basic/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2026-05-07 -layout: default -tags: -- base64-encode-decode -- visual-basic -title: Base64 Encode Decode in Visual Basic -title1: Base64 Encode Decode -title2: in Visual Basic ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System.Text - -Module Program - - Sub Main(args As String()) - - If args.Length <> 2 Then - ShowUsage() - Return - End If - - Dim mode = args(0).ToLowerInvariant() - Dim value = args(1) - - If String.IsNullOrWhiteSpace(mode) OrElse String.IsNullOrWhiteSpace(value) Then - ShowUsage() - Return - End If - - Select Case mode - - Case "encode" - Console.WriteLine( - Convert.ToBase64String( - Encoding.UTF8.GetBytes(value) - ) - ) - - Case "decode" - Try - Console.WriteLine( - Encoding.UTF8.GetString( - Convert.FromBase64String(value) - ) - ) - - Catch ex As FormatException - ShowUsage() - End Try - - Case Else - ShowUsage() - - End Select - - End Sub - - Private Sub ShowUsage() - Console.WriteLine("Usage: please provide a mode and a string to encode/decode") - End Sub - -End Module -``` - -{% endraw %} - -Base64 Encode Decode in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/base64-encode-decode/zig/index.md b/docs/projects/base64-encode-decode/zig/index.md deleted file mode 100644 index 48f4ad9cba..0000000000 --- a/docs/projects/base64-encode-decode/zig/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Zia -date: 2025-03-29 -featured-image: base64-encode-decode-in-every-language.png -last-modified: 2025-03-29 -layout: default -tags: -- base64-encode-decode -- zig -title: Base64 Encode Decode in Zig -title1: Base64 Encode -title2: Decode in Zig ---- - - - -Welcome to the [Base64 Encode Decode](/projects/base64-encode-decode) in [Zig](/languages/zig) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```zig -const std = @import("std"); -const decoder = std.base64.standard.Decoder; -const encoder = std.base64.standard.Encoder; -const process = std.process; - -const stdout = std.io.getStdOut().writer(); - -fn die() !void { - try stdout.writeAll("Usage: please provide a mode and a string to encode/decode\n"); - process.exit(1); -} - -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); - - var args = process.args(); - - _ = args.next(); - const mode_opt = args.next(); - const src_opt = args.next(); - - if (mode_opt == null or src_opt == null) { - try die(); - } - - const mode = mode_opt.?; - const src = src_opt.?; - - if (src.len == 0) { - try die(); - } - - if (std.mem.eql(u8, mode, "encode")) { - const buffer = try allocator.alloc(u8, encoder.calcSize(src.len)); - defer allocator.free(buffer); - - _ = encoder.encode(buffer, src); - try stdout.writeAll(buffer); - _ = try stdout.write("\n"); - } else if (std.mem.eql(u8, mode, "decode")) { - errdefer { - die() catch unreachable; - } - const buflen = try decoder.calcSizeForSlice(src); - - const buffer = try allocator.alloc(u8, buflen); - defer allocator.free(buffer); - - decoder.decode(buffer, src) catch { - try die(); - }; - - try stdout.writeAll(buffer); - _ = try stdout.write("\n"); - } else { - try die(); - } -} - -``` - -{% endraw %} - -Base64 Encode Decode in [Zig](/languages/zig) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/ada/index.md b/docs/projects/binary-search/ada/index.md deleted file mode 100644 index fd9cbee802..0000000000 --- a/docs/projects/binary-search/ada/index.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-09 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-09 -layout: default -tags: -- ada -- binary-search -title: Binary Search in Ada -title1: Binary Search -title2: in Ada ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Containers.Vectors; - -procedure Binary_Search is - - Parse_Error : exception; - - package Int_Vec is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - use Int_Vec; - - function Contains (V : Vector; Value : Integer) return Boolean is - Len : constant Natural := Natural (Length (V)); - Low : Natural := First_Index (V); - High : Natural := Last_Index (V); - begin - if Len = 0 then - return False; - end if; - - while Low <= High loop - declare - Mid : constant Natural := Low + (High - Low) / 2; - Mid_Val : constant Integer := Element (V, Mid); - begin - if Value < Mid_Val then - if Mid = 0 then - exit; - end if; - High := Mid - 1; - - elsif Mid_Val < Value then - Low := Mid + 1; - - else - return True; - end if; - end; - end loop; - - return False; - end Contains; - - function Parse_Int (S : String) return Integer is - Clean : constant String := Trim (S, Ada.Strings.Both); - begin - if Clean'Length = 0 then - raise Parse_Error; - end if; - - return Integer'Value (Clean); - exception - when others => - raise Parse_Error; - end Parse_Int; - - function Parse_Sorted_List (S : String) return Vector is - V : Vector; - Start : Positive := S'First; - First_Item : Boolean := True; - Prev : Integer := 0; - begin - if S'Length = 0 then - raise Parse_Error; - end if; - - for I in S'Range loop - if S (I) = ',' then - declare - Value : constant Integer := Parse_Int (S (Start .. I - 1)); - begin - if not First_Item and then Value < Prev then - raise Parse_Error; -- not sorted - - end if; - - Append (V, Value); - Prev := Value; - First_Item := False; - Start := I + 1; - end; - end if; - end loop; - - declare - Value : constant Integer := Parse_Int (S (Start .. S'Last)); - begin - if not First_Item and then Value < Prev then - raise Parse_Error; - end if; - - Append (V, Value); - end; - - return V; - end Parse_Sorted_List; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide a list of sorted integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")"); - end Print_Usage; - -begin - if Argument_Count /= 2 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - declare - Haystack : Vector; - Needle : Integer; - begin - Haystack := Parse_Sorted_List (Argument (1)); - Needle := Parse_Int (Argument (2)); - - Put_Line (if Contains (Haystack, Needle) then "true" else "false"); - - exception - when Parse_Error | Constraint_Error => - Print_Usage; - Set_Exit_Status (Failure); - end; - -end Binary_Search; - -``` - -{% endraw %} - -Binary Search in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/algol60/index.md b/docs/projects/binary-search/algol60/index.md deleted file mode 100644 index eb2c408e91..0000000000 --- a/docs/projects/binary-search/algol60/index.md +++ /dev/null @@ -1,262 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-17 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-04-17 -layout: default -tags: -- algol60 -- binary-search -title: Binary Search in ALGOL 60 -title1: Binary Search -title2: in ALGOL 60 ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of sorted integers " - "(\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - boolean procedure isSorted(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - boolean valid; - integer i; - - valid := true; - i := 2; - comploop: - if valid & i <= arrLen then - begin - valid := arr[i - 1] < arr[i]; - i := i + 1; - goto comploop - end; - - isSorted := valid - end isSorted; - - integer procedure binarySearch(arr, arrLen, target); - value arrLen, target; - integer array arr; - integer arrLen, target; - begin - integer idx, low, mid, high; - boolean found; - - idx := -1; - low := 1; - high := arrLen + 1; - searchloop: - if low < high then - begin - mid := (low + high) % 2; - if arr[mid] = target then - begin - idx := mid; - goto done - end - else if arr[mid] < target then low := mid + 1 - else high := mid; - goto searchloop - end; - - done: - binarySearch := idx - end binarySearch; - - integer argc, arrLen, ch, target, idx; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 2 then usage; - - comment Get list input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 1 then usage; - - comment Get target value from 2nd argument. Exit if invalid; - if !inValidInteger(target, ch, false) then usage; - - comment If list is not sorted, exit; - if !isSorted(arr, arrLen) then usage; - - comment Binary search for target value in list. Indicate if found; - idx := binarySearch(arr, arrLen, target); - if idx > 0 then outstring(1, "true\n") - else outstring(1, "false\n") -end - -``` - -{% endraw %} - -Binary Search in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/algol68/index.md b/docs/projects/binary-search/algol68/index.md deleted file mode 100644 index b8817769cd..0000000000 --- a/docs/projects/binary-search/algol68/index.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-27 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-01-30 -layout: default -tags: -- algol68 -- binary-search -title: Binary Search in ALGOL 68 -title1: Binary Search -title2: in ALGOL 68 ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a list of sorted integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")")) -); - -PROC check sorted = (REF []INT values) BOOL: -( - BOOL sorted := TRUE; - - FOR k TO UPB values - 1 - WHILE - sorted := (values[k] <= values[k + 1]) - DO - SKIP - OD; - - sorted -); - -PROC binary search = (INT target, REF []INT values) INT: -( - INT found := 0; - INT low := 1; - INT high := UPB values + 1; - INT mid; - WHILE low < high AND found = 0 - DO - mid := (low + high) OVER 2; - - # If found it, return index # - IF values[mid] = target - THEN - found := mid - # If too low, move lower bound # - ELIF values[mid] < target - THEN - low := mid + 1 - # Else too high, move upper bound # - ELSE - high := mid - FI - OD; - - found -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result -THEN - usage; - stop -FI; - -# Parse 2nd command-line argument # -s := argv(5); -PARSEINT_RESULT result := parse int(s); -INT target := value OF result; -IF NOT valid OF result OR leftover OF result /= "" -THEN - usage; - stop -FI; - -# Make sure list is sorted # -IF NOT check sorted(values) -THEN - usage; - stop -FI; - -# Do binary search and show results # -INT index = binary search(target, values); -printf(($gl$, (index > 0 | "true" | "false"))) - -``` - -{% endraw %} - -Binary Search in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/awk/index.md b/docs/projects/binary-search/awk/index.md deleted file mode 100644 index ea0f075e72..0000000000 --- a/docs/projects/binary-search/awk/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-14 -featured-image: binary-search-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- binary-search -title: Binary Search in AWK -title1: Binary Search -title2: in AWK ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -function is_sorted(arr, arr_len, sorted, i) { - sorted = 1 - for (i = 1; sorted && i < arr_len; i++) { - sorted = (arr[i] <= arr[i + 1]) - } - - return sorted -} - -function binary_search(arr, arr_len, target, found, low, mid, high, value) { - found = 0 - low = 1 - high = arr_len + 1 - while (low < high && !found) { - mid = rshift(low + high, 1) - value = arr[mid] - if (value == target) { - found = mid - } else if (value < target) { - low = mid + 1 - } else { - high = mid - } - } - - return found -} - -BEGIN { - if (ARGC < 3) { - usage() - } - - str_to_array(ARGV[1], arr) - target = str_to_number(ARGV[2]) - arr_len = length(arr) - if (!arr_len || arr[1] == "ERROR" || target == "ERROR") { - usage() - } - - if (!is_sorted(arr, arr_len)) { - usage() - } - - idx = binary_search(arr, arr_len, target) - print (idx > 0) ? "true" : "false" -} - -``` - -{% endraw %} - -Binary Search in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/beef/index.md b/docs/projects/binary-search/beef/index.md deleted file mode 100644 index 1d482f7c6a..0000000000 --- a/docs/projects/binary-search/beef/index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-02 -featured-image: binary-search-in-every-language.jpg -last-modified: 2024-02-02 -layout: default -tags: -- beef -- binary-search -title: Binary Search in Beef -title1: Binary Search -title2: in Beef ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace BinarySearch; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11") - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - public static int BinarySearch(List arr, T target) - where int : operator T <=> T - { - return arr.BinarySearch(target); - } - - public static bool IsSorted(List arr) - where int : operator T <=> T - { - for (int i = 1; i < arr.Count; i++) - { - if (arr[i - 1] > arr[i]) - { - return false; - } - } - - return true; - } - - public static int Main(String[] args) - { - if (args.Count < 2) - { - Usage(); - } - - List arr = scope .(); - if (ParseIntList(args[0], arr) case .Err) - { - Usage(); - } - - int32 target = ?; - switch (ParseInt(args[1])) - { - case .Ok(out target): - case .Err: - Usage(); - } - - if (!IsSorted(arr)) - { - Usage(); - } - - int index = BinarySearch(arr, target); - Console.WriteLine(index >= 0 ? "true" : "false"); - - return 0; - } -} - -``` - -{% endraw %} - -Binary Search in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/c-plus-plus/index.md b/docs/projects/binary-search/c-plus-plus/index.md deleted file mode 100644 index c71ca59009..0000000000 --- a/docs/projects/binary-search/c-plus-plus/index.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Sailok Chinta -- Ștefan-Iulian Alecu -date: 2019-10-27 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- binary-search -- c-plus-plus -title: Binary Search in C++ -title1: Binary Search -title2: in C++ ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11"))" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - s = trim(s); - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -int main(int argc, char* argv[]) { - if (argc != 3) usage(); - - const auto target = to_int(argv[2]); - if (!target) usage(); - - const std::string_view input{argv[1]}; - auto ints_view = input | views::split(',') | - views::transform([](auto&& rng) { - return std::string_view(rng.begin(), rng.end()); - }) | - views::transform(to_int) | - views::filter([](auto&& opt) { return opt.has_value(); }) | - views::transform([](auto&& opt) { return *opt; }); - - std::vector haystack; - ranges::copy(ints_view, std::back_inserter(haystack)); - - if (haystack.empty() || !ranges::is_sorted(haystack)) usage(); - - const bool found = ranges::binary_search(haystack, *target); - std::cout << std::format("{}\n", found); - - return 0; -} -``` - -{% endraw %} - -Binary Search in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Sailok Chinta -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/c-sharp/index.md b/docs/projects/binary-search/c-sharp/index.md deleted file mode 100644 index 6d7221fa19..0000000000 --- a/docs/projects/binary-search/c-sharp/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2024-10-29 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- binary-search -- c-sharp -title: Binary Search in C# -title1: Binary -title2: Search in C# ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Collections.Generic; - -if (args is not [var input, var targetRaw] - || !int.TryParse(targetRaw, out int target) - || !TryParseSorted(input.AsSpan(), out var numbers)) -{ - return Usage(); -} - -Console.WriteLine(numbers.BinarySearch(target) >= 0); -return 0; - -static bool TryParseSorted(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - int last = int.MinValue; - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n) || n < last) - return false; - - numbers.Add(n); - last = n; - } - - return numbers.Count > 0; -} - -static int Usage() -{ - Console.Error.WriteLine( - """Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")""" - ); - - return 1; -} -``` - -{% endraw %} - -Binary Search in [C#](/languages/c-sharp) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/c/index.md b/docs/projects/binary-search/c/index.md deleted file mode 100644 index ff5032ee37..0000000000 --- a/docs/projects/binary-search/c/index.md +++ /dev/null @@ -1,227 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2024-10-28 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- binary-search -- c -title: Binary Search in C -title1: Binary -title2: Search in C ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include - -// Function prototypes -int binarySearch(const int arr[], int size, int target); -int isSorted(const int arr[], int size); -int isValidNumber(const char *str); -char *trimWhitespace(char *str); -int parseInput(const char *input, int **arr, int *size); -void freeMemory(int *arr); -void printErrorAndExit(const char *message, int *arr); - -int main(int argc, char *argv[]) -{ - if (argc != 3) - { - printErrorAndExit( - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, " - "12\") and the integer to find (\"11\")\n", - NULL); - } - - int *arr = NULL; - int size = 0; - - // Parse the input array from the first argument - if (parseInput(argv[1], &arr, &size) != 0 - || size < 1 - || !isSorted(arr, size)) - { - printErrorAndExit( - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, " - "12\") and the integer to find (\"11\")\n", - arr); - } - - // Get target value from the second argument - if (!isValidNumber(argv[2])) - { - printErrorAndExit( - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, " - "12\") and the integer to find (\"11\")\n", - arr); - } - - int target = atoi(argv[2]); - - // Perform binary search - int result = binarySearch(arr, size, target); - printf(result != -1 ? "true\n" : "false\n"); - - // Free allocated memory - freeMemory(arr); - return 0; -} - -// Function to perform binary search -int binarySearch(const int arr[], int size, int target) -{ - int left = 0; - int right = size - 1; - - while (left <= right) - { - int mid = left + (right - left) / 2; - - if (arr[mid] == target) - return mid; // Target found - - if (arr[mid] < target) - left = mid + 1; // Move right - else - right = mid - 1; // Move left - } - - return -1; // Target not found -} - -// Function to parse input string and populate the array -int parseInput(const char *input, int **arr, int *size) -{ - char *token; - int capacity = 10; // Initial capacity - *arr = malloc(capacity * sizeof(int)); - if (*arr == NULL) - { - printf("Memory allocation failed. Exiting.\n"); - return 1; - } - - // Tokenize the input string based on commas - char *inputCopy = strdup(input); - token = strtok(inputCopy, ","); - *size = 0; - while (token) - { - trimWhitespace(token); // Trim whitespace around token - if (!isValidNumber(token)) - { - printf("Invalid number detected: '%s'. Exiting.\n", token); - freeMemory(*arr); - free(inputCopy); - return 1; // Exit if a number is invalid - } - - if (*size >= capacity) - { - capacity *= 2; - *arr = realloc(*arr, capacity * sizeof(int)); - if (*arr == NULL) - { - printf("Memory reallocation failed. Exiting.\n"); - free(inputCopy); - return 1; - } - } - (*arr)[(*size)++] = atoi(token); - token = strtok(NULL, ","); - } - - // Resize the array to the actual size - *arr = realloc(*arr, *size * sizeof(int)); - free(inputCopy); // Free the input copy - return 0; // Successful parsing -} - -// Function to free allocated memory -void freeMemory(int *arr) -{ - free(arr); -} - -// Function to print error message and exit -void printErrorAndExit(const char *message, int *arr) -{ - if (arr != NULL) - freeMemory(arr); - printf("%s", message); - exit(1); -} - -// Function to check if the array is sorted -int isSorted(const int arr[], int size) -{ - for (int i = 1; i < size; i++) - if (arr[i] < arr[i - 1]) - return 0; // Array is not sorted - return 1; // Array is sorted -} - -// Function to check if a string is a valid number -int isValidNumber(const char *str) -{ - char *end; - strtol(str, &end, 10); // Convert string to long - return (*end == '\0' - || *end == '\n'); // Check if the entire string was valid -} - -// Function to trim whitespace from a string -char *trimWhitespace(char *str) -{ - // Trim leading whitespace - while (isspace((unsigned char)*str)) - str++; - // Trim trailing whitespace - char *end = str + strlen(str) - 1; - while (end > str && isspace((unsigned char)*end)) - end--; - *(end + 1) = '\0'; // Null terminate after the last non-space character - return str; -} - -``` - -{% endraw %} - -Binary Search in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/cobol/index.md b/docs/projects/binary-search/cobol/index.md deleted file mode 100644 index 2cecec9542..0000000000 --- a/docs/projects/binary-search/cobol/index.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-19 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-04-19 -layout: default -tags: -- binary-search -- cobol -title: Binary Search in COBOL -title1: Binary Search -title2: in COBOL ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. binary-search. - -data division. -working-storage section. - -01 MAX-ENTRIES constant as 100. -01 argc binary-long. -01 list-string pic x(1100). -01 target-string pic x(20). -01 ws-token pic x(20). -01 ws-ptr binary-long. -01 num-count binary-long value 0. -01 num-list. - 05 num pic s9(9) - occurs 1 to MAX-ENTRIES - depending on num-count - ascending key is num - indexed by num-idx. -01 target-number pic s9(9). -01 prev-num pic s9(9) value -999999999. -01 search-state pic x value 'F'. - 88 item-found value 'T'. - 88 item-not-found value 'F'. - -procedure division. - -main. - perform validate-args - perform parse-and-validate-input - perform binary-search - - if item-found - display "true" - else - display "false" - end-if - goback. - -validate-args. - accept argc from argument-number - - if argc <> 2 - perform display-usage - end-if - - accept list-string from argument-value - accept target-string from argument-value - - if list-string = spaces or target-string = spaces - perform display-usage - end-if - - if function test-numval(target-string) <> 0 - perform display-usage - end-if - - move function numval(target-string) to target-number. - -parse-and-validate-input. - move 1 to ws-ptr - perform until ws-ptr > length of list-string - or list-string(ws-ptr:) = spaces - - move spaces to ws-token - unstring list-string - delimited by all "," - into ws-token - with pointer ws-ptr - end-unstring - - if ws-token <> spaces - if function test-numval(ws-token) <> 0 - perform display-usage - end-if - - add 1 to num-count - if num-count > MAX-ENTRIES - perform display-usage - end-if - - move function numval(ws-token) to num(num-count) - - if num(num-count) < prev-num - perform display-usage - end-if - move num(num-count) to prev-num - end-if - end-perform - - if num-count = 0 - perform display-usage - end-if. - -binary-search. - set item-not-found to true - search all num - when num(num-idx) = target-number - set item-found to true - end-search. - -display-usage. - display 'Usage: please provide a list of sorted integers ' - '("1, 4, 5, 11, 12") and the integer to find ("11")' - stop run. - -``` - -{% endraw %} - -Binary Search in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/commodore-basic/index.md b/docs/projects/binary-search/commodore-basic/index.md deleted file mode 100644 index d7048496c0..0000000000 --- a/docs/projects/binary-search/commodore-basic/index.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-07 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-10-15 -layout: default -tags: -- binary-search -- commodore-basic -title: Binary Search in Commodore BASIC -title1: Binary Search in -title2: Commodore BASIC ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -20 GOSUB 2000: REM Get array -30 IF V = 0 OR C <> -1 THEN GOTO 200: REM invalid or end of input/value -40 GOSUB 1000: REM Get target value -50 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -60 GOSUB 2500: REM Check if sorted -70 IF V = 0 THEN GOTO 200: REM not sorted -75 REM Perform binary search -80 T = NR -90 GOSUB 3000 -100 R$ = "false" -110 IF I >= 0 THEN R$ = "true" -120 PRINT R$ -130 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide a list of sorted integers "; -220 PRINT "("; Q$; "1, 4, 5, 11, 12"; Q$; ") and the integer to find "; -230 PRINT "("; Q$; "11"; Q$; ")" -240 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -2500 REM Check if sorted -2502 REM - A contains array to search -2503 REM - NA contains size of array -2504 REM Outputs: V = 1 if sorted, 0 otherwise -2510 I = -1 -2520 V = 1 -2530 I = I + 1 -2540 IF I >= (NA - 1) THEN RETURN -2550 IF A(I) > A(I + 1) THEN V = 0: RETURN: REM Not sorted -2560 GOTO 2530 -3000 REM Binary search -3001 REM Inputs: -3002 REM - A contains array to search -3003 REM - NA contains size of array -3004 REM - T contains item to find -3005 REM Outputs: I contains index of array item found, -1 if not found -3010 I = -1 -3020 LO = 0 -3030 HI = NA - 1 -3040 IF LO > HI THEN I = -1: RETURN: REM Not found -3050 MD = INT((LO + HI) / 2) -3060 IF A(MD) = T THEN I = MD: RETURN: REM Found -3070 IF A(MD) < T THEN LO = MD + 1: REM Too low, move lower bound -3080 IF A(MD) > T THEN HI = MD - 1: REM Too high, move upper bound -3090 GOTO 3040 - -``` - -{% endraw %} - -Binary Search in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/euphoria/index.md b/docs/projects/binary-search/euphoria/index.md deleted file mode 100644 index 9befa331cc..0000000000 --- a/docs/projects/binary-search/euphoria/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- binary-search -- euphoria -title: Binary Search in Euphoria -title1: Binary Search -title2: in Euphoria ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/search.e -include std/utils.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n" - ) - abort(0) -end procedure - -function check_sorted(sequence values) - for k = 1 to length(values) - 1 - do - if values[k] > values[k + 1] - then - return FALSE - end if - end for - - return TRUE -end function - --- Check command-line arguments -sequence argv = command_line() -if length(argv) < 5 or length(argv[4]) = 0 or length(argv[5]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence list_result = parse_int_list(argv[4]) -sequence values = list_result[PARSE_INT_LIST_VALUES] -if not list_result[PARSE_INT_LIST_VALID] -then - usage() -end if - --- Parse 2nd command-line argument -sequence result = parse_int(argv[5]) -integer target = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] -then - usage() -end if - --- Make sure list is sorted -if not check_sorted(values) -then - usage() -end if - --- Use built-in binary search and show results -integer index = binary_search(target, values) -puts(STDOUT, iif(index > 0, "true\n", "false\n")) - -``` - -{% endraw %} - -Binary Search in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/f-sharp/index.md b/docs/projects/binary-search/f-sharp/index.md deleted file mode 100644 index 7f95f3d599..0000000000 --- a/docs/projects/binary-search/f-sharp/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-06 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-04-06 -layout: default -tags: -- binary-search -- f-sharp -title: Binary Search in F# -title1: Binary -title2: Search in F# ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module BinarySearch = - let private search (haystack: int array) (needle: int) = - let len = haystack.Length - - if needle < haystack.[0] || needle > haystack.[len - 1] then - false - else - let rec loop lo hi = - if lo > hi then - false - else - let mid = lo + (hi - lo) / 2 - - match compare needle haystack.[mid] with - | 0 -> true - | c when c < 0 -> loop lo (mid - 1) - | _ -> loop (mid + 1) hi - - loop 0 (len - 1) - - let find haystack needle = search haystack needle - -module Helpers = - - let private isSorted itemList = - itemList |> Seq.pairwise |> Seq.forall (fun (a, b) -> a <= b) - - let private (|Int|_|) (s: string) = - match Int32.TryParse(s.Trim()) with - | true, n -> Some n - | _ -> None - - let private (|SortedIntList|_|) (s: string) = - if String.IsNullOrWhiteSpace(s) then - None - else - let parts = s.Split([| ',' |], StringSplitOptions.RemoveEmptyEntries) - - let parsed = - parts - |> Array.choose ( - function - | Int n -> Some n - | _ -> None - ) - - if not (Array.isEmpty parsed) && parsed.Length = parts.Length && isSorted parsed then - Some parsed - else - None - - let parseArgs argv = - match argv with - | [| SortedIntList numbers; Int target |] -> Ok(numbers, target) - | _ -> - Error - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")" - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - let okBool (b: bool) = if b then Ok "true" else Ok "false" - - argv - |> Helpers.parseArgs - |> Result.bind (fun (numbers, target) -> BinarySearch.find numbers target |> okBool) - |> Helpers.handleResult - -``` - -{% endraw %} - -Binary Search in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/fortran/index.md b/docs/projects/binary-search/fortran/index.md deleted file mode 100644 index bb882b1ab7..0000000000 --- a/docs/projects/binary-search/fortran/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- leoraggy -date: 2025-11-05 -featured-image: binary-search-in-every-language.jpg -last-modified: 2025-11-05 -layout: default -tags: -- binary-search -- fortran -title: Binary Search in Fortran -title1: Binary Search -title2: in Fortran ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program binarysearch - implicit none - character(len=256) :: input1 - character(len=10) :: input2 - integer :: key, left, right, middle, io_status, i, length, pos - integer, allocatable :: numbers(:) - logical :: searched - - if(command_argument_count() < 2) call usage() - - call get_command_argument(1, input1) - call get_command_argument(2,input2) - - if(input1 == "") call usage() - - call convert_to_array(input1, numbers) - - read(input2, fmt=*, iostat=io_status) key - - do i = 1, size(numbers) - 1 - if(numbers(i) > numbers(i+1)) then - call usage() - end if - end do - - left = 1 - right = size(numbers) - searched = binary_search(numbers,key, left, right) - if (searched) then - print '(a)', 'true' - else - print '(a)', 'false' - end if - -contains - subroutine usage() - write(*,'(a)') "Usage: please provide a list of sorted integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")" - stop - end subroutine usage - - subroutine convert_to_array(input1, numbers) - implicit none - character(len=*), intent(in) :: input1 - integer, allocatable, intent(out) :: numbers(:) - integer :: i, length, pos, io_status - - length = 1 - do i = 1, len_trim(input1) - if (input1(i:i) == ',') length = length + 1 - end do - - allocate(numbers(length)) - - pos = 1 - do i = 1, length - read(input1(pos:), *, iostat=io_status) numbers(i) - pos = index(input1(pos:), ',') + pos - end do - end subroutine convert_to_array - - function binary_search(numbers, key, left, right) result(answer) - implicit none - logical :: answer - integer, intent(in) :: key - integer, intent(in) :: numbers(:) - integer :: left - integer :: right - integer :: middle - answer = .false. - do while (left <= right) - middle = (left + right) / 2 - if(numbers(middle) == key) then - answer = .true. - return - else if(numbers(middle) > key) then - right = middle - 1 - else - left = middle + 1 - end if - end do - end function binary_search -end program binarysearch -``` - -{% endraw %} - -Binary Search in [Fortran](/languages/fortran) was written by: - -- leoraggy - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/go/index.md b/docs/projects/binary-search/go/index.md deleted file mode 100644 index 64c6cfb62d..0000000000 --- a/docs/projects/binary-search/go/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-10-24 -featured-image: binary-search-in-every-language.jpg -last-modified: 2019-10-24 -layout: default -tags: -- binary-search -- go -title: Binary Search in Go -title1: Binary -title2: Search in Go ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "encoding/json" - "fmt" - "os" - "regexp" - "strconv" - "strings" -) - -func binarySearch(list []int, target int) bool { - midIndex := len(list) / 2 - midpoint := list[midIndex] - - if midpoint == target { - return true - } - - if len(list) <= 1 { - return false - } - - if target < list[midIndex] { - return binarySearch(list[:midIndex], target) - } - - return binarySearch(list[midIndex:], target) -} - -func verifySortedList(list []int) { - lastVal := list[0] - for _, val := range list { - if val < lastVal { - exitWithError() - } - } -} - -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} - -func sliceIntToString(list []int) (out string) { - bytes, _ := json.Marshal(list) - out = strings.Replace(string(bytes), ",", ", ", -1) - out = strings.Trim(out, "[]") - return -} - -func exitWithError() { - fmt.Println("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")") - os.Exit(1) -} - -func main() { - if len(os.Args) != 3 { - exitWithError() - } - - list := strToSliceInt(os.Args[1]) - verifySortedList(list) - target, err := strconv.Atoi(os.Args[2]) - if err != nil { - exitWithError() - } - fmt.Println(binarySearch(list, target)) -} - -``` - -{% endraw %} - -Binary Search in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/haskell/index.md b/docs/projects/binary-search/haskell/index.md deleted file mode 100644 index 514fe3edfc..0000000000 --- a/docs/projects/binary-search/haskell/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-11 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- binary-search -- haskell -title: Binary Search in Haskell -title1: Binary Search -title2: in Haskell ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Data.Array (Array, (!)) -import qualified Data.Array as Array -import Control.Monad (guard) -import Text.Read - --- Converts string in format "1, 2, 3" to a Maybe array of int -stringToArrayMaybe :: String -> Maybe (Array Int Int) -stringToArrayMaybe str = do - xs <- readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - guard $ (not . null) xs - return $ Array.listArray (0, length xs - 1) xs - -isSorted :: (Ord a) => [a] -> Bool -isSorted [] = True -isSorted [_] = True -isSorted (x1:x2:xs) = x1 <= x2 && isSorted (x2:xs) - -parseArgs :: [String] -> Maybe (Array Int Int, Int) -parseArgs [a, t] = do - target <- readMaybe t - array <- stringToArrayMaybe a - guard (isSorted (Array.elems array)) - return (array, target) -parseArgs _ = Nothing - -binarySearch :: (Ord e) => e -> Array Int e -> Bool -binarySearch x xs = go lo hi - where - (lo, hi) = Array.bounds xs - go l h - | l > h = False - | xs ! m == x = True - | xs ! m < x = go (m+1) h - | otherwise = go l (m-1) - where m = (h+l) `quot` 2 - -main :: IO () -main = do - args <- getArgs - case parseArgs args of - Nothing -> - putStrLn "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")" - Just (array, target) -> - let result = binarySearch target array - in putStrLn (if result then "true" else "false") - - -``` - -{% endraw %} - -Binary Search in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/index.md b/docs/projects/binary-search/index.md deleted file mode 100644 index 060877dbba..0000000000 --- a/docs/projects/binary-search/index.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -date: 2019-10-24 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- binary-search -title: Binary Search -title1: Binary -title2: Search ---- - - - -Welcome to the Binary Search page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Binary search is a special type of search function which relies on a few properties -of the search space. First, the search space must have constant time random access -(i.e. an array). In addition, the search space must be sorted by some attribute. -As a consequence, we're able to navigate the search space in O(log(N)) instead of -O(N). - -Jargon aside, binary search works by taking advantage of a sorted collection. As a result, -we don't have to search every element in the collection. Instead, we can try the middle. -If the middle element is greater than the element we want to find, we know that the element -must be "to the left" of that element, assuming the collection is sorted least to greatest. -From there, we can try the element in the middle of the left half, and so on. - -Eventually, we'll find the element we're looking for, or we'll reach the end of our search. -In either case, we'll only explore O(log(N)) elements. This gives us a dramatic improvement -over linear search. - - -## Requirements - -For the purposes of this project, we'll assume that the search space is a list of integers. -Specifically, we'll accept two inputs on the command line: the list of integers and the -integer to find: - -```shell -$ ./binary-search.lang "1, 4, 5, 11, 12" "4" -``` - -If successful, the script should return `true`. Otherwise, the script should return `false`. -If any user input errors occur, the script should output the following usage message: -`Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")`. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Binary Search. -In order to keep things simple, we split up the testing as follows: - -- Binary Search Valid Tests -- Binary Search Invalid Tests - -### Binary Search Valid Tests - -| Description | List Input | Target Integer Input | Output | -| ----------- | ---------- | -------------------- | ------ | -| Sample Input: First True | "1, 3, 5, 7" | "1" | "true" | -| Sample Input: Last True | "1, 3, 5, 7" | "7" | "true" | -| Sample Input: Middle True | "1, 3, 5, 7" | "5" | "true" | -| Sample Input: One True | "5" | "5" | "true" | -| Sample Input: One False | "5" | "7" | "false" | -| Sample Input: Many False | "1, 3, 5, 6" | "7" | "false" | -| Sample Input: Middle True | "1, 2, 3, 4, 5, 6, 7" | "3" | "true" | - -### Binary Search Invalid Tests - -| Description | List Input | Target Integer Input | -| ----------- | ---------- | -------------------- | -| No Input | | | -| Missing Input: Target | "1, 2, 3, 4" | | -| Missing Input: List | "" | "5" | -| Out Of Order Input | "3, 5, 1, 2" | "3" | - -All of these tests should output the following: - -``` -Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11") -``` - - -## Articles - -There are 31 articles: - -- [Binary Search in ALGOL 60](/projects/binary-search/algol60) -- [Binary Search in ALGOL 68](/projects/binary-search/algol68) -- [Binary Search in AWK](/projects/binary-search/awk) -- [Binary Search in Ada](/projects/binary-search/ada) -- [Binary Search in Beef](/projects/binary-search/beef) -- [Binary Search in C](/projects/binary-search/c) -- [Binary Search in C#](/projects/binary-search/c-sharp) -- [Binary Search in C++](/projects/binary-search/c-plus-plus) -- [Binary Search in COBOL](/projects/binary-search/cobol) -- [Binary Search in Commodore BASIC](/projects/binary-search/commodore-basic) -- [Binary Search in Euphoria](/projects/binary-search/euphoria) -- [Binary Search in F#](/projects/binary-search/f-sharp) -- [Binary Search in Fortran](/projects/binary-search/fortran) -- [Binary Search in Go](/projects/binary-search/go) -- [Binary Search in Haskell](/projects/binary-search/haskell) -- [Binary Search in Java](/projects/binary-search/java) -- [Binary Search in JavaScript](/projects/binary-search/javascript) -- [Binary Search in Kotlin](/projects/binary-search/kotlin) -- [Binary Search in Mathematica](/projects/binary-search/mathematica) -- [Binary Search in PHP](/projects/binary-search/php) -- [Binary Search in Pascal](/projects/binary-search/pascal) -- [Binary Search in Perl](/projects/binary-search/perl) -- [Binary Search in PowerShell](/projects/binary-search/powershell) -- [Binary Search in Python](/projects/binary-search/python) -- [Binary Search in Ruby](/projects/binary-search/ruby) -- [Binary Search in Rust](/projects/binary-search/rust) -- [Binary Search in Swift](/projects/binary-search/swift) -- [Binary Search in Tcl](/projects/binary-search/tcl) -- [Binary Search in TypeScript](/projects/binary-search/typescript) -- [Binary Search in Visual Basic](/projects/binary-search/visual-basic) -- [Binary Search in m4](/projects/binary-search/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/binary-search/java/index.md b/docs/projects/binary-search/java/index.md deleted file mode 100644 index 86ca5cc2b6..0000000000 --- a/docs/projects/binary-search/java/index.md +++ /dev/null @@ -1,168 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Shreyas Kamath -- Vipin Yadav -date: 2022-10-02 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- binary-search -- java -title: Binary Search in Java -title1: Binary Search -title2: in Java ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -public class BinarySearch { - public static void binarySearch(ArrayList arr, int first, int last, int key) { - int mid = (first + last) / 2; - while (first <= last) { - if (arr.get(mid) < key) { - first = mid + 1; - } else if (arr.get(mid) == key) { - System.out.println("True"); - break; - } else { - last = mid - 1; - } - mid = (first + last) / 2; - } - if (first > last) { - System.out.println("False"); - } - } - - public static void main(String args[]) { - try { - ArrayList listOfNumbers = new ArrayList<>(); - String[] NumberArray = args[0].split(","); - for (String Number : NumberArray) { - listOfNumbers.add(Integer.parseInt(Number.trim())); - } - int key = Integer.parseInt(args[1].trim()); - int last = listOfNumbers.size() - 1; - for (int i = 0; i < last - 1; i++) { - if (listOfNumbers.get(i) > listOfNumbers.get(i + 1)) { - System.out.println( - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); - System.exit(1); - } - } - binarySearch(listOfNumbers, 0, last, key); - } catch (Exception e) { - System.out.println( - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); - } - } -} -``` - -{% endraw %} - -Binary Search in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Vipin Yadav - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Shreyas Kamath - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -At this point, let's dig into the code a bit. The following sections break down the Binary Search in Java functionality. - -### The Main Function - -```java -public static void main(String args[]) { - try { - ArrayList listOfNumbers = new ArrayList<>(); - String[] NumberArray = args[0].split(","); - for (String Number : NumberArray) { - listOfNumbers.add(Integer.parseInt(Number.trim())); - } - int key = Integer.parseInt(args[1].trim()); - int last = listOfNumbers.size() - 1; - for (int i = 0; i < last - 1; i++) { - if (listOfNumbers.get(i) > listOfNumbers.get(i + 1)) { - System.out.println( - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); - System.exit(1); - } - } - binarySearch(listOfNumbers, 0, last, key); - } catch (Exception e) { - System.out.println( - "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); - } -} -``` -This is the main function and is automatically executed when this Java file runs. -* The input to the main function is supplied in the form of command line arguments, e.g., String "10,20,30,40,50" and the element to be found "40". -* The function splits this input through the delimeter ',' and converts the strings to integer array. -* The function checks if the array is sorted. -* If the input array is sorted the binary search function is called. -* The "usage" statement is displayed and the program exits if the command line arguments are incorrect, the list is not sorted, or anything throws an exception. - -### Binary Search - -```java -public static void binarySearch(ArrayList arr, int first, int last, int key) { - int mid = (first + last) / 2; - while (first <= last) { - if (arr.get(mid) < key) { - first = mid + 1; - } else if (arr.get(mid) == key) { - System.out.println("True"); - break; - } else { - last = mid - 1; - } - mid = (first + last) / 2; - } - if (first > last) { - System.out.println("False"); - } -} -``` - -* First, the search space must have constant time random access (i.e., an array). In addition, the search space must be sorted by some attribute. As a consequence, we're able to navigate the search space in O(log(N)) instead of O(N). - -* If the middle element is greater than the element we want to find, we know that the element must be "to the left" of that element, assuming the collection is sorted least to greatest. From there, we can try the element in the middle of the left half, and so on - -* Eventually, we'll find the element we're looking for and display "True", or we'll reach the end of our search and display "False". - - -## How to Run the Solution - -* Save the code as a .java file eg BinarySearch.java -* Run the command ```javac BinarySearch.java``` in the directory containing this file -* Run the command with the desired input arguments eg ```java BinarySearch "10,20,30,40,50" "40"``` diff --git a/docs/projects/binary-search/javascript/index.md b/docs/projects/binary-search/javascript/index.md deleted file mode 100644 index 0e0ba21ac7..0000000000 --- a/docs/projects/binary-search/javascript/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- izexi -date: 2020-10-23 -featured-image: binary-search-in-every-language.jpg -last-modified: 2020-10-23 -layout: default -tags: -- binary-search -- javascript -title: Binary Search in JavaScript -title1: Binary Search -title2: in JavaScript ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const [, , array, target] = process.argv; -const error = 'Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")'; - -const binarySearch = (array, target, start = 0, end = array.length - 1) => { - - const isOrdered = array.every((num, i, arr) => !i || num >= arr[i - 1]); - if (!isOrdered) return error; - - const middleIndex = Math.floor((start + end) / 2); - const middleValue = array[middleIndex]; - const newIndexes = - target < middleValue ? [start, middleIndex - 1] : [middleIndex + 1, end]; - - return middleValue === target - ? true - : start >= end - ? false - : binarySearch(array, target, ...newIndexes); -}; - -console.log(array && target ? binarySearch(array.split(', '), target) : error); - -``` - -{% endraw %} - -Binary Search in [JavaScript](/languages/javascript) was written by: - -- izexi - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/kotlin/index.md b/docs/projects/binary-search/kotlin/index.md deleted file mode 100644 index 80622c6d96..0000000000 --- a/docs/projects/binary-search/kotlin/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- Bolshialex -date: 2025-02-18 -featured-image: binary-search-in-every-language.jpg -last-modified: 2025-02-18 -layout: default -tags: -- binary-search -- kotlin -title: Binary Search in Kotlin -title1: Binary Search -title2: in Kotlin ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args : Array){ - if (args.size != 2) { - println("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")") - return - } - - val listInput = args[0].replace(",", "") - val targetInput = args[1] - - val arr: IntArray - val target: Int - - try { - arr = listInput.split(" ").map { it.toInt() }.toIntArray() - target = targetInput.toInt() - } catch (e: NumberFormatException) { - println("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")") - return - } - - if (!isSorted(arr)) { - println("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")") - return - } - - val result = binarySearch(arr, target) - println(result) -} - -fun binarySearch(arr: IntArray, target: Int): Boolean{ - var left = 0; - var right = arr.size - 1 - - while(left <= right){ - var mid = (left + right) / 2; - if(arr[mid] == target){ - return true - } else if(arr[mid] < target){ - left = mid + 1 - }else{ - right = mid - 1 - } - } - - return false -} - - -fun isSorted(arr: IntArray): Boolean { - for (i in 0 until arr.size - 1) { - if (arr[i] > arr[i + 1]) { - return false - } - } - return true -} -``` - -{% endraw %} - -Binary Search in [Kotlin](/languages/kotlin) was written by: - -- Bolshialex - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/m4/index.md b/docs/projects/binary-search/m4/index.md deleted file mode 100644 index 61dd0fecd2..0000000000 --- a/docs/projects/binary-search/m4/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-09-07 -featured-image: binary-search-in-every-language.jpg -last-modified: 2025-09-07 -layout: default -tags: -- binary-search -- m4 -title: Binary Search in m4 -title1: Binary -title2: Search in m4 ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11") -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl is_sorted(varname): -dnl if varname[length] < 2: -dnl Return 1 -dnl for n = 1 to varname[length] - 1: -dnl if varname[n - 1] > varname[n]: -dnl Return 0 -dnl Return 1 -define(`is_sorted', `ifelse(eval(array_get(`$1', `length') < 2), 1, `1', `_is_sorted(`$1', 1)')') -define(`_is_sorted', -`ifelse( -eval(incr($2) >= array_get(`$1', `length')), 1, `1', -eval(array_get(`$1', decr($2)) > array_get(`$1', $2)), 1, `0', -`_is_sorted(`$1', incr($2))'dnl -)'dnl -) - -dnl binary_search(varname, target): -dnl lo = 0 -dnl hi = varname[length] -dnl while lo < hi: -dnl mid = (lo + hi) // 2 -dnl if varname[mid] == target: -dnl Return mid -dnl elseif varname[mid] < target: -dnl lo = mid + 1 -dnl else: -dnl hi = mid -dnl Return -1 -define(`binary_search', -`pushdef(`mid', `')dnl -_binary_search(`$1', 0, array_get(`$1', `length'), $2)dnl -popdef(`mid')'dnl -) -define(`_binary_search', -`ifelse( -eval($2 >= $3), 1, `-1', -`define(`mid', eval(($2 + $3) / 2))dnl -ifelse( -array_get(`$1', mid), $4, mid, -eval(array_get(`$1', mid) < $4), 1, `_binary_search(`$1', incr(mid), $3, $4)', -`_binary_search(`$1', $2, mid, $4)'dnl -)'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 2 || len(ARGV1) < 1 || !parse_int_list(`arr', ARGV1) || !is_valid(ARGV2)), 1, `show_usage()')dnl -ifelse(is_sorted(`arr'), 0, `show_usage()')dnl -ifelse(binary_search(`arr', ARGV2), -1, `false', `true') - -``` - -{% endraw %} - -Binary Search in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/mathematica/index.md b/docs/projects/binary-search/mathematica/index.md deleted file mode 100644 index 5e33757708..0000000000 --- a/docs/projects/binary-search/mathematica/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-19 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-01-19 -layout: default -tags: -- binary-search -- mathematica -title: Binary Search in Mathematica -title1: Binary Search -title2: in Mathematica ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Binary search option binarySearch1 uses the built-in, modified to -return Null in case the element is not found: *) - -Needs["Combinatorica`"] - -binarySearch1 = If[IntegerQ[#], #, Null] & @* -Combinatorica`BinarySearch; - -(* If that is considered cheating, then option binarySearch2 implements it -using 'primitives': *) - -binarySearch2 = Function[{l, n}, - NestWhile[ (* keep subdividing the search interval *) - Apply[(* convert the single two-element list argument to two arguments *) - Function[{i, j},(* subdivide the given interval into a smaller one containing the item sought *) - Module[{m = Floor[(i + j)/2], me},(* use some definite element as the midpoint to test *) - me = l[[m]]; - Which[ - (* Did we find the element we're searching for? *) - me == n, m, - (* Element is before the midpoint? Then either keep searching, or give up *) - n < me, If[i < m, {i, m - 1}, Null], - (* Element is after the midpoint? Then either keep searching, or give up *) - n > me, If[m < j, {m + 1, j}, Null]]]]], - {1, Length[l]} (* begin by considering the entire list to search within *), - ListQ (* while we are still searching *)]]; - -(* The outer function does the string parsing: *) - -binarySearchMain = Function[{l, i}, - Module[{e = "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"}, - Catch[ - If[ - (* convert position to "true" or Null to "false" *) - IntegerQ[binarySearch2 @@ Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct two arguments to binary search: list of search array, item to search; as strings *) - {StringSplit[If[StringLength[l] > 0, l, Throw[e]], ", "], i}, - {-1} (* at each leaf *)]], - "true", "false"]]]]; - -(* Valid Tests *) -Print /@ Apply[binarySearchMain] /@ { - {"1, 4, 5, 11, 12", "4"}, - {"1, 3, 5, 7", "1"}, - {"1, 3, 5, 7", "7"}, - {"5", "5"}, - {"5", "7"}, - {"1, 3, 5, 6", "7"}}; - -(* Invalid Tests *) -binarySearchMain["1, 2, 3, 4",""] -binarySearchMain["", "5"] - -(* Not checking the 'list is unsorted' invalid test. *) -``` - -{% endraw %} - -Binary Search in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/pascal/index.md b/docs/projects/binary-search/pascal/index.md deleted file mode 100644 index 0ce7a61c38..0000000000 --- a/docs/projects/binary-search/pascal/index.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-21 -featured-image: binary-search-in-every-language.jpg -last-modified: 2025-07-21 -layout: default -tags: -- binary-search -- pascal -title: Binary Search in Pascal -title1: Binary Search -title2: in Pascal ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program BinarySearch; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - StrUtils, - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")'); - Halt(1); -end; - -type - TIntegerList = specialize TList; - -function ParseIntegerList(const S: string): TIntegerList; -var - tokens: TStringArray; - token: string; - val: integer; -begin - if S.Trim.IsEmpty then - ShowUsage; - - tokens := S.Split([',']); - Result := TIntegerList.Create; - for token in tokens do - begin - if not TryStrToInt(Trim(token), val) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(val); - end; - - if Result.Count = 0 then - begin - Result.Free; - ShowUsage; - end; -end; - -function IsSorted(const A: TIntegerList): boolean; -var - i, Length: integer; -begin - Length := A.Count; - if Length <= 1 then - Exit(True); - - for i := 1 to Length - 1 do - if A[i] < A[i - 1] then - Exit(False); - - Result := True; -end; - -// This is the textbook binary search, with a couple of early exits to not spend -// time on degenerate cases. -function BinarySearch(const List: TIntegerList; Value: integer): boolean; -var - Left, Right, Pivot: integer; - Length: integer; -begin - Length := List.Count; - - // Handle empty list - if Length = 0 then - Exit(False); - - // Handle single-element list - if Length = 1 then - Exit(List.First = Value); - - // If the value isn't within the range of values inside the array, there's no - // reason to even start the algorithm. - if (Value < List.First) or (Value > List.Last) then - Exit(False); - - Left := 0; - Right := Length - 1; - Result := False; - while Left <= Right do - begin - Pivot := Left + ((Right - Left) shr 1); - if List[Pivot] = Value then - Exit(True) - else if List[Pivot] < Value then - Left := Pivot + 1 - else - Right := Pivot - 1; - end; - - Result := False; -end; - -var - ListArg, ValueArg: string; - Numbers: TIntegerList; - Value: integer; -begin - if ParamCount <> 2 then - ShowUsage; - - ListArg := Trim(ParamStr(1)); - ValueArg := Trim(ParamStr(2)); - - if ListArg.IsEmpty or ValueArg.IsEmpty then - ShowUsage; - - Numbers := ParseIntegerList(ListArg); - try - if not IsSorted(Numbers) then - ShowUsage; - - if not TryStrToInt(ValueArg, Value) then - ShowUsage; - - Writeln(BoolToStr(BinarySearch(Numbers, Value), 'true', 'false')); - finally - Numbers.Free; - end; -end. - -``` - -{% endraw %} - -Binary Search in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/perl/index.md b/docs/projects/binary-search/perl/index.md deleted file mode 100644 index d0eec9abc0..0000000000 --- a/docs/projects/binary-search/perl/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Meet Thakur -- Ștefan-Iulian Alecu -date: 2025-10-11 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- binary-search -- perl -title: Binary Search in Perl -title1: Binary Search -title2: in Perl ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -use feature qw/keyword_any/; -no warnings 'experimental::keyword_any'; - -sub usage { - say 'Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")'; - exit; -} - -sub parse_list ($s) { - return undef unless defined $s; - - my @vals = split /\s*,\s*/, $s; - - return undef unless @vals; - return undef if any { $_ !~ /\A\d+\z/ } @vals; - - @vals = map 0 + $_, @vals; - - return undef if any { $vals[$_] > $vals[ $_ + 1 ] } 0 .. $#vals - 1; - return \@vals; -} - -sub binary_search ( $a, $x ) { - my ( $lo, $hi ) = ( 0, $#$a ); - - while ( $lo <= $hi ) { - my $mid = ( $lo + $hi ) >> 1; - - return "true" if $a->[$mid] == $x; - $hi = $mid - 1 if $a->[$mid] > $x; - $lo = $mid + 1 if $a->[$mid] < $x; - } - - return "false"; -} - -my ( $list_s, $num_s ) = @ARGV; - -defined $num_s or usage(); - -my $list = parse_list($list_s) or usage(); - -usage() unless $num_s =~ /\A\d+\z/; -my $num = 0 + $num_s; - -say binary_search( $list, $num ); - -``` - -{% endraw %} - -Binary Search in [Perl](/languages/perl) was written by: - -- Meet Thakur -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/php/index.md b/docs/projects/binary-search/php/index.md deleted file mode 100644 index f0db2038e3..0000000000 --- a/docs/projects/binary-search/php/index.md +++ /dev/null @@ -1,178 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-21 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-03-27 -layout: default -tags: -- binary-search -- php -title: Binary Search in PHP -title1: Binary Search -title2: in PHP ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -function check_sorted($values) -{ - for ($index = 1; $index < count($values); $index++) - { - if ($values[$index - 1] > $values[$index]) { - return FALSE; - } - } - - return TRUE; -} - -function binary_search($target, $values) -{ - $low = 0; - $high = count($values); - while ($low < $high) - { - $mid = intdiv($low + $high, 2); - - // If found it, return index - if ($values[$mid] == $target) - { - return $mid; - } - - // If too low, move lower bound - if ($values[$mid] < $target) - { - $low = $mid + 1; - } - // Else, move upper bound - else - { - $high = $mid; - } - } - - return -1; -} - -// Exit if too few arguments -if (count($argv) < 3) -{ - usage(); -} - -// Parse 1st argument. Exit if invalid -$values = parse_int_array($argv[1]); -if ($values === FALSE) -{ - usage(); -} - -// Parse 2nd argument. Exit if invalid -$target = parse_int($argv[2]); -if ($target == FALSE) -{ - usage(); -} - -// Make sure list is sorted -if (!check_sorted($values)) -{ - usage(); -} - -// Do binary search and show results -$index = binary_search($target, $values); -printf("%s\n", ($index >= 0) ? "true" : "false"); -?> - -``` - -{% endraw %} - -Binary Search in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/powershell/index.md b/docs/projects/binary-search/powershell/index.md deleted file mode 100644 index 30d7e2f381..0000000000 --- a/docs/projects/binary-search/powershell/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-07 -featured-image: binary-search-in-every-language.jpg -last-modified: 2025-07-07 -layout: default -tags: -- binary-search -- powershell -title: Binary Search in PowerShell -title1: Binary Search -title2: in PowerShell ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -function Test-IsSorted([int[]]$arr) { - for ($i = 1; $i -lt $arr.Length; $i++) { - if ($arr[$i - 1] -gt $arr[$i]) { - return $false - } - } - - $true -} - -function Invoke-BinarySearch([int[]]$arr, [int]$target) { - [Array]::BinarySearch($arr, $target) -} - -if ($args.Length -lt 2 -or -not $args[0]) { - Show-Usage -} - -try { - $arr = Parse-IntList $args[0] - $target = [int]::Parse($args[1]) -} catch { - Show-Usage -} - -if (-not (Test-IsSorted $arr)) { - Show-Usage -} - -$idx = Invoke-BinarySearch $arr $target -Write-Output (($idx -ge 0) ? "true" : "false") - -``` - -{% endraw %} - -Binary Search in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/python/index.md b/docs/projects/binary-search/python/index.md deleted file mode 100644 index 0b46d0e5a3..0000000000 --- a/docs/projects/binary-search/python/index.md +++ /dev/null @@ -1,224 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- shubhragupta-code -- Vikram Rayavarapu -date: 2019-10-27 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- binary-search -- python -title: Binary Search in Python -title1: Binary Search -title2: in Python ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def binary_search(array_list, key): - start = 0 - end = len(array_list) - while start < end: - mid = (start + end) // 2 - if array_list[mid] > key: - end = mid - elif array_list[mid] < key: - start = mid + 1 - else: - return mid - return -1 - - -def input_list(list_str): - array_of_numbers = list_str - array_of_numbers = array_of_numbers.split(",") - array_of_numbers = [int(x) for x in array_of_numbers] - return array_of_numbers - - -def exit_with_error(): - print('Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")') - sys.exit(1) - - -if __name__ == "__main__": - try: - array_of_numbers = sys.argv[1] - value_to_be_found = int(sys.argv[2]) - array_of_numbers = input_list(array_of_numbers) - - if array_of_numbers != sorted( - array_of_numbers) or len(array_of_numbers) < 1: - exit_with_error() - index = binary_search(array_of_numbers, value_to_be_found) - if index < 0: - print(False) - else: - print(True) - except (IndexError, ValueError): - exit_with_error() - -``` - -{% endraw %} - -Binary Search in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Vikram Rayavarapu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code -- Vikram Rayavarapu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -### The Main Function - -Breaking down this solution from bottom to top, - -```python -if __name__ == "__main__": - try: - array_of_numbers = sys.argv[1] - value_to_be_found = int(sys.argv[2]) - array_of_numbers = input_list(array_of_numbers) - - if array_of_numbers != sorted( - array_of_numbers) or len(array_of_numbers) < 1: - exit_with_error() - index = binary_search(array_of_numbers, value_to_be_found) - if index < 0: - print(False) - else: - print(True) - except (IndexError, ValueError): - exit_with_error() -``` - -This bit of code checks to see if this is the main module run. If it is then it starts exectuing the code -function and passes user input to main program. In this case the user inputs are two strings -for example they are like as follows`"1, 4, 5, 11, 12"` `"11"`. - -```python -def binary_search(alist, key_value): - start = 0 - end = len(alist) - while start < end: - mid = (start + end)//2 - if alist[mid] > key_value: - end = mid - elif alist[mid] < key_value: - start = mid + 1 - else: - return mid - return -1 - -``` - -This is the main function of this file. It parses the input, then calls our binary search function -(and returns mid (index of our key_value) or -1 (If key_value is not avaliable)). - -### Transform Input Parameters - -```python -def input_list(list_str): - array_of_numbers = list_str - array_of_numbers = array_of_numbers.split(",") - array_of_numbers = [int(x) for x in array_of_numbers] - return array_of_numbers -``` - -This function takes a string like `"1, 4, 5, 11, 12"`, and turns into a list of numbers. -It does this using a list comprehension, first we need to convert our string into a -list `array_of_numbers.split(',')` which is a list of strings split by comma (,). So our -original input string becomes `["1", " 4", " 5", " 11", " 12"]`. -Then for each element in the list `for x in ...` , we convert it to an `int`. For example, -the string `" 4"` is converted into a decimal number in this case `4` (it removes the " "(space) too). This is done -for every item in the list so our original input `"1, 4, 5, 11, 12"` becomes `[1, 4, 5, 11, 12]`. - -### Throws Error - -```python -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) -``` - -This function prints a message and then exits the script with an error, `sys.exit(1)`. -If any non-zero value is returned after execution of program then the program didn't complete properly. -The above function (`exit_with_error()`) is called everytime whenever the user input isn't correct. - -### Binary Search - -```python -def binary_search(alist, key_value): - start = 0 - end = len(alist) - while start < end: - mid = (start + end) // 2 - if alist[mid] > key_value: - end = mid - elif alist[mid] < key_value: - start = mid + 1 - else: - return mid - return -1 -``` - -This function takes a sorted integer list and a value and returns the index of the item found (or `-1` if not) -using the binary search algorithm. - -For example, if `[1, 4, 5, 11, 12]` is the input: - -* First we take `start = 0`, `end = len(alist)` - -* while `start` is less than `end`, we keep on iterating loop - -* first we take middle value of array with the expression (`mid = (start + end) // 2`) - -* Then we compare the middle value that we got (`mid`) with `key_value` - -* If the middle value (`mid`) is greater than `key_value` then we take `end` as middle value (`mid`) and continue searching. - -* If the middle value (`mid`) is less than `key_value` then we take end as middle value + 1 (`mid + 1`) and continue searching. - -* If key_value is neither greater nor lesser than that of the middle value, then it means that the value that we are searching is at `mid`. So we return the index of the `key_value` (if value in the given list) or `-1` (if not). - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of Binary Search in Python. -After that, we should make sure we have the latest Python interpreter. -From there, we can run the following command in the terminal: - -`python binary_search.py "1, 4, 5, 11, 12" "11"` - -Alternatively, we can copy the solution into an online Python interpreter and hit run then you need to modify `sys.argv[i]` to your inputs. diff --git a/docs/projects/binary-search/ruby/index.md b/docs/projects/binary-search/ruby/index.md deleted file mode 100644 index 1c63aca6c1..0000000000 --- a/docs/projects/binary-search/ruby/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Tyler Gilmore -- Ștefan-Iulian Alecu -date: 2024-11-09 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- binary-search -- ruby -title: Binary Search in Ruby -title1: Binary Search -title2: in Ruby ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -module Enumerable - def sorted? - each_cons(2).all? { |a, b| (a <=> b) <= 0 } - end -end - -def parse_args - list, key = ARGV - raise ArgumentError unless list && key - - parts = list.split(",").map(&:strip) - raise ArgumentError if parts.empty? || parts.any?(&:empty?) - - numbers = parts.map { Integer(it, exception: false) } - raise ArgumentError if numbers.any?(nil) - - key = Integer(key, exception: false) - raise ArgumentError if key.nil? - - raise ArgumentError unless numbers.sorted? - - [numbers, key] -end - -begin - numbers, key = parse_args - puts !numbers.bsearch { key <=> it }.nil? -rescue ArgumentError - warn 'Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")' -end - -``` - -{% endraw %} - -Binary Search in [Ruby](/languages/ruby) was written by: - -- Tyler Gilmore -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/rust/index.md b/docs/projects/binary-search/rust/index.md deleted file mode 100644 index e016d92525..0000000000 --- a/docs/projects/binary-search/rust/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- Andrew Johnson -- rzuckerm -date: 2020-10-03 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- binary-search -- rust -title: Binary Search in Rust -title1: Binary Search -title2: in Rust ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -fn is_sorted(arr: &Vec) -> bool { - (0..(arr.len() - 1)) - .all(|x| arr[x] <= arr[x + 1]) -} - -fn binary_search(search_arr: &Vec, target: &T) -> Option { - let mut low: usize = 0; - let mut high: usize = search_arr.len() - 1; - - while low <= high { - let mid = ((high - low) / 2) + low; - let val = &search_arr[mid]; - - if val == target { - return Some(mid); - } - - // If value is < target then search between mid + 1 and high - if val < target { - low = mid + 1; - } - - // If value is > target then search between low and mid - 1 - if val > target { - high = mid - 1; - } - } - - return None; -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Make sure array is sorted - if !is_sorted(&arr) { - usage(); - } - - // Convert 2nd command-line argument to integer - let target: i32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - match binary_search::(&arr, &target) { - Some(_) => println!("true"), - None => println!("false"), - } -} - -``` - -{% endraw %} - -Binary Search in [Rust](/languages/rust) was written by: - -- Andrew Johnson -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/swift/index.md b/docs/projects/binary-search/swift/index.md deleted file mode 100644 index 06a154d1b5..0000000000 --- a/docs/projects/binary-search/swift/index.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- binary-search -- swift -title: Binary Search in Swift -title1: Binary Search -title2: in Swift ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11") - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -extension Collection where Element: Comparable { - var isSorted: Bool { zip(self, dropFirst()).allSatisfy(<=) } -} - -extension Collection { - subscript(safe index: Index) -> Element? { - indices.contains(index) ? self[index] : nil - } -} - -extension RandomAccessCollection where Element: Comparable { - func binarySearch(for target: Element) -> Index? { - var low = startIndex - var high = index(before: endIndex) - - while low <= high { - let distance = self.distance(from: low, to: high) - let mid = index(low, offsetBy: distance / 2) - - let value = self[mid] - - if value == target { return mid } - if value < target { - low = index(after: mid) - } else { - high = index(before: mid) - } - } - - return nil - } -} - -func parseInput(_ args: [String]) -> ([Int], Int)? { - guard - let rawList = args[safe: 1], - let rawTarget = args[safe: 2], - let target = Int(rawTarget) - else { return nil } - - let values = - rawList - .split(separator: ",") - .compactMap { Int($0.trimmed) } - - guard !values.isEmpty, values.isSorted else { - return nil - } - - return (values, target) -} - -guard let (values, target) = parseInput(CommandLine.arguments) else { - print(usage) - exit(1) -} - -print(values.binarySearch(for: target) != nil) - -``` - -{% endraw %} - -Binary Search in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/tcl/index.md b/docs/projects/binary-search/tcl/index.md deleted file mode 100644 index c6962f42a7..0000000000 --- a/docs/projects/binary-search/tcl/index.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-07 -featured-image: binary-search-in-every-language.jpg -last-modified: 2025-10-07 -layout: default -tags: -- binary-search -- tcl -title: Binary Search in Tcl -title1: Binary Search -title2: in Tcl ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a list of sorted integers ("1, 4, 5, 11, 12") and the integer to find ("11")} - exit 1 -} - -proc parseIntegerList {s} { - set s [string trim $s] - if {$s eq ""} { - usage - } - - set tokens [split $s ","] - set result {} - - foreach token $tokens { - set t [string trim $token] - if {$t eq ""} { - usage - } - if {[catch {expr {int($t)}} val]} { - usage - } - lappend result $val - } - - if {[llength $result] == 0} { - usage - } - return $result -} - -proc isSorted {lst} { - set len [llength $lst] - if {$len <= 1} { return 1 } - for {set i 1} {$i < $len} {incr i} { - if {[lindex $lst $i] < [lindex $lst [expr {$i - 1}]]} { - return 0 - } - } - return 1 -} - -proc binarySearch {lst value} { - set len [llength $lst] - if {$len == 0} { return 0 } - if {$len == 1} { - return [expr {[lindex $lst 0] == $value}] - } - - # Since binary search assumes a sorted list, if the value isn't within - # the range of the values inside the list, there's no need to even start - # the algorithm. - set first [lindex $lst 0] - set last [lindex $lst end] - if {$value < $first || $value > $last} { return 0 } - - set left 0 - set right [expr {$len - 1}] - - while {$left <= $right} { - set mid [expr {$left + (($right - $left) / 2)}] - set pivot [lindex $lst $mid] - - if {$pivot == $value} { - return 1 - } elseif {$pivot < $value} { - set left [expr {$mid + 1}] - } else { - set right [expr {$mid - 1}] - } - } - return 0 -} - -if {$argc != 2} { - usage -} - -set listArg [string trim [lindex $argv 0]] -set valueArg [string trim [lindex $argv 1]] - -if {$listArg eq "" || $valueArg eq ""} { - usage -} - -set numbers [parseIntegerList $listArg] - -if {![isSorted $numbers]} { - usage -} - -if {[catch {expr {int($valueArg)}} value]} { - usage -} - -puts [expr {[binarySearch $numbers $value] ? "true" : "false"}] - -``` - -{% endraw %} - -Binary Search in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/typescript/index.md b/docs/projects/binary-search/typescript/index.md deleted file mode 100644 index 7df05b7909..0000000000 --- a/docs/projects/binary-search/typescript/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2023-10-07 -featured-image: binary-search-in-every-language.jpg -last-modified: 2023-10-07 -layout: default -tags: -- binary-search -- typescript -title: Binary Search in TypeScript -title1: Binary Search -title2: in TypeScript ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -const error_msg: string = "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"; -if (process.argv.length != 4) { - console.log(error_msg); - process.exit(1); -} - -let list_str: string = process.argv[2] -let target: number = parseInt(process.argv[3]); - -if (isNaN(target) || list_str.length == 0) { - console.log(error_msg); - process.exit(1); -} -let list: number[] = list_str.split(",").map((x: string) => parseInt(x)); -// check if list is sorted -for (let i: number = 1; i < list.length; i++) { - if (list[i] < list[i - 1]) { - console.log(error_msg); - process.exit(1); - } -} -let found: boolean = false; -let low: number = 0; -let high: number = list.length - 1; -while (low <= high) { - let mid: number = Math.floor((low + high) / 2); - if (list[mid] == target) { - found = true; - break; - } - if (list[mid] < target) { - low = mid + 1; - } else { - high = mid - 1; - } -} -console.log(found ? "true" : "false"); -``` - -{% endraw %} - -Binary Search in [TypeScript](/languages/typescript) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/binary-search/visual-basic/index.md b/docs/projects/binary-search/visual-basic/index.md deleted file mode 100644 index 12d023d826..0000000000 --- a/docs/projects/binary-search/visual-basic/index.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: binary-search-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- binary-search -- visual-basic -title: Binary Search in Visual Basic -title1: Binary Search -title2: in Visual Basic ---- - - - -Welcome to the [Binary Search](/projects/binary-search) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System - -Module BinarySearch - - Sub Main(args As String()) - - If args.Length <> 2 Then - ShowUsage() - Return - End If - - Dim list = ParseList(args(0)) - Dim target As Integer - - If list Is Nothing OrElse Not Integer.TryParse(args(1), target) Then - ShowUsage() - Return - End If - - If Not IsSorted(list) Then - ShowUsage() - Return - End If - - Console.WriteLine(BinarySearch(list, target)) - - End Sub - - Private Function ParseList(input As String) As List(Of Integer) - - Dim result As New List(Of Integer) - - For Each part In input.Split(","c) - - Dim value As Integer - - If Not Integer.TryParse(part.Trim(), value) Then - Return Nothing - End If - - result.Add(value) - - Next - - Return result - - End Function - - Private Function BinarySearch(list As List(Of Integer), target As Integer) As Boolean - - Dim low = 0 - Dim high = list.Count - 1 - - While low <= high - - Dim mid = (low + high) \ 2 - - If list(mid) = target Then - Return True - ElseIf list(mid) < target Then - low = mid + 1 - Else - high = mid - 1 - End If - - End While - - Return False - - End Function - - Private Function IsSorted(list As List(Of Integer)) As Boolean - - For i = 0 To list.Count - 2 - If list(i) > list(i + 1) Then - Return False - End If - Next - - Return True - - End Function - - Private Sub ShowUsage() - Console.WriteLine( - "Usage: please provide a list of sorted integers " & - "(""1, 4, 5, 11, 12"") and the integer to find (""11"")" - ) - End Sub - -End Module -``` - -{% endraw %} - -Binary Search in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/ada/index.md b/docs/projects/bubble-sort/ada/index.md deleted file mode 100644 index a63b348ee1..0000000000 --- a/docs/projects/bubble-sort/ada/index.md +++ /dev/null @@ -1,172 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-09 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-05-09 -layout: default -tags: -- ada -- bubble-sort -title: Bubble Sort in Ada -title1: Bubble Sort -title2: in Ada ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Containers.Vectors; - -procedure Bubble_Sort is - - Parse_Error : exception; - - package Int_Vec is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - use Int_Vec; - - procedure Bubble_Sort (V : in out Vector) is - begin - if Natural (Length (V)) <= 1 then - return; - end if; - - for I in reverse First_Index (V) + 1 .. Last_Index (V) loop - for J in First_Index (V) .. I - 1 loop - if Element (V, J) > Element (V, J + 1) then - Swap (V, J, J + 1); - end if; - end loop; - end loop; - end Bubble_Sort; - - function Parse_Int (S : String) return Integer is - Clean : constant String := Trim (S, Ada.Strings.Both); - begin - if Clean'Length = 0 then - raise Parse_Error; - end if; - - return Integer'Value (Clean); - exception - when others => - raise Parse_Error; - end Parse_Int; - - function Parse_List (S : String) return Vector is - V : Vector; - Start : Positive := S'First; - Count : Natural := 0; - begin - if S'Length = 0 then - raise Parse_Error; - end if; - - for I in S'Range loop - if S (I) = ',' then - if Start > I - 1 then - raise Parse_Error; -- empty element like ",," - - end if; - - Append (V, Parse_Int (S (Start .. I - 1))); - Count := Count + 1; - Start := I + 1; - end if; - end loop; - - -- last element - if Start > S'Last then - raise Parse_Error; - end if; - - Append (V, Parse_Int (S (Start .. S'Last))); - Count := Count + 1; - - if Count < 2 then - raise Parse_Error; - end if; - - return V; - end Parse_List; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide a list of at least two integers to sort in the format ""1, 2, 3, 4, 5"""); - end Print_Usage; - - procedure Print_Vector (V : Vector) is - function Img (X : Integer) return String - is (Trim (Integer'Image (X), Ada.Strings.Left)); - begin - for I in First_Index (V) .. Last_Index (V) loop - Put (Img (Element (V, I))); - - if I /= Last_Index (V) then - Put (", "); - end if; - end loop; - - New_Line; - end Print_Vector; - -begin - if Argument_Count /= 1 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - declare - V : Vector; - begin - V := Parse_List (Argument (1)); - Bubble_Sort (V); - Print_Vector (V); - - exception - when Parse_Error | Constraint_Error => - Print_Usage; - Set_Exit_Status (Failure); - end; - -end Bubble_Sort; - -``` - -{% endraw %} - -Bubble Sort in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/algol60/index.md b/docs/projects/bubble-sort/algol60/index.md deleted file mode 100644 index 79c6b3b730..0000000000 --- a/docs/projects/bubble-sort/algol60/index.md +++ /dev/null @@ -1,269 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-17 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- bubble-sort -title: Bubble Sort in ALGOL 60 -title1: Bubble Sort -title2: in ALGOL 60 ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of at least two integers " - "to sort in the format \"1, 2, 3, 4, 5\"\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Output integer array; - procedure outIntegerArray(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i; - for i := 1 step 1 until arrLen do - begin - if i > 1 then outstring(1, ", "); - outIntegerNoSpace(arr[i]) - end; - - if arrLen > 0 then outstring(1, "\n") - end outIntegerArray; - - comment Source https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort; - procedure bubbleSort(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i, n, newN, temp; - - n := arrLen; - sortloop: - newN := 1; - for i := 2 step 1 until n do - begin - if arr[i - 1] > arr[i] then - begin - temp := arr[i - 1]; - arr[i - 1] := arr[i]; - arr[i] := temp; - newN := i - end - end; - - n := newN; - if n > 2 then goto sortloop - end bubbleSort; - - integer argc, arrLen; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 2 then usage; - - comment Bubble sort input and output result; - bubbleSort(arr, arrLen); - outIntegerArray(arr, arrLen) -end - -``` - -{% endraw %} - -Bubble Sort in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/algol68/index.md b/docs/projects/bubble-sort/algol68/index.md deleted file mode 100644 index 11c68f40a7..0000000000 --- a/docs/projects/bubble-sort/algol68/index.md +++ /dev/null @@ -1,206 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-27 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2023-01-30 -layout: default -tags: -- algol68 -- bubble-sort -title: Bubble Sort in ALGOL 68 -title1: Bubble Sort -title2: in ALGOL 68 ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a list of at least two integers to sort in the format ""1, 2, 3, 4, 5""")) -); - -PROC bubble sort = (REF []INT values) VOID: -( - COMMENT - Source: https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort - COMMENT - - INT n := UPB values; - INT new n; - INT temp; - DO - new n := 1; - FOR i FROM 2 TO n - DO - IF values[i - 1] > values[i] - THEN - temp := values[i - 1]; - values[i - 1] := values[i]; - values[i] := temp; - new n := i - FI - OD; - n := new n - UNTIL n <= 2 - OD -); - -PROC show list values = (REF []INT values) VOID: -( - INT n = UPB values; - FOR k TO n - DO - IF k > 1 - THEN - print(", ") - FI; - - print(whole(values[k], 0)) - OD; - - IF n > 0 - THEN - print(newline) - FI -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result OR UPB values < 2 -THEN - usage; - stop -FI; - -# Do bubble sort and show results # -bubble sort(values); -show list values(values) - -``` - -{% endraw %} - -Bubble Sort in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/awk/index.md b/docs/projects/bubble-sort/awk/index.md deleted file mode 100644 index 50120c9588..0000000000 --- a/docs/projects/bubble-sort/awk/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-16 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- bubble-sort -title: Bubble Sort in AWK -title1: Bubble Sort -title2: in AWK ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -# Source: https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort -function bubble_sort(arr, arr_len, i, t, n, new_n) { - n = arr_len - do { - new_n = 1 - for (i = 2; i <= n; i++) { - if (arr[i - 1] > arr[i]) { - t = arr[i - 1] - arr[i - 1] = arr[i] - arr[i] = t - new_n = i - } - } - - n = new_n - } while (n > 1) -} - -function show_array(arr, idx, s) { - s = "" - for (idx in arr) { - if (s) { - s = s ", " - } - s = s arr[idx] - } - - print s -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], arr) - arr_len = length(arr) - if (!arr_len || arr_len < 2) { - usage() - } - - bubble_sort(arr, arr_len) - show_array(arr) -} - -``` - -{% endraw %} - -Bubble Sort in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/bash/index.md b/docs/projects/bubble-sort/bash/index.md deleted file mode 100644 index c4c8b3ba44..0000000000 --- a/docs/projects/bubble-sort/bash/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Lucas Schaan -date: 2019-10-01 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2019-10-01 -layout: default -tags: -- bash -- bubble-sort -title: Bubble Sort in Bash -title1: Bubble Sort -title2: in Bash ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -ERROR="Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - -function bubble-sort { - new_array=(${array[@]::${#array[@]}-1}) #all elements except the last one - for i in "${!array[@]}"; do - switch=false; - for j in "${!new_array[@]}" ; do - if [ "${array[j]}" -gt "${array[j+1]}" ]; then - aux=${array[j]} - array[j]=${array[j+1]} - array[j+1]=$aux - switch=true; - fi; - done; - if [ $switch = false ]; then - break; - fi; - done; -} - -#Validation to fit criteria -if [ "$#" != "1" ]; then echo $ERROR; exit 1; fi; #wrong input -if [[ ! "$1" =~ "," ]]; then echo $ERROR; exit 1; fi; #wrong format - -array=($(echo $@ | tr ", " " ")) - -if [ "${array[0]}" == "" ]; then echo $ERROR; exit 1; fi; #empty input -if [ "${#array[@]}" == "1" ]; then echo $ERROR; exit 1; fi; #not a list - -bubble-sort array -arrayString=${array[@]} -echo "${arrayString//" "/", "}" - - -``` - -{% endraw %} - -Bubble Sort in [Bash](/languages/bash) was written by: - -- Lucas Schaan - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/beef/index.md b/docs/projects/bubble-sort/beef/index.md deleted file mode 100644 index acb00e479a..0000000000 --- a/docs/projects/bubble-sort/beef/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-02 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2024-02-02 -layout: default -tags: -- beef -- bubble-sort -title: Bubble Sort in Beef -title1: Bubble Sort -title2: in Beef ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace BubbleSort; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Reference: https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort - public static void BubbleSort(List arr) - where int : operator T <=> T - { - int n = arr.Count; - while (n > 0) - { - int newN = 0; - for (int i in 1..< n) - { - if (arr[i - 1] > arr[i]) - { - Swap!(arr[i - 1], arr[i]); - newN = i; - } - } - - n = newN; - } - } - - public static void ShowList(List arr) - { - String line = scope .(); - for (T val in arr) - { - if (!line.IsEmpty) - { - line += ", "; - } - - line.AppendF("{}", val); - } - - Console.WriteLine(line); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - List arr = scope .(); - switch (ParseIntList(args[0], arr)) - { - case .Ok: - if (arr.Count < 2) - { - Usage(); - } - case .Err: - Usage(); - } - - BubbleSort(arr); - ShowList(arr); - return 0; - } -} - -``` - -{% endraw %} - -Bubble Sort in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/c-plus-plus/index.md b/docs/projects/bubble-sort/c-plus-plus/index.md deleted file mode 100644 index d6c292929f..0000000000 --- a/docs/projects/bubble-sort/c-plus-plus/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -authors: -- Jayden Thrasher -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2019-10-02 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- bubble-sort -- c-plus-plus -title: Bubble Sort in C++ -title1: Bubble Sort -title2: in C++ ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5")" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - s = trim(s); - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -template - requires std::sortable> -void bubble_sort(R&& r) { - auto end_it = ranges::end(r); - if (ranges::begin(r) == end_it) return; - - while (ranges::begin(r) != end_it) { - auto last_swapped = ranges::begin(r); - auto current = ranges::begin(r); - auto next = std::next(current); - - while (next != end_it) { - if (*next < *current) { - ranges::iter_swap(current, next); - last_swapped = next; - } - current = next++; - } - if (last_swapped == ranges::begin(r)) break; - end_it = last_swapped; - } -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - const std::string_view input{argv[1]}; - auto ints_view = input | views::split(',') | - views::transform([](auto&& rng) { - return std::string_view(rng.begin(), rng.end()); - }) | - views::transform(to_int) | - views::filter([](auto&& opt) { return opt.has_value(); }) | - views::transform([](auto&& opt) { return *opt; }); - - std::vector numbers; - ranges::copy(ints_view, std::back_inserter(numbers)); - - if (numbers.size() < 2) usage(); - - bubble_sort(numbers); - - for (const char* sep = ""; int val : numbers) { - std::cout << std::exchange(sep, ", ") << val; - } - std::cout << "\n"; - - return 0; -} -``` - -{% endraw %} - -Bubble Sort in [C++](/languages/c-plus-plus) was written by: - -- Jayden Thrasher -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/c-sharp/index.md b/docs/projects/bubble-sort/c-sharp/index.md deleted file mode 100644 index 0594c57c1e..0000000000 --- a/docs/projects/bubble-sort/c-sharp/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-28 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- bubble-sort -- c-sharp -title: Bubble Sort in C# -title1: Bubble -title2: Sort in C# ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Runtime.InteropServices; - -if (args is not [var input] || !TryParseList(input.AsSpan(), out var numbers)) - return Usage(); - -BubbleSort(numbers); - -Console.WriteLine(string.Join(", ", numbers)); -return 0; - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return numbers.Count > 1; -} - -static void BubbleSort(List list) -{ - Span span = CollectionsMarshal.AsSpan(list); - int n = span.Length; - - for (int i = 0; i < n - 1; i++) - { - bool swapped = false; - - for (int j = 0; j < n - i - 1; j++) - { - if (span[j] <= span[j + 1]) - continue; - - (span[j], span[j + 1]) = (span[j + 1], span[j]); - swapped = true; - } - - if (!swapped) - return; - } -} - - -static int Usage() -{ - Console.Error.WriteLine(""" -Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -""" - ); - return 1; -} -``` - -{% endraw %} - -Bubble Sort in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/c/index.md b/docs/projects/bubble-sort/c/index.md deleted file mode 100644 index dda5a0643d..0000000000 --- a/docs/projects/bubble-sort/c/index.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- Ștefan-Iulian Alecu -date: 2019-01-04 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- bubble-sort -- c -title: Bubble Sort in C -title1: Bubble -title2: Sort in C ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include -#include - -size_t parse_list(const char *orig_list, long **arr) -{ - char *list; - char *token; - size_t num_elements = 0; - int i; - int curr_index = 0; - long temp_num; - - /* figure out the length of the list first */ - for (i = 0; orig_list[i]; i++) - if (orig_list[i] == ',') - num_elements++; - - /* if there are no commas, it's an invalid list */ - if (num_elements == 0) - { - *arr = NULL; - return 0; - } - - /* since there's one more number than there are commas, add one */ - num_elements++; - - /* alloc our array */ - *arr = malloc(num_elements * sizeof(long)); - - /* find the numbers */ - list = strdup(orig_list); - token = strtok(list, ","); - while (token != NULL) - { - errno = 0; - temp_num = strtol(token, NULL, 10); - if (errno != 0) - { - *arr = NULL; - return 0; - } - - (*arr)[curr_index++] = temp_num; - - token = strtok(NULL, ","); - } - - free(list); - - return num_elements; -} - -void swap_elements(long *arr, size_t i, size_t j) -{ - long temp; - - temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; -} - -int bubble_sort(long *arr, size_t num_elems) -{ - int i; - bool had_to_swap; - - while (true) - { - had_to_swap = false; - - for (i = 0; i < num_elems - 1; i++) - { - if (arr[i] > arr[i + 1]) - { - swap_elements(arr, i, i + 1); - had_to_swap = true; - } - } - - if (!had_to_swap) - break; - } - - return 0; -} - -void print_array(long *arr, size_t num_elems) -{ - int i; - - for (i = 0; i < num_elems - 1; i++) - printf("%ld, ", arr[i]); - - printf("%ld\n", arr[num_elems - 1]); -} - -void usage() -{ - fputs("Usage: please provide a list of at least two integers to sort in " - "the format \"1, 2, 3, 4, 5\"\n", - stderr); -} - -int main(int argc, char **argv) -{ - long *arr; - long num_elements; - - if (argc < 2) - { - usage(); - return 1; - } - - num_elements = parse_list(argv[1], &arr); - if (num_elements == 0) - { - usage(); - return 1; - } - - bubble_sort(arr, num_elements); - print_array(arr, num_elements); - - free(arr); -} - -``` - -{% endraw %} - -Bubble Sort in [C](/languages/c) was written by: - -- Christoph Böhmwalder -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/clojure/index.md b/docs/projects/bubble-sort/clojure/index.md deleted file mode 100644 index 498ba5c64d..0000000000 --- a/docs/projects/bubble-sort/clojure/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Kateryna Tokar -- Tobias Schröder -date: 2019-10-02 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2019-10-19 -layout: default -tags: -- bubble-sort -- clojure -title: Bubble Sort in Clojure -title1: Bubble Sort -title2: in Clojure ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Clojure](/languages/clojure) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```clojure -(ns bubble-sort - (:gen-class)) - -(defn- bubble [ys x] - (if-let [y (peek ys)] - (if (> y x) - (conj (pop ys) x y) - (conj ys x)) - [x])) - -(defn bubble-sort [xs] - (let [ys (reduce bubble [] xs)] - (if (= xs ys) - xs - (recur ys)))) - -(defn- convert-to-int-array [string] - (->> (clojure.string/split string #", " ) - (map #(Integer/parseInt %)))) - -(defn- convert-to-string [int-array] - (clojure.string/join ", " int-array)) - -(defn- print-bubble-sort [string] - (println - (convert-to-string - (bubble-sort - (convert-to-int-array string))))) - -(defn- is-valid-input [args] - (and - (not= (count args) 0) - (not= (first args) "") - (> (count (convert-to-int-array (first args))) 1) - )) - -(defn- print-error [] - (println "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"")) - -(defn main [args] - (try - (if (is-valid-input args) - (print-bubble-sort (first args)) - (print-error)) - (catch Exception e (print-error)))) - -(main *command-line-args*) -``` - -{% endraw %} - -Bubble Sort in [Clojure](/languages/clojure) was written by: - -- Kateryna Tokar -- Tobias Schröder - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/cobol/index.md b/docs/projects/bubble-sort/cobol/index.md deleted file mode 100644 index a70a3398f3..0000000000 --- a/docs/projects/bubble-sort/cobol/index.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-21 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-04-21 -layout: default -tags: -- bubble-sort -- cobol -title: Bubble Sort in COBOL -title1: Bubble Sort -title2: in COBOL ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. bubble-sort. - -data division. -working-storage section. - -01 max-entries constant as 1000. - -01 argument-string pic x(32768). -01 current-token pic x(128). -01 scan-ptr binary-long. - -01 sort-table. - 05 list-size binary-long value 0. - 05 entry-value pic s9(9) occurs 0 to max-entries - depending on list-size. - -01 work-vars. - 05 i binary-long. - 05 temp-val pic s9(9). - 05 last-swap-pos binary-long. - 05 new-swap-pos binary-long. - -01 flags. - 05 swap-flag pic x. - 88 has-swapped value 'Y'. - 88 no-swaps value 'N'. - -01 output-formatting. - 05 display-num pic ---------9. - 05 separator pic x(2) value ", ". - -procedure division. - -main. - perform validate-input - perform parse-input - perform execute-sort - perform display-results - goback. - -validate-input. - accept argument-string from argument-value - if argument-string = spaces - perform show-usage - end-if. - -parse-input. - move 1 to scan-ptr - - perform until scan-ptr > length of argument-string - move spaces to current-token - - unstring argument-string delimited by "," - into current-token with pointer scan-ptr - end-unstring - - if current-token = spaces - continue - end-if - - if function test-numval(function trim(current-token)) <> 0 - perform show-usage - end-if - - add 1 to list-size - if list-size > max-entries - perform show-usage - end-if - - move function numval(current-token) to entry-value(list-size) - end-perform - - if list-size < 2 perform show-usage end-if. - -execute-sort. - move list-size to last-swap-pos - - perform until last-swap-pos <= 1 - set no-swaps to true - move 0 to new-swap-pos - - perform varying i from 1 by 1 until i >= last-swap-pos - if entry-value(i) > entry-value(i + 1) - move entry-value(i) to temp-val - move entry-value(i + 1) to entry-value(i) - move temp-val to entry-value(i + 1) - - set has-swapped to true - move i to new-swap-pos - end-if - end-perform - - if no-swaps - exit perform - end-if - - move new-swap-pos to last-swap-pos - end-perform. - -display-results. - perform varying i from 1 by 1 until i > list-size - if i > 1 - display separator with no advancing - end-if - - move entry-value(i) to display-num - display function trim(display-num) with no advancing - end-perform - display space. - -show-usage. - display - 'Usage: please provide a list of at least two integers ' - 'to sort in the format "1, 2, 3, 4, 5"' - stop run. - -``` - -{% endraw %} - -Bubble Sort in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/commodore-basic/index.md b/docs/projects/bubble-sort/commodore-basic/index.md deleted file mode 100644 index 057c4757a3..0000000000 --- a/docs/projects/bubble-sort/commodore-basic/index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-07 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- bubble-sort -- commodore-basic -title: Bubble Sort in Commodore BASIC -title1: Bubble Sort in -title2: Commodore BASIC ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -20 GOSUB 2000: REM Get array -25 REM Error if invalid, not end of input/value, or less that 2 items -30 IF V = 0 OR C >= 0 OR NA < 2 THEN GOTO 200 -40 GOSUB 3000: REM Perform bubble sort -50 GOSUB 3500: REM Show array -60 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide a list of at least two integers to sort "; -220 PRINT "in the format "; Q$; "1, 2, 3, 4, 5"; Q$ -230 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Bubble sort -3001 REM Inputs: -3002 REM - A contains array to sort -3003 REM - NA contains size of array -3004 REM Outputs: A contains sorted array -3010 I = NA -3020 IF I < 1 THEN GOTO 3130 -3030 NI = 0 -3040 FOR J = 1 TO I - 1 -3050 IF A(J - 1) <= A(J) THEN GOTO 3100 -3060 T = A(J) -3070 A(J) = A(J - 1) -3080 A(J - 1) = T -3090 NI = J -3100 NEXT J -3110 I = NI -3120 GOTO 3020 -3130 RETURN -3500 REM Display array -3501 REM A contains array -3502 REM NA contains size of array -3510 IF NA < 1 THEN GOTO 3590 -3520 FOR I = 0 TO NA - 1 -3530 S$ = STR$(A(I)) -3540 IF A(I) >= 0 THEN S$ = MID$(S$, 2): REM strip leading space -3550 PRINT S$; -3560 IF I < (NA - 1) THEN PRINT ", "; -3570 NEXT I -3580 PRINT -3590 RETURN - -``` - -{% endraw %} - -Bubble Sort in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/dart/index.md b/docs/projects/bubble-sort/dart/index.md deleted file mode 100644 index b254c6e4d7..0000000000 --- a/docs/projects/bubble-sort/dart/index.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -authors: -- Paddy -date: 2019-10-18 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2019-10-18 -layout: default -tags: -- bubble-sort -- dart -title: Bubble Sort in Dart -title1: Bubble Sort -title2: in Dart ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -import 'dart:io'; - -main(List args) { - try { - List numbersList = parseInput(args.join()); - if (numbersList.length <= 1) exitWithError(); - print(bubbleSort(numbersList)); - } catch (e) { - exitWithError(); - } -} - -String bubbleSort(List numbersList) { - bool pairSwapped = true; - int listLength = numbersList.length; - - while (pairSwapped) { - pairSwapped = false; - - for (int position = 0; position < listLength - 1; position++) { - if (numbersList[position] > numbersList[position + 1]) { - numbersList = swapPair(numbersList, position, (position + 1)); - pairSwapped = true; - } - } - } - - return formatOutput(numbersList); -} - -List swapPair( - List numbersList, int currentPosition, int nextPosition) { - double currentValue = numbersList[currentPosition]; - - numbersList[currentPosition] = numbersList[nextPosition]; - numbersList[nextPosition] = currentValue; - - return numbersList; -} - -String formatOutput(List numbersList) { - List output = []; - - numbersList.forEach((number) { - output.add((number * 10) % 10 != 0 ? "$number" : "${number.toInt()}"); - }); - - return output.join(", "); -} - -List parseInput(String input) { - List parsedList = []; - - for (String item in input.replaceAll(" ", "").split(",")) { - parsedList.add(double.parse(item)); - } - - return parsedList; -} - -exitWithError() { - print( - 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - exit(1); -} - -``` - -{% endraw %} - -Bubble Sort in [Dart](/languages/dart) was written by: - -- Paddy - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/elixir/index.md b/docs/projects/bubble-sort/elixir/index.md deleted file mode 100644 index ec2a96698a..0000000000 --- a/docs/projects/bubble-sort/elixir/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Sree Siva Sandeep Palaparthi -date: 2019-10-03 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2019-10-16 -layout: default -tags: -- bubble-sort -- elixir -title: Bubble Sort in Elixir -title1: Bubble Sort -title2: in Elixir ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Elixir](/languages/elixir) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elixir -defmodule Bubble do - @doc """ - Sort the giveen input using bubble sort - """ - def main(args) do - cond do - length(args) != 1 - or List.first(args) == "" - or List.first(args) |> String.split(",") |> length < 2 -> - IO.puts("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - true -> - input = List.first(args) - |> String.split(",") - |> Enum.map(&String.trim/1) - |> Enum.map(&String.to_integer/1) - sorted_list = pass(input, []) - IO.puts(Enum.join(sorted_list, ", ")) - end - end - - @doc """ - Handle each pass, return the list when there are no more changes to the list - """ - def pass(new_list, old_list) when new_list == old_list, do: new_list - - def pass(new_list, old_list) when new_list != old_list do - passed_list = sort(new_list, []) - pass(passed_list, new_list) - end - - @doc """ - Add the smaller element to accumulator, recursively call sort until all elements are added to accumulator - """ - def sort([], acc), do: acc - - def sort([head, tail], acc) do - if head > tail, do: sort([], acc ++ [tail, head]), else: sort([], acc ++ [head, tail]) - end - - def sort([head | [head2 | tail]], acc) do - if head > head2, do: sort([head | tail], acc ++ [head2]), else: sort([head2 | tail], acc ++ [head]) - end -end - -Bubble.main(System.argv()) - -``` - -{% endraw %} - -Bubble Sort in [Elixir](/languages/elixir) was written by: - -- Jeremy Grifski -- Sree Siva Sandeep Palaparthi - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/erlang/index.md b/docs/projects/bubble-sort/erlang/index.md deleted file mode 100644 index d2f1baa7e5..0000000000 --- a/docs/projects/bubble-sort/erlang/index.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -authors: -- Jacky Hui -- rzuckerm -date: 2019-10-03 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2023-11-21 -layout: default -tags: -- bubble-sort -- erlang -title: Bubble Sort in Erlang -title1: Bubble Sort -title2: in Erlang ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Erlang](/languages/erlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```erlang --module(bubble_sort). --export([main/1]). - -%% Run with: escript bubble_sort.erl - -usage() -> - io:format("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"~n"), - halt(). - -convert_list_to_integers(Str) -> - Values = string:tokens(Str, ","), - NumCommas = count_commas(Str), - NumValues = length(Values), - if - (NumCommas + 1) == NumValues -> - convert_values(Values); - true -> - {error, []} - end. - -count_commas([]) -> - 0; -count_commas([$, | Rest]) -> - 1 + count_commas(Rest); -count_commas([_ | Rest]) -> - count_commas(Rest). - -convert_values([]) -> - {ok, []}; -convert_values([ValueStr | Rest]) -> - case convert_to_integer(ValueStr) of - {ok, Value} -> - case convert_values(Rest) of - {ok, RestValues} -> - {ok, [Value | RestValues]}; - _ -> - {error, []} - end; - _ -> - {error, []} - end. - -convert_to_integer(Str) -> - Result = catch string:to_integer(string:strip(Str)), - case Result of - {Int, Rest} when Rest == "" -> - {ok, Int}; - _ -> - {error, 0} - end. - -bubble_sort(List) -> bubble_sort(List, [], false). - -bubble_sort([A, B | T], Acc, _) when A > B -> - bubble_sort([A | T], [B | Acc], true); -bubble_sort([A, B | T], Acc, Tainted) -> - bubble_sort([B | T], [A | Acc], Tainted); -bubble_sort([A | T], Acc, Tainted) -> - bubble_sort(T, [A | Acc], Tainted); -bubble_sort([], Acc, true) -> - bubble_sort(lists:reverse(Acc)); -bubble_sort([], Acc, false) -> - lists:reverse(Acc). - - -handle_output([Num]) -> - io:format("~p~n", [Num]); -handle_output([Num|NumList]) -> - io:format("~p, ", [Num]), - handle_output(NumList). - -main(Args) -> - if - length(Args) < 1 -> - usage(); - true -> - ok - end, - - StrValue = lists:nth(1, Args), - Values = case convert_list_to_integers(StrValue) of - {ok, Result} -> - Result; - _ -> - usage() - end, - - if - length(Values) < 2 -> - usage(); - true -> - ok - end, - - SortedValues = bubble_sort(Values), - handle_output(SortedValues). - -``` - -{% endraw %} - -Bubble Sort in [Erlang](/languages/erlang) was written by: - -- Jacky Hui -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/euphoria/index.md b/docs/projects/bubble-sort/euphoria/index.md deleted file mode 100644 index 803289a54c..0000000000 --- a/docs/projects/bubble-sort/euphoria/index.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2023-02-27 -layout: default -tags: -- bubble-sort -- euphoria -title: Bubble Sort in Euphoria -title1: Bubble Sort -title2: in Euphoria ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"\n" - ) - abort(0) -end procedure - -procedure show_list_values(sequence values) - if length(values) > 0 - then - sequence format = repeat_pattern("%d, ", length(values)) - sequence s = sprintf(format[1..$-2], values) - printf(STDOUT, "%s\n", {s}) - end if -end procedure - -function bubble_sort(sequence values) - -- Source: https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort - - integer n = length(values) - integer new_n - integer temp - loop - do - new_n = 1 - for i = 2 to n - do - if values[i - 1] > values[i] - then - temp = values[i - 1] - values[i - 1] = values[i] - values[i] = temp - new_n = i - end if - end for - - n = new_n - until n <= 2 - end loop - - return values -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int_list(argv[4]) -sequence values = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] or length(values) < 2 -then - usage() -end if - --- Do bubble sort and show results -values = bubble_sort(values) -show_list_values(values) - -``` - -{% endraw %} - -Bubble Sort in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/f-sharp/index.md b/docs/projects/bubble-sort/f-sharp/index.md deleted file mode 100644 index 963cabf29c..0000000000 --- a/docs/projects/bubble-sort/f-sharp/index.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-06 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-04-06 -layout: default -tags: -- bubble-sort -- f-sharp -title: Bubble Sort in F# -title1: Bubble -title2: Sort in F# ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - - -module BubbleSort = - let private sort (arr: int array) = - let result = Array.copy arr - let mutable lastUnsorted = result.Length - 1 - let mutable swapped = true - - while swapped && lastUnsorted > 0 do - swapped <- false - - for i = 0 to lastUnsorted - 1 do - if result.[i] > result.[i + 1] then - let tmp = result.[i] - result.[i] <- result.[i + 1] - result.[i + 1] <- tmp - swapped <- true - - lastUnsorted <- lastUnsorted - 1 - - result - - let run (numbers: int array) = - numbers |> sort |> Array.map string |> String.concat ", " |> Ok - - -module Helpers = - let private (|IntList|_|) (s: string) = - if String.IsNullOrWhiteSpace(s) then - None - else - let parts = s.Split([| ',' |], StringSplitOptions.RemoveEmptyEntries) - let len = parts.Length - - if len < 2 then - None - else - let numbers = Array.zeroCreate len - let mutable ok = true - - for i = 0 to len - 1 do - match Int32.TryParse(parts.[i].Trim()) with - | true, n -> numbers.[i] <- n - | _ -> ok <- false - - if ok then Some numbers else None - - let parseArgs argv = - match argv with - | [| IntList numbers |] -> Ok numbers - | _ -> Error "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.bind BubbleSort.run |> Helpers.handleResult - -``` - -{% endraw %} - -Bubble Sort in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/fortran/index.md b/docs/projects/bubble-sort/fortran/index.md deleted file mode 100644 index 48a8fefce0..0000000000 --- a/docs/projects/bubble-sort/fortran/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- leoraggy -date: 2025-11-05 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2025-11-05 -layout: default -tags: -- bubble-sort -- fortran -title: Bubble Sort in Fortran -title1: Bubble Sort -title2: in Fortran ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program bubblesort - implicit none - character(len=256) input1 - character(len=256) output - character(len=10) :: integer_number - integer, allocatable :: numbers(:) - integer :: i - - if(command_argument_count() /= 1) call usage() - call get_command_argument(1, input1) - if(input1 == "") call usage() - call convert_to_array(input1, numbers) - - if(size(numbers) == 1) call usage() - - call bubble_sort(numbers) - - output = "" - do i = 1, size(numbers) - write(integer_number, '(I0)') numbers(i) - if(len_trim(output) == 0) then - output = trim(integer_number) - else - output = trim(output) // ", " // trim(integer_number) - end if - end do - print '(A)', trim(output) - - -contains - subroutine usage() - write(*,'(a)') 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - stop - end subroutine usage - - subroutine convert_to_array(input1, numbers) - implicit none - character(len=*), intent(in) :: input1 - integer, allocatable, intent(out) :: numbers(:) - integer :: i, length, pos, io_status - - length = 1 - do i = 1, len_trim(input1) - if (input1(i:i) == ',') length = length + 1 - end do - - allocate(numbers(length)) - - pos = 1 - do i = 1, length - read(input1(pos:), *, iostat=io_status) numbers(i) - if (io_status /= 0) call usage() - pos = index(input1(pos:), ',') + pos - end do - end subroutine convert_to_array - - subroutine bubble_sort(numbers) - implicit none - integer, intent(inout) :: numbers(:) - integer :: i, j, temp - - do i = 1, size(numbers) - do j = 1, size(numbers) - i - if(numbers(j) > numbers(j+1)) then - temp = numbers(j) - numbers(j) = numbers(j+1) - numbers(j+1) = temp - end if - end do - end do - end subroutine bubble_sort -end program bubblesort -``` - -{% endraw %} - -Bubble Sort in [Fortran](/languages/fortran) was written by: - -- leoraggy - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/go/index.md b/docs/projects/bubble-sort/go/index.md deleted file mode 100644 index 959c66e1af..0000000000 --- a/docs/projects/bubble-sort/go/index.md +++ /dev/null @@ -1,262 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -- rzuckerm -- Thomas Braccia -date: 2019-03-05 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- bubble-sort -- go -title: Bubble Sort in Go -title1: Bubble -title2: Sort in Go ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "encoding/json" - "fmt" - "os" - "regexp" - "strconv" - "strings" -) - -func bubbleSort(list []int) []int { - swapped := true - for swapped { - swapped = false - for i := 0; i < len(list)-1; i++ { - if list[i] > list[i+1] { - n := list[i] - list[i] = list[i+1] - list[i+1] = n - swapped = true - } - } - } - return list -} - -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - if len(list) < 2 { - exitWithError() - } - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} - -func sliceIntToString(list []int) (out string) { - bytes, _ := json.Marshal(list) - out = strings.Replace(string(bytes), ",", ", ", -1) - out = strings.Trim(out, "[]") - return -} - -func exitWithError() { - fmt.Println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - nums := strToSliceInt(os.Args[1]) - nums = bubbleSort(nums) - fmt.Println(sliceIntToString(nums)) -} - -``` - -{% endraw %} - -Bubble Sort in [Go](/languages/go) was written by: - -- Parker Johansen - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Thomas Braccia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -At this point, let's dig into the code a bit. The following sections break -down the Bubble Sort in Go functionality. - -### The Main Function - -Breaking down this solution bottom up, - -```go -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - nums := strToSliceInt(os.Args[1]) - nums = bubbleSort(nums) - fmt.Println(sliceIntToString(nums)) -} -``` -This is the `main` function of this file. It parses the form `Args`, assures that there is enough elements for it to be sorted, the converts the string to integers, then calls our bubble sort function, and finally prints the results. -It also deals with any errors raised. - -### Transform Input Parameters - -```go -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - if len(list) < 2 { - exitWithError() - } - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} -``` - -This function takes a string like `"2, 1, 10, 5, 3"`, and turns into a list of numbers. -First we need to convert our string into a -list `Split(strList, -1)` which is a list of strings split by comma (,). So our -original input string becomes `["2", " 1", " 10", " 5", " 3"]`. -Then for each element in the list `for _, num := ...` , we do something to it. - -In this example we convert it into a decimal integer, `strconv.Atoi(num)`. After that each of the newly converted integers are converted added to the new list `nums`. - -### Transform Output Result - -```go -func sliceIntToString(list []int) (out string) { - bytes, _ := json.Marshal(list) - out = strings.Replace(string(bytes), ",", ", ", -1) - out = strings.Trim(out, "[]") - return -} -``` - -This function takes a list of integers like `[2, 1, 10, 5, 3]`, and turns into a string. -First we need to convert our list of integers into a -string `bytes, _ := json.Marshal(list)`. So our -original input string becomes `"[2,1,10,5,3]"`. -Then we replace the commas with commas and a space `"[2, 1, 10, 5, 3]"`. Finally, we remove the square brackets before returning the string `out = strings.Trim(out, "[]")`. - - -### Throw Errors - -```go -func exitWithError() { - fmt.Println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - os.Exit(1) -} -``` - -This function prints a message and then exits the script with an error, `os.Exit(1)`. -If any non-zero value is returned then the program didn't complete properly. -This function is called if the user input isn't correct. - -### Bubble Sort - -```go -func bubbleSort(list []int) []int { - swapped := true - for swapped { - swapped = false - for i := 0; i < len(list)-1; i++ { - if list[i] > list[i+1] { - n := list[i] - list[i] = list[i+1] - list[i+1] = n - swapped = true - } - } - } - return list -} -``` - -Finally we're at the real meat and potatoes of the script. This function takes an unsorted integer -list and returns a sorted list, using the bubble sort algorithm. This function `bubbleSort` has two nested for loops inside of it. The `for swapped` loop will run as long as the variable gets swapped in each run of the loop. The `for` loop nested inside will run from the first element in the list (`i=0`) to the last minus one (`len(list)-1`). As it runs through it compares every element to the one after it and if it is larger it swaps them - -```go -n := list[i] -list[i] = list[i+1] -list[i+1] = n -``` - -After that it marks `swapped` as true to notify the outer loop it should keep running. If `swapped` was not changed to `true` the list would stop there because it checked every element and determined none of them needed to be moved. - -For example, if `[3, 2, 5, 1]` is the input: - -* First we compare 3 and 2 -* 3 is greater than 2 -* Store 3 to a temporary variable: `n := list[i]` -* Places 2 where 3 was: `list[i] = list[i+1]` -* Places 3 where 2 was: `list[i+1] = n` - -* Next we compare 3 and 5 -* Nothing happens because 5 is greater than 3. - -* First we compare 5, 1 -* 5 is greater than 1 -* Store 5 to a temporary variable: `n := list[i]` -* Places 1 where 5 was: `list[i] = list[i+1]` -* Places 5 where 1 was: `list[i+1] = n` - -At this point, `list` is `[2, 3, 1, 5]`. The process repeats starting at the beginning of the list until there are no more items to swap: - -* `[2, 3, 1, 5]` becomes `[2, 1, 3, 5]` -* `[2, 1, 3, 5]` becomes `[1, 2, 3, 5]`, and we're done - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Bubble Sort in Go](https://github.com/TheRenegadeCoder/sample-programs/blob/master/archive/g/go/bubble-sort.go). -After that, we should make sure we have the latest Go interpreter. -From there, we can run the following command in the terminal: - -`go run bubble-sort.go "3, 2, 10, 6, 1, 7"` - -Alternatively, we can copy the solution into an online Go interpreter and hit run. diff --git a/docs/projects/bubble-sort/haskell/index.md b/docs/projects/bubble-sort/haskell/index.md deleted file mode 100644 index f4ef857a63..0000000000 --- a/docs/projects/bubble-sort/haskell/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-12-02 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2019-03-26 -layout: default -tags: -- bubble-sort -- haskell -title: Bubble Sort in Haskell -title1: Bubble Sort -title2: in Haskell ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Text.Read -import System.Environment -import System.Exit (exitWith, ExitCode(ExitFailure)) -import Data.List (intercalate) - - -bubble :: Ord a => [a] -> [a] -bubble xs = foldl (\acc _ -> pass acc) xs xs - where pass [x] = [x] - pass (x1:x2:xs) - | x1 > x2 = x2:(pass (x1:xs)) - | otherwise = x1:(pass (x2:xs)) - - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - --- Ensure that a list contains at least two elements -verifyListLength :: Ord a => [a] -> Maybe [a] -verifyListLength [] = Nothing -verifyListLength [x] = Nothing -verifyListLength (x:xs) = Just (x:xs) - -listToString :: [Int] -> String -listToString = intercalate ", " . map show - - -main :: IO () -main = do - args <- getArgs - let xs = headMaybe args >>= stringToListMaybe >>= verifyListLength - case xs of - Nothing -> do - putStrLn "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exitWith $ ExitFailure 1 - Just xs -> putStrLn $ listToString $ bubble xs - - -``` - -{% endraw %} - -Bubble Sort in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/index.md b/docs/projects/bubble-sort/index.md deleted file mode 100644 index 587ff4ccb4..0000000000 --- a/docs/projects/bubble-sort/index.md +++ /dev/null @@ -1,211 +0,0 @@ ---- -date: 2018-12-02 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- bubble-sort -title: Bubble Sort -title1: Bubble -title2: Sort ---- - - - -Welcome to the Bubble Sort page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Bubble sort is a sorting algorithm that repeatedly cycles through a list of elements -and swaps adjacent elements if they are not in order. It works as follows: - -1. Identify the next two adjacent elements in the list (start with the 1st and 2nd, then 2nd and 3rd, 3rd and 4th, and so on) -2. If the elements are not in order swap them. -3. If the end of this list has not been reached, repeat steps 1-3 again -4. If any elements were swapped in the above pass, repeat steps 1-4 again - -### Performance - -The performance of sorting algorithms is generally defined in "Big O notation". -If you are not familiar with such notations, please refer to the relevant -article by [Rob Bell][1] or the [Wikipedia][2] entry listed in further readings below. - -| Cases | Big O Notatation | -| ------------ | ---------------- | -| Best case | O(n) | -| Average case | O(n2) | -| Worst case | O(n2) | - -Bubble sort is generally not an efficient sorting algorithm; however, it does have one advantage. -When the elements are already sorted, bubble sort will only pass throught the list once; whereas, -most other algorithms will still perform their complete sorting process. - -### Example: "4, 5, 3, 1, 2" - -In the example below, "pass" refers to one pass through the list (steps 1-4 one time). -Each row in the pass shows a single comparison (steps 1-2 one time). -The elements in __bold__ on each line are the two being compared. -If the row is labeled "swap," a swap will occur after the comparison. - -__Pass 1__ -- __4__ __5__ 3 1 2 -- 4 __5__ __3__ 1 2 -> swap -- 4 3 __5__ __1__ 2 -> swap -- 4 3 1 __5__ __2__ -> swap - -__Pass 2__ -- __4__ __3__ 1 2 5 -> swap -- 3 __4__ __1__ 2 5 -> swap -- 3 1 __4__ __2__ 5 -> swap -- 3 1 2 __4__ __5__ - -__Pass 3__ -- __3__ __1__ 2 4 5 -> swap -- 1 __3__ __2__ 4 5 -> swap -- 1 2 __3__ __4__ 5 -- 1 2 3 __4__ __5__ - -__Pass 4__ -- __1__ __2__ 3 4 5 -- 1 __2__ __3__ 4 5 -- 1 2 __3__ __4__ 5 -- 1 2 3 __4__ __5__ - -Note that although the elements were sorted at the end of pass 3, -the algorithm needs an additional pass without any swapping in order to know that the elements are sorted. - -[1]: https://robbell.io/2009/06/a-beginners-guide-to-big-o-notation -[2]: https://en.wikipedia.org/wiki/Big_O_notation - - -## Requirements - -Write a sample program that takes a list of numbers in the format "4, 5, 3, 1, 2". -It should then sort the numbers and output them: - -```console -$ ./bubble-sort.lang "4, 5, 3, 1, 2" -1, 2, 3, 4, 5 -``` - -The solution should handle duplicate elements - -```console -$ ./bubble-sort.lang "4, 5, 3, 1, 4, 2" -1, 2, 3, 4, 4, 5 -``` - -In addition, there should be some error handling for situations where the user -doesn't supply correct input. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Bubble Sort. -In order to keep things simple, we split up the testing as follows: - -- Bubble Sort Valid Tests -- Bubble Sort Invalid Tests - -### Bubble Sort Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input | "4, 5, 3, 1, 2" | "1, 2, 3, 4, 5" | -| Sample Input: With Duplicate | "4, 5, 3, 1, 4, 2" | "1, 2, 3, 4, 4, 5" | -| Sample Input: Already Sorted | "1, 2, 3, 4, 5" | "1, 2, 3, 4, 5" | -| Sample Input: Reverse Sorted | "9, 8, 7, 6, 5, 4, 3, 2, 1" | "1, 2, 3, 4, 5, 6, 7, 8, 9" | - -### Bubble Sort Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A List | "1" | -| Invalid Input: Wrong Format | "4 5 3" | - -All of these tests should output the following: - -``` -Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -``` - - -## Articles - -There are 40 articles: - -- [Bubble Sort in ALGOL 60](/projects/bubble-sort/algol60) -- [Bubble Sort in ALGOL 68](/projects/bubble-sort/algol68) -- [Bubble Sort in AWK](/projects/bubble-sort/awk) -- [Bubble Sort in Ada](/projects/bubble-sort/ada) -- [Bubble Sort in Bash](/projects/bubble-sort/bash) -- [Bubble Sort in Beef](/projects/bubble-sort/beef) -- [Bubble Sort in C](/projects/bubble-sort/c) -- [Bubble Sort in C#](/projects/bubble-sort/c-sharp) -- [Bubble Sort in C++](/projects/bubble-sort/c-plus-plus) -- [Bubble Sort in COBOL](/projects/bubble-sort/cobol) -- [Bubble Sort in Clojure](/projects/bubble-sort/clojure) -- [Bubble Sort in Commodore BASIC](/projects/bubble-sort/commodore-basic) -- [Bubble Sort in Dart](/projects/bubble-sort/dart) -- [Bubble Sort in Elixir](/projects/bubble-sort/elixir) -- [Bubble Sort in Erlang](/projects/bubble-sort/erlang) -- [Bubble Sort in Euphoria](/projects/bubble-sort/euphoria) -- [Bubble Sort in F#](/projects/bubble-sort/f-sharp) -- [Bubble Sort in Fortran](/projects/bubble-sort/fortran) -- [Bubble Sort in Go](/projects/bubble-sort/go) -- [Bubble Sort in Haskell](/projects/bubble-sort/haskell) -- [Bubble Sort in Java](/projects/bubble-sort/java) -- [Bubble Sort in JavaScript](/projects/bubble-sort/javascript) -- [Bubble Sort in Julia](/projects/bubble-sort/julia) -- [Bubble Sort in Kotlin](/projects/bubble-sort/kotlin) -- [Bubble Sort in Lua](/projects/bubble-sort/lua) -- [Bubble Sort in Mathematica](/projects/bubble-sort/mathematica) -- [Bubble Sort in Octave](/projects/bubble-sort/octave) -- [Bubble Sort in PHP](/projects/bubble-sort/php) -- [Bubble Sort in Pascal](/projects/bubble-sort/pascal) -- [Bubble Sort in Perl](/projects/bubble-sort/perl) -- [Bubble Sort in PowerShell](/projects/bubble-sort/powershell) -- [Bubble Sort in Python](/projects/bubble-sort/python) -- [Bubble Sort in Ruby](/projects/bubble-sort/ruby) -- [Bubble Sort in Rust](/projects/bubble-sort/rust) -- [Bubble Sort in Scala](/projects/bubble-sort/scala) -- [Bubble Sort in Swift](/projects/bubble-sort/swift) -- [Bubble Sort in Tcl](/projects/bubble-sort/tcl) -- [Bubble Sort in TypeScript](/projects/bubble-sort/typescript) -- [Bubble Sort in Visual Basic](/projects/bubble-sort/visual-basic) -- [Bubble Sort in m4](/projects/bubble-sort/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/bubble-sort/java/index.md b/docs/projects/bubble-sort/java/index.md deleted file mode 100644 index c15d7c8682..0000000000 --- a/docs/projects/bubble-sort/java/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Tim Lange -date: 2019-10-16 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- bubble-sort -- java -title: Bubble Sort in Java -title1: Bubble Sort -title2: in Java ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.ArrayList; - -public class BubbleSort { - - public static void main(String[] args) { - try { - ArrayList listOfNumbers = new ArrayList<>(); - String[] NumberArray = args[0].split(","); - for (String Number : NumberArray) { - listOfNumbers.add(Integer.parseInt(Number.trim())); - } - if (listOfNumbers.size() >= 2) { - StringBuilder output = new StringBuilder(); - ArrayList SortedList = sort(listOfNumbers); - - for (Integer Number : SortedList) { - if (SortedList.indexOf(Number) == 0) { - output.append(Number); - } else { - output.append(", ").append(Number); - } - } - System.out.println(output); - } else { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } - } catch (Exception e) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } - } - - private static ArrayList sort(ArrayList list) { - int memory; - for (int i = 1; i < list.size(); i++) { - for (int j = 0; j < list.size() - i; j++) { - if (list.get(j) > list.get(j + 1)) { - memory = list.get(j); - list.set(j, list.get(j + 1)); - list.set(j + 1, memory); - } - } - } - return list; - } -} - -``` - -{% endraw %} - -Bubble Sort in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Tim Lange - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/javascript/index.md b/docs/projects/bubble-sort/javascript/index.md deleted file mode 100644 index 7b5bf65fff..0000000000 --- a/docs/projects/bubble-sort/javascript/index.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -authors: -- Zachary Smith -date: 2019-10-12 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2019-10-17 -layout: default -tags: -- bubble-sort -- javascript -title: Bubble Sort in JavaScript -title1: Bubble Sort -title2: in JavaScript ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -/** - * Bubble sort algorithm - * - * @param {Integer array} arr - */ - -function bubblesort(arr) { - let swap; - - // repeat while array is unsorted - do { - swap = false; - - // iterate array - for (let index = 0; index < arr.length - 1; index++) { - // if current item is out of order - if (arr[index] > arr[index + 1]) { - // hotswap the current element with the next element - [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]]; - - // flag that list was unordered in this pass - swap = true; - } - } - - } while (swap); - - return arr; -} - -/** - * Executable function - * - * @param {Command line input} input - */ - -function main(input) { - /** - * If the string matches the format `"[number], [number], (... [number])"`, - * we have a valid input. - */ - const inputValidation = /^"?(\d+,\s*){2,}\d+(,"?|"?)$/gm; - - if (inputValidation.test(input) == true) { - // valid input - let arr; - - /** - * Format string to be bubblesorted. - * - strip all whitespace and quotations - * - split into array at ',' character - * - convert all elements to integers - * - filter out NaN elements (uncaught text characters or empty elements) - */ - arr = input.replace(/(\s|"|'|`)/g, ''); - arr = arr.split(','); - arr = arr.map(function (n) { - return parseInt(n, 10); - }); - arr = arr.filter(n => n); - - // apply bubblesort and output result - arr = bubblesort(arr); - - let str; - - str = arr.toString(); - str = str.replace(/,/g, ', '); - - console.log(str); - } - else { - // invalid input - console.log(usage); - } -} - -// usage text -const usage = `Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"`; - -if (process.argv.length > 2) { - // run the executable function - const input = process.argv[2]; - main(input); -} -else { - console.log(usage); -} - -``` - -{% endraw %} - -Bubble Sort in [JavaScript](/languages/javascript) was written by: - -- Zachary Smith - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/julia/index.md b/docs/projects/bubble-sort/julia/index.md deleted file mode 100644 index b0b7bcc15f..0000000000 --- a/docs/projects/bubble-sort/julia/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- sniklas142 -date: 2020-10-01 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2020-10-01 -layout: default -tags: -- bubble-sort -- julia -title: Bubble Sort in Julia -title1: Bubble Sort -title2: in Julia ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -#!/usr/bin/julia - -function BubbleSort(arr) - l = length(arr) - swapped = true - while swapped - swapped = false - for j = 2:l - if arr[j-1] > arr[j] - tmp = arr[j-1] - arr[j-1] = arr[j] - arr[j] = tmp - swapped = true - end - end - end -end - -function error() - println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") -end - -function HandleInput(inp) - - a = split(inp,",") - a = map(x->split(x," "),a) - a = map(x->last(x),a) - numbers = map(x->parse(Int,x),a) - if length(numbers) == 1 - error() - exit() - end - return numbers - -end - -function PrintOutput(out) - for i = 1:length(out) - print(out[i]) - if i != length(out) - print(", ") - end - end - println() -end - -try - - n = HandleInput(ARGS[1]) - BubbleSort(n) - PrintOutput(n) - -catch e - error() -end - - - -``` - -{% endraw %} - -Bubble Sort in [Julia](/languages/julia) was written by: - -- sniklas142 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/kotlin/index.md b/docs/projects/bubble-sort/kotlin/index.md deleted file mode 100644 index d86d24230d..0000000000 --- a/docs/projects/bubble-sort/kotlin/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Blake.Ke -- Jeremy Grifski -- mikenmo -date: 2020-10-01 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- bubble-sort -- kotlin -title: Bubble Sort in Kotlin -title1: Bubble Sort -title2: in Kotlin ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) -{ - var nums: IntArray - try - { - nums = args[0].split(", ").map{ it.toInt() }.toIntArray() - if (nums.size < 2) { - throw Exception() - } - } - catch(e: Exception) - { - println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - return - } - var swapped:Boolean = false - for(i in 0 until nums.count()-1) - { - swapped = false - for(j in 0 until nums.count()-i-1) - { - if(nums[j]>nums[j+1]) - { - //swap - nums[j] = nums[j+1].also {nums[j+1] = nums[j]} - swapped = true - } - } - if (swapped==false) - { - break - } - } - for(i in 0 until nums.count()) - { - if (i==nums.count()-1) - { - println("${nums[i]}") - return - } - print("${nums[i]}, ") - } -} - -``` - -{% endraw %} - -Bubble Sort in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- Jeremy Grifski -- mikenmo - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/lua/index.md b/docs/projects/bubble-sort/lua/index.md deleted file mode 100644 index 9675e1433c..0000000000 --- a/docs/projects/bubble-sort/lua/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Jeremy Grifski -- jketterer -date: 2019-10-28 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- bubble-sort -- lua -title: Bubble Sort in Lua -title1: Bubble Sort -title2: in Lua ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua --- Initialize table -nums = {} - --- Exit if no list is entered or list is empty -if arg[1] == nil or #arg[1] == 0 then - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - return -end - --- Exit if list has a single entry or is not formatted with commas -if (not string.match(arg[1], " ")) or (not string.match(arg[1], ",")) then - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - return -end - --- Read input list into a table -for i=1, #arg[1] do - char = string.sub(arg[1], i, i) - if tonumber(char) then - table.insert(nums, char) - end -end - --- Loop through entire table -for i=1, #nums do - -- Loop through entire table - for index,value in pairs(nums) do - -- If current number is larger than next number, swap them - if nums[index+1] ~= nil and value > nums[index+1] then - nums[index] = nums[index+1] - nums[index+1] = value - end - end -end - --- Print sorted list -for k,v in pairs(nums) do - io.write(v) - - -- Comma formatting - if nums[k+1] ~= nil then - io.write(', ') - end -end - -io.write("\n") - -``` - -{% endraw %} - -Bubble Sort in [Lua](/languages/lua) was written by: - -- Jeremy Grifski -- jketterer - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/m4/index.md b/docs/projects/bubble-sort/m4/index.md deleted file mode 100644 index 8bdd7aa2c2..0000000000 --- a/docs/projects/bubble-sort/m4/index.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-01 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2025-10-01 -layout: default -tags: -- bubble-sort -- m4 -title: Bubble Sort in m4 -title1: Bubble -title2: Sort in m4 ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl array_swap(var_name, idx1, idx2): -dnl t = var_name[idx1] -dnl var_name[idx1] = var_name[idx2] -dnl var_name[idx] = t -define(`array_swap', -`pushdef(`t', array_get(`$1', `$2'))dnl -array_set(`$1', `$2', array_get(`$1', `$3'))dnl -array_set(`$1', `$3', t)dnl -popdef(`t')'dnl -) - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl show_int_list(varname): -dnl for i = 0 to n-1: -dnl if i > 0: -dnl Output ", " -dnl Output varname[i] -define(`show_int_list', `_show_int_list(`$1', 0)') -define(`_show_int_list', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`ifelse(eval($2 > 0), 1, `, ')dnl -array_get(`$1', $2)`'dnl -_show_int_list(`$1', incr($2))'`'dnl -)'dnl -) - -dnl Reference: https://en.wikipedia.org/wiki/Bubble_sort#Pseudocode_implementation -dnl bubble_sort(varname): -dnl n = varname[length] -dnl do: -dnl swapped = false -dnl for i from 1 to n-1: -dnl if varname[i-1] > varname[i]: -dnl swap(varname, i-1, i) -dnl swapped = true -dnl while swapped -define(`bubble_sort', `ifelse(_bubble_sort_outer(`$1', 1, 0), 1, `bubble_sort(`$1')')') -define(`_bubble_sort_outer', -`ifelse(eval($2 < array_get(`$1', `length')), 0, -`$3', -`ifelse(_bubble_sort_inner(`$1', $2), 1, -`_bubble_sort_outer(`$1', incr($2), 1)', `_bubble_sort_outer(`$1', incr($2), $3)'dnl -)'dnl -)'dnl -) -define(`_bubble_sort_inner', -`ifelse(eval(array_get(`$1', decr($2)) <= array_get(`$1', $2)), 1, -0, `array_swap(`$1', decr($2), $2)1'`'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !parse_int_list(`arr', ARGV1)), 1, `show_usage()')dnl -ifelse(eval(array_get(`arr', `length') < 2), 1, `show_usage()')dnl -bubble_sort(`arr')dnl -show_int_list(`arr') - -``` - -{% endraw %} - -Bubble Sort in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/mathematica/index.md b/docs/projects/bubble-sort/mathematica/index.md deleted file mode 100644 index 6d2591d096..0000000000 --- a/docs/projects/bubble-sort/mathematica/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-19 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2023-01-19 -layout: default -tags: -- bubble-sort -- mathematica -title: Bubble Sort in Mathematica -title1: Bubble Sort in -title2: Mathematica ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual bubble sort operating on Mathematica lists: *) - -(* keep making passes over the list until it stops changing *) -bubbleSort = Function[{l}, - FixedPoint[Function[{l}, - (* pass over a pair of elements in the list *) - Fold[Function[{l, i}, - (* element pair is out of order?*) - If[l[[i]] > l[[i + 1]], - (* swap the two elements *) - Permute[l, Cycles[{{i, i + 1}}]], - l]], - l, (* begin with the list in its original state *) - Range[Length[l] - 1]]],(* over each pair of elements *) - l]]; - -(* The outer function provides the 'user interface': *) - -bubbleSortMain = l \[Function] - Module[{e = - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""}, - Catch[ - StringRiffle[ - bubbleSort@ - (* list must have more than one element *) - If[Length[#] > 1, #, Throw[e]] & @ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments to bubble sort: list of items *) - StringSplit[l, ", "], - {-1} (* at each leaf *)], - ", "]]]; - - -(* Valid Tests *) -Print /@ bubbleSortMain /@ { - "4, 5, 3, 1, 2", - "4, 5, 3, 1, 4, 2", - "1, 2, 3, 4, 5", - "9, 8, 7, 6, 5, 4, 3, 2, 1" - }; - - -(* Invalid Tests *) -bubbleSortMain[""] - -``` - -{% endraw %} - -Bubble Sort in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/octave/index.md b/docs/projects/bubble-sort/octave/index.md deleted file mode 100644 index e73e5bb45e..0000000000 --- a/docs/projects/bubble-sort/octave/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- bubble-sort -- octave -title: Bubble Sort in Octave -title1: Bubble Sort -title2: in Octave ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function bubble_sort() - %input validation - usage = 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - arg_list = argv(); - nargin = length(arg_list); - if nargin == 0 - %if there was no input - disp(usage); - return; - end - - array_string = arg_list{1}; - array_size = sum(array_string == ',') + 1; - if array_size < 2 - disp(usage); - return; - end - - %build array - array = str2num(array_string); - if length(array) ~= array_size || any(mod(array, 1) ~= 0) - disp(usage); - return; - end - - %to keep track of whether any changes have been made on each pass - flag = 1; - - while flag == 1 - flag = 0; - for i = 1:array_size-1 - if array(i) > array(i+1) - temp = array(i+1); - array(i+1) = array(i); - array(i) = temp; - flag = 1; - end - end - end - - %convert to string - result_string = num2str(array); - - %replace space with ', ' - result_string = regexprep(result_string, '\s+', ', '); - disp(result_string); -end - -``` - -{% endraw %} - -Bubble Sort in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/pascal/index.md b/docs/projects/bubble-sort/pascal/index.md deleted file mode 100644 index a84f9b1e76..0000000000 --- a/docs/projects/bubble-sort/pascal/index.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- bubble-sort -- pascal -title: Bubble Sort in Pascal -title1: Bubble Sort -title2: in Pascal ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program BubbleSort; - -{$mode objfpc}{$H+} - -uses - Classes, Generics.Collections, SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: Integer; -begin - if S.Trim.IsEmpty then - ShowUsage; - - Tokens := S.Split([',']); - Result := TIntegerList.Create; - - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; - - if Result.Count < 2 then - begin - Result.Free; - ShowUsage; - end; -end; - -function IsSorted(const A: TIntegerList): Boolean; -var - i: Integer; -begin - for i := 1 to A.Count - 1 do - if A[i] < A[i - 1] then - Exit(False); - Result := True; -end; - -procedure BubbleSort(List: TIntegerList); -var - i, j: Integer; - Swapped: Boolean; - - procedure SwapElements(Index1, Index2: Integer); - var - Temp: Integer; - begin - Temp := List[Index1]; - List[Index1] := List[Index2]; - List[Index2] := Temp; - end; -begin - for i := List.Count - 1 downto 1 do - begin - Swapped := False; - for j := 0 to i - 1 do - if List[j] > List[j + 1] then - begin - SwapElements(j, j + 1); - Swapped := True; - end; - - if not Swapped then - Break; - end; -end; - -function FormatIntegerList(List: TIntegerList): string; -var - i: Integer; -begin - Result := ''; - for i := 0 to List.Count - 1 do - begin - if i > 0 then - Result += ', '; - Result += IntToStr(List[i]); - end; -end; - -var - RawInput: string; - Numbers: TIntegerList; -begin - if ParamCount <> 1 then - ShowUsage; - - RawInput := ParamStr(1); - Numbers := ParseIntegerList(RawInput); - try - if not IsSorted(Numbers) then - BubbleSort(Numbers); - - Writeln(FormatIntegerList(Numbers)); - finally - Numbers.Free; - end; -end. - - -``` - -{% endraw %} - -Bubble Sort in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/perl/index.md b/docs/projects/bubble-sort/perl/index.md deleted file mode 100644 index df668bd28d..0000000000 --- a/docs/projects/bubble-sort/perl/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- SourabhBadhya -- Ștefan-Iulian Alecu -date: 2020-10-02 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- bubble-sort -- perl -title: Bubble Sort in Perl -title1: Bubble Sort -title2: in Perl ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -use feature qw/keyword_any/; -no warnings 'experimental::keyword_any'; - -sub usage { - say 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - exit; -} - -sub parse_list ($s) { - return undef unless defined $s; - - my @vals = split /\s*,\s*/, $s; - - return undef if @vals < 2; - return undef if any { $_ !~ /\A-?\d+\z/ } @vals; - - return [ map 0 + $_, @vals ]; -} - -sub bubble_sort ($a) { - my $n = @$a; - - for my $end ( reverse 1 .. $n - 1 ) { - my $swapped = false; - - for my $i ( 0 .. $end - 1 ) { - next if $a->[$i] <= $a->[ $i + 1 ]; - ( $a->[$i], $a->[ $i + 1 ] ) = ( $a->[ $i + 1 ], $a->[$i] ); - $swapped = true; - } - - last unless $swapped; - } - - return $a; -} - -my ($input) = @ARGV; -my $a = parse_list($input) or usage(); - -bubble_sort($a); -say join ', ', @$a; - -``` - -{% endraw %} - -Bubble Sort in [Perl](/languages/perl) was written by: - -- SourabhBadhya -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/php/index.md b/docs/projects/bubble-sort/php/index.md deleted file mode 100644 index 2a4a7e8f67..0000000000 --- a/docs/projects/bubble-sort/php/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -- Shahab Rahnama -date: 2019-10-04 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- bubble-sort -- php -title: Bubble Sort in PHP -title1: Bubble Sort -title2: in PHP ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -# Source: https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort -function Invoke-BubbleSort([array]$Values) { - $n = $Values.Length - do { - $newN = 0 - for ($i = 1; $i -lt $n; $i++) { - if ($Values[$i - 1] -gt $Values[$i]) { - $Values[$i - 1], $Values[$i] = $Values[$i], $Values[$i - 1] - $newN = $i - } - } - - $n = $newN - } while ($n -gt 1) -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -try { - $values = Parse-IntList $args[0] - if ($values.Length -lt 2) { - Show-Usage - } -} catch { - Show-Usage -} - -Invoke-BubbleSort $values -Write-Output ($values -join ', ') - -``` - -{% endraw %} - -Bubble Sort in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/python/index.md b/docs/projects/bubble-sort/python/index.md deleted file mode 100644 index e27f98e713..0000000000 --- a/docs/projects/bubble-sort/python/index.md +++ /dev/null @@ -1,217 +0,0 @@ ---- -authors: -- Haseeb Majid -- Jeremy Grifski -- Parker Johansen -- rzuckerm -date: 2018-12-04 -featured-image: bubble-sort-in-python.jpg -last-modified: 2023-05-15 -layout: default -tags: -- bubble-sort -- python -title: Bubble Sort in Python -title1: Bubble Sort -title2: in Python ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys -from functools import reduce - - -def bubble_sort(xs): - def pass_list(xs): - if len(xs) <= 1: - return xs - x0 = xs[0] - x1 = xs[1] - if x1 < x0: - del xs[1] - return [x1] + pass_list(xs) - return [x0] + pass_list(xs[1:]) - return reduce(lambda acc, _: pass_list(acc), xs, xs[:]) - - -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] - - -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) - - -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(bubble_sort(xs)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Bubble Sort in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Parker Johansen - -This article was written by: - -- Haseeb Majid -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -At this point, let's dig into the code a bit. The following sections break -down the Bubble Sort in Python functionality. - -### The Main Function - -Breaking down this solution bottom up: - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -This bit of code checks to see if this is the `main` module run. If it is it then calls the `main` -function and passes user input to it. In this case the user input would be a string of numbers -to sort like so: `"2, 1, 10, 5, 3"`. - -```python -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(bubble_sort(xs)) - except (IndexError, ValueError): - exit_with_error() -``` - -This is the `main` function of this file. It parses the input, then calls our bubble sort function -(and prints the results). It also deals with any errors raised. - -### Transform Input Parameters - -```python -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] -``` - -This function takes a string like `"2, 1, 10, 5, 3"`, and turns into a list of numbers. -It does this using a list comprehension, first we need to convert our string into a -list `list_str.split(',')` which is a list of strings split by comma (,). So our -original input string becomes `["2", " 1", " 10", " 5", " 3"]`. -Then for each element in the list `for x in ...` , we do something to it. - -In this example we convert it into a decimal integer, `int(x.strip(" "), 10)`. Then `x.strip(" ")`, -removes any whitespace so `" 1"` becomes `"1"`. Then `int("1", 10)` -converts the string `"1"` into a decimal number in this case `1`. This is done -for every item in the list so our original input of `"2, 1, 10, 5, 3"` becomes `[2, 1, 10, 5, 3]`. - -### Throw Errors - -```python -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) -``` - -This function prints a message and then exits the script with an error, `sys.exit(1)`. -If any non-zero value is returned then the program didn't complete properly. -This function is called if the user input isn't correct. - -### Bubble Sort - -```python -def bubble_sort(xs): - def pass_list(xs): - if len(xs) <= 1: - return xs - x0 = xs[0] - x1 = xs[1] - if x1 < x0: - del xs[1] - return [x1] + pass_list(xs) - return [x0] + pass_list(xs[1:]) - return reduce(lambda acc, _ : pass_list(acc), xs, xs[:]) -``` - -Finally we're at the real meat and potatoes of the script. This function takes an unsorted integer -list and returns a sorted list, using the bubble sort algorithm. This function `bubble_sort` has -another function inside of it `pass_list`, also called a closure. The nested function can access -the variables of the parent function but as read-only, they cannot change the variable values. - -The `pass_list` function does one pass of the list and makes sure it's sorted, it does by deleting -elements from the list if they're sorted and comparing the next two. - -For example, if `[3, 2, 5, 1]` is the input: - -* First we compare 2, 3 -* 2 < 3 -* Delete 2 from the list `del xs[1]` -* Call `pass_list`, `[2] + pass_list(3,5,1)` - -So we combine the output of pass_list with 2. - -Taking a look at the time `pass_list` is called. - -* Compare 3, 5 -* 3 < 5 -* This time we don't delete 3, we then pass every element of the list except the first one (3) `xs[1:]` -* Call `pass_list`, `[3] + pass_list(5,1)`. - -The final bit of the code is what calls `pass_list`, where `acc` parameter is the `xs` list. -The `reduce` function is used to call `pass_list`, multiple times and `xs[:]` is a copy of the -`xs` so when `xs` is changed `xs[:]` is unaffected. The `reduce` function is used to loop -through every element, it (`reduce`) it uses the output of the last iteration as input to -the next one. - -For example: - -* For input `[10, 3, 2, 5, 7]` output is `[3, 2, 5, 7, 10]` -* Then input is `[3, 2, 5, 7, 10]` output is `[2, 3, 5, 7, 10]` -* Then input is `[2, 3, 5, 7, 10]` output is `[2, 3, 5, 7, 10]` -* ... - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Bubble Sort in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/master/archive/p/python/bubble-sort.py). -After that, we should make sure we have the latest Python interpreter. -From there, we can run the following command in the terminal: - -`python bubble-sort.py "3, 2, 10, 6, 1, 7"` - -Alternatively, we can copy the solution into an online Python interpreter and hit run. diff --git a/docs/projects/bubble-sort/ruby/index.md b/docs/projects/bubble-sort/ruby/index.md deleted file mode 100644 index 71cbe35ea9..0000000000 --- a/docs/projects/bubble-sort/ruby/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2019-03-20 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- bubble-sort -- ruby -title: Bubble Sort in Ruby -title1: Bubble Sort -title2: in Ruby ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -class Array - def bubble_sort - arr = dup - n = arr.length - - (n - 1).times do |i| - swapped = false - - (n - i - 1).times do |j| - next unless arr[j] > arr[j + 1] - - arr[j], arr[j + 1] = arr[j + 1], arr[j] - swapped = true - end - - break unless swapped - end - - arr - end -end - -def parse_input - raw = ARGV.first - raise ArgumentError unless raw - - numbers = raw.split(",").map { Integer(it.strip, exception: false) } - raise ArgumentError if numbers.any?(nil) || numbers.length < 2 - - numbers -end - -def usage! - abort %(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5") -end - -begin - numbers = parse_input - puts numbers.bubble_sort.join(", ") -rescue ArgumentError - usage! -end - -``` - -{% endraw %} - -Bubble Sort in [Ruby](/languages/ruby) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/rust/index.md b/docs/projects/bubble-sort/rust/index.md deleted file mode 100644 index 838949a773..0000000000 --- a/docs/projects/bubble-sort/rust/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- Andrew Johnson -- rzuckerm -date: 2020-10-03 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- bubble-sort -- rust -title: Bubble Sort in Rust -title1: Bubble Sort -title2: in Rust ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -fn bubble_sort(arr: &mut Vec) { - let mut swap_occured = true; - - while swap_occured { - swap_occured = false; - - for i in 1..arr.len() { - if arr[i - 1] > arr[i] { - arr.swap(i - 1, i); - swap_occured = true; - } - } - } -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let mut arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if list too small - if arr.len() < 2 { - usage(); - } - - // Perform bubble sort and show results - bubble_sort(&mut arr); - println!("{arr:?}"); -} - -``` - -{% endraw %} - -Bubble Sort in [Rust](/languages/rust) was written by: - -- Andrew Johnson -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/scala/index.md b/docs/projects/bubble-sort/scala/index.md deleted file mode 100644 index 05e00b693e..0000000000 --- a/docs/projects/bubble-sort/scala/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- bubble-sort -- scala -title: Bubble Sort in Scala -title1: Bubble Sort -title2: in Scala ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -import scala.annotation.tailrec -import scala.math.Ordering.Implicits.infixOrderingOps - -object BubbleSort: - - private val usage = - """Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"""" - - def main(args: Array[String]): Unit = - val result = - args.headOption - .flatMap(parse) - .map(bubbleSort) - .map(_.mkString(", ")) - .getOrElse(usage) - - println(result) - - private def parse(input: String): Option[List[Int]] = - val parts = input.split(',').map(_.trim).toList - val nums = parts.flatMap(_.toIntOption) - Option.when(nums.size >= 2 && nums.size == parts.size)(nums) - - private def bubbleSort[T: Ordering](xs: List[T]): List[T] = - @tailrec - def pass(list: List[T], acc: List[T] = Nil, swapped: Boolean = false): (List[T], Boolean) = - list match - case a :: b :: tail if a > b => - pass(a :: tail, b :: acc, true) - case a :: tail => - pass(tail, a :: acc, swapped) - case Nil => - (acc.reverse, swapped) - - @tailrec - def loop(current: List[T]): List[T] = - val (next, swapped) = pass(current) - if swapped then loop(next) - else next - - loop(xs) -``` - -{% endraw %} - -Bubble Sort in [Scala](/languages/scala) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/swift/index.md b/docs/projects/bubble-sort/swift/index.md deleted file mode 100644 index 1240e6504d..0000000000 --- a/docs/projects/bubble-sort/swift/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- bubble-sort -- swift -title: Bubble Sort in Swift -title1: Bubble Sort -title2: in Swift ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseIntegers(from args: [String]) -> [Int]? { - guard args.count == 2 else { return nil } - - let parts = args[1].split(separator: ",", omittingEmptySubsequences: false) - let values = parts.compactMap { Int($0.trimmed) } - - guard values.count == parts.count, - values.count >= 2 - else { - return nil - } - - return values -} - -extension MutableCollection where Self: BidirectionalCollection { - mutating func bubbleSort(by areInIncreasingOrder: (Element, Element) -> Bool) { - guard count > 1 else { return } - - var end = index(before: endIndex) - - while end > startIndex { - var lastSwap = startIndex - var current = startIndex - - while current < end { - let next = index(after: current) - - if areInIncreasingOrder(self[next], self[current]) { - swapAt(current, next) - lastSwap = next - } - - current = next - } - - end = lastSwap - } - } -} - -guard var numbers = parseIntegers(from: CommandLine.arguments) else { - print(usage) - exit(1) -} - -numbers.bubbleSort(by: <) - -print(numbers.map(String.init).joined(separator: ", ")) - -``` - -{% endraw %} - -Bubble Sort in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/tcl/index.md b/docs/projects/bubble-sort/tcl/index.md deleted file mode 100644 index 7dd0e9654c..0000000000 --- a/docs/projects/bubble-sort/tcl/index.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-07 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2025-10-07 -layout: default -tags: -- bubble-sort -- tcl -title: Bubble Sort in Tcl -title1: Bubble Sort -title2: in Tcl ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"} - exit 1 -} - -proc parseIntegerList {s} { - set s [string trim $s] - if {$s eq ""} { - usage - } - - set tokens [split $s ","] - set result {} - - foreach token $tokens { - set t [string trim $token] - if {$t eq ""} { - usage - } - if {[catch {expr {int($t)}} val]} { - usage - } - lappend result $val - } - - if {[llength $result] < 2} { - usage - } - return $result -} - -proc isSorted {lst} { - set len [llength $lst] - if {$len <= 1} { return 1 } - for {set i 1} {$i < $len} {incr i} { - if {[lindex $lst $i] < [lindex $lst [expr {$i - 1}]]} { - return 0 - } - } - return 1 -} - -proc bubbleSort {lstVar} { - upvar 1 $lstVar lst - set n [llength $lst] - for {set i [expr {$n - 1}]} {$i > 0} {incr i -1} { - set swapped 0 - for {set j 0} {$j < $i} {incr j} { - set a [lindex $lst $j] - set b [lindex $lst [expr {$j + 1}]] - if {$a > $b} { - # swap elements - lset lst $j $b - lset lst [expr {$j + 1}] $a - set swapped 1 - } - } - if {!$swapped} { - break - } - } -} - -proc formatList {lst} { - set out "" - set n [llength $lst] - for {set i 0} {$i < $n} {incr i} { - if {$i > 0} { append out ", " } - append out [lindex $lst $i] - } - return $out -} - -if {$argc != 1} { - usage -} - -set raw [lindex $argv 0] -set numbers [parseIntegerList $raw] - -if {![isSorted $numbers]} { - bubbleSort numbers -} - -puts [formatList $numbers] - -``` - -{% endraw %} - -Bubble Sort in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/typescript/index.md b/docs/projects/bubble-sort/typescript/index.md deleted file mode 100644 index bdb5325016..0000000000 --- a/docs/projects/bubble-sort/typescript/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Aaron -date: 2024-10-08 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2024-10-08 -layout: default -tags: -- bubble-sort -- typescript -title: Bubble Sort in TypeScript -title1: Bubble Sort -title2: in TypeScript ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function DisplayErrorMessage() { - console.log( - `Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"`, - ); - process.exit(1); -} - -/** - * Processes user arguments from CLI, displays usages message and exits if arguments are incorrect - * @returns user input argument as a list to be merge sorted - */ -function VerifyUserInput(): number[] { - if (process.argv.length != 3) { - DisplayErrorMessage(); - } - // regex string to match requirements - const regexStr = /^([0-9]+)((, ?)([0-9]+))+$/; - const regex = new RegExp(regexStr); - const user_arg_pos = 2; - const numbers: string = process.argv[user_arg_pos]; - - if (numbers.length == 0 || !numbers.match(regex)) { - DisplayErrorMessage(); - } - // split numbers into array and parse values - return numbers.split(",").map((x) => parseInt(x)); -} - -/** - * Swaps the values of the array at the given positions - * @param array the array with the values to swap - * @param i the index of the first value to swap - * @param j the index of the second value to swap - * @returns 0 to signify that a swap happened - */ -function Swap(array: number[], i: number, j: number): number { - //list deconstruction to swap values - [array[i], array[j]] = [array[j], array[i]]; - return 0; -} - -/** - * Sorts the given array using the Bubble Sort Algorithm - * @param array the array to be sorted - */ -function BubbleSort(array: number[]) { - var end = array.length; - while (end > 1) { - var new_end = 0; - for (var i = 1; i < end; i++) { - if (array[i - 1] > array[i]) { - Swap(array, i - 1, i) - new_end = i - } - } - end = new_end - } -} - -/** start of program */ -const input: number[] = VerifyUserInput(); -BubbleSort(input); -console.log(input.join(", ")); - -``` - -{% endraw %} - -Bubble Sort in [TypeScript](/languages/typescript) was written by: - -- Aaron - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/bubble-sort/visual-basic/index.md b/docs/projects/bubble-sort/visual-basic/index.md deleted file mode 100644 index 2928aa7c3a..0000000000 --- a/docs/projects/bubble-sort/visual-basic/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- rzuckerm -- Thomas Braccia -date: 2020-10-01 -featured-image: bubble-sort-in-every-language.jpg -last-modified: 2023-05-16 -layout: default -tags: -- bubble-sort -- visual-basic -title: Bubble Sort in Visual Basic -title1: Bubble Sort in -title2: Visual Basic ---- - - - -Welcome to the [Bubble Sort](/projects/bubble-sort) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module BubbleSort - Public Sub Main(args As String()) - Try - ' Convert string to array of integers - Dim listOfStringInputs As String() = args(0).Split(",") - Dim n as Integer = UBound(listOfStringInputs) - If n < 2 - Usage() - Exit Sub - End If - - Dim sortArray(n) As Integer - For i As Integer = 0 To n - sortArray(i) = Integer.Parse(listOfStringInputs(i)) - Next i - - ' Sort array - BubbleSort(sortArray) - - ' Display array - Dim first As Boolean = True - For i As Integer = 0 To n - If i <> 0 - System.Console.Write(", ") - End If - - System.Console.Write(sortArray(i)) - Next i - System.Console.WriteLine() - Catch e As FormatException - Usage() - Catch e As IndexOutOfRangeException - Usage() - End Try - End Sub - - Public Sub Usage() - System.Console.WriteLine("Usage: please provide a list of at least two integers to sort in the format ""1, 2, 3, 4, 5""") - End Sub - - Public Sub BubbleSort(ByRef sortArray As Integer()) - Dim holdInt As Integer - Dim n As Integer = UBound(sortArray) - For i As Integer = 0 To n - 1 - For x As Integer = i + 1 To n - If sortArray(x) < sortArray(i) Then - holdInt = sortArray(x) - sortArray(x) = sortArray(i) - sortArray(i) = holdInt - End If - Next x - Next i - End Sub -End Module - -``` - -{% endraw %} - -Bubble Sort in [Visual Basic](/languages/visual-basic) was written by: - -- rzuckerm -- Thomas Braccia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/ada/index.md b/docs/projects/capitalize/ada/index.md deleted file mode 100644 index a17d595e18..0000000000 --- a/docs/projects/capitalize/ada/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-09 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-09 -layout: default -tags: -- ada -- capitalize -title: Capitalize in Ada -title1: Capitalize -title2: in Ada ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Characters.Handling; - -procedure Capitalize is - - use Ada.Characters.Handling; - - function Capitalize (S : String) return String is - Result : String := S; - begin - Result (Result'First) := To_Upper (Result (Result'First)); - return Result; - end Capitalize; - -begin - if Argument_Count /= 1 or else Argument (1)'Length = 0 then - Put_Line ("Usage: please provide a string"); - Set_Exit_Status (Failure); - return; - end if; - - Put_Line (Capitalize (Argument (1))); - -end Capitalize; - -``` - -{% endraw %} - -Capitalize in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/algol60/index.md b/docs/projects/capitalize/algol60/index.md deleted file mode 100644 index 4eb8455bd4..0000000000 --- a/docs/projects/capitalize/algol60/index.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-30 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-04-03 -layout: default -tags: -- algol60 -- capitalize -title: Capitalize in ALGOL 60 -title1: Capitalize -title2: in ALGOL 60 ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please provide a string\n"); - stop - end usage; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - procedure outAsciiChar(ch); - value ch; - integer ch; - begin - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - outchar( - 1, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ) - end outAsciiChar; - - procedure outCharArray(s, len); - value len; - integer array s; - integer len; - begin - integer i; - for i := 1 step 1 until len do outAsciiChar(s[i]) - end outCharArray; - - procedure capitialize(s, len); - value len; - integer array s; - integer len; - begin - if len > 0 then - begin - comment a (97) ... z (122) -> A (65) ... Z (90); - if s[1] >= 97 & s[1] <= 122 then s[1] := s[1] - 32 - end - end capitialize; - - integer argc, len; - integer array s[1:256]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get string as integer array. Exit if empty; - len := inCharArray(s, 256); - if len < 1 then usage; - - comment Capitialize first character and output string as integer array; - capitialize(s, len); - outCharArray(s, len); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Capitalize in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/algol68/index.md b/docs/projects/capitalize/algol68/index.md deleted file mode 100644 index 3ad0e9c07e..0000000000 --- a/docs/projects/capitalize/algol68/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-22 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-02-01 -layout: default -tags: -- algol68 -- capitalize -title: Capitalize in ALGOL 68 -title1: Capitalize -title2: in ALGOL 68 ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC usage = VOID: printf(($gl$, "Usage: please provide a string")); - -PROC capitalize = (STRING s) STRING: -( - # Capitalize first letter if lowercase # - toupper(s[1]) + s[2:] -); - -# Get 1st command-line argument. Exit if empty # -STRING s := argv(4); -IF UPB s = 0 -THEN - usage; - stop -FI; - -# Capitalize string and show it # -s := capitalize(s); -printf(($gl$, s)) - -``` - -{% endraw %} - -Capitalize in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/awk/index.md b/docs/projects/capitalize/awk/index.md deleted file mode 100644 index 1253a1a00e..0000000000 --- a/docs/projects/capitalize/awk/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-06 -featured-image: capitalize-in-every-language.jpg -last-modified: 2025-04-06 -layout: default -tags: -- awk -- capitalize -title: Capitalize in AWK -title1: Capitalize -title2: in AWK ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a string" - exit(1) -} - -function capitalize(s) { - return toupper(substr(s, 1, 1)) substr(s, 2) -} - -BEGIN { - if (ARGC < 2 || !ARGV[1]) { - usage() - } - - print capitalize(ARGV[1]) -} - -``` - -{% endraw %} - -Capitalize in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/bash/index.md b/docs/projects/capitalize/bash/index.md deleted file mode 100644 index 5b7a7dd1bf..0000000000 --- a/docs/projects/capitalize/bash/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Jeremy Grifski -- lohxx -date: 2019-10-08 -featured-image: capitalize-in-every-language.jpg -last-modified: 2019-10-26 -layout: default -tags: -- bash -- capitalize -title: Capitalize in Bash -title1: Capitalize -title2: in Bash ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -if [ -z "$1" ]; then - echo "Usage: please provide a string" - exit 1 -fi - -echo ${1^} - -``` - -{% endraw %} - -Capitalize in [Bash](/languages/bash) was written by: - -- Jeremy Grifski -- lohxx - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/beef/index.md b/docs/projects/capitalize/beef/index.md deleted file mode 100644 index 4f62cc5c0b..0000000000 --- a/docs/projects/capitalize/beef/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-18 -featured-image: capitalize-in-every-language.jpg -last-modified: 2024-01-18 -layout: default -tags: -- beef -- capitalize -title: Capitalize in Beef -title1: Capitalize -title2: in Beef ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace Capitalize; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a string"); - Environment.Exit(0); - } - - public static void Capitalize(StringView str, ref String capitalized) - { - capitalized.Set(scope $"{str[0].ToUpper}{str[1...]}"); - } - - public static int Main(String[] args) - { - if (args.Count < 1 || args[0].Length == 0) - { - Usage(); - } - - String capitalized = scope .(); - Capitalize(args[0], ref capitalized); - Console.WriteLine(capitalized); - return 0; - } -} - -``` - -{% endraw %} - -Capitalize in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/brainfuck/index.md b/docs/projects/capitalize/brainfuck/index.md deleted file mode 100644 index 5d1ed2285d..0000000000 --- a/docs/projects/capitalize/brainfuck/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-21 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-12-21 -layout: default -tags: -- brainfuck -- capitalize -title: Capitalize in Brainfuck -title1: Capitalize -title2: in Brainfuck ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Brainfuck](/languages/brainfuck) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```brainfuck -[ - Source for division algorithm: - https://stackoverflow.com/questions/27905818/divmod-algorithm-in-brainfuck - - Source for error message text: - https://copy.sh/brainfuck/text.html -] -; Mem 0 = 1 (indicate first char) -+ -; Mem 1 = input char; loop while not null ->,[ - ; Copy input char to Mem 2 and 3; setting Mem 1 to 0 - >[-] - >[-] - <<[>+>+<<-] - ; If first char; - <[ - ; Mem 5 = 26; Mem 3 = input char minus 97 ('a'); Mem 4 = 0 (uninitialized) - >>>>>>++++++++++[ ; Mem 6 = 10 - <+++ ; Add 3 to Mem 5 - <<---------- ; Sub 10 from Mem 3 - >>>- ; Dec Mem 6 - ] - <---- ; Sub 4 from Mem 5 - <<+++ ; Add 3 to Mem 3 - ; Mem 3 = junk; Mem 4 = n; Mem 5 = d minus r; Mem 6 = r; Mem 7 = q - ; where: - ; * n = input char minus 97 (numerator) - ; * d = 26 (denominator) - ; * r = n % d (remainder) - ; * q = n / d (quotient) - ; - ; q will be zero if input char is lowercase; not zero otherwise - [->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<] - ; Sub 32 from Mem 2 (copy of input char) to potentially make it uppercase - <<++++[ ; Mem 1 = 4 - >-------- ; Sub 8 from Mem 2 - <- ; Dec Mem 1 - ] - ; If Mem 7 (q) is not zero (not a lowercase char); add 32 to Mem 2 to undo above - ; (restore copy of input char) - >>>>>>[ - <<<<<<++++[ ; Mem 1 = 4 - >++++++++ ; Add 8 to Mem 2 - <- ; Dec Mem 1 - ] - >>>>>>[-] ; Mem 7 = 0 - ] - ; Mem 0 = 0 (indicate not first char) - <<<<<<<[-] - ] - ; Output Mem 32 (copy of input char; uppercased for first char) - >>. - ; Mem 1 = input char - <, -] -; If first char was null; display error message -<[ - [-] - -[--->+<]>. - +[--->+<]>+. - ++[->+++<]>++. - ++++++. - --. - +++[->+++<]>++. - [-->+<]>+++. - [-->+++++++<]>. - ----. - -------. - ----. - --[--->+<]>--. - ++++[->+++<]>. - --[--->+<]>-. - [-->+++++++<]>. - ++. - ---. - +++++++. - [------>+<]>. - -----. - +. - --[--->+<]>-. - [->+++<]>+. - -[->+++<]>. - ---[->++++<]>-. - +. - --. - ---------. - +++++. - -------. - < -] - -``` - -{% endraw %} - -Capitalize in [Brainfuck](/languages/brainfuck) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/c-plus-plus/index.md b/docs/projects/capitalize/c-plus-plus/index.md deleted file mode 100644 index 1b4ebbfcab..0000000000 --- a/docs/projects/capitalize/c-plus-plus/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Ford Smith -- Ștefan-Iulian Alecu -date: 2019-10-09 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- capitalize -title: Capitalize in C++ -title1: Capitalize -title2: in C++ ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please provide a string\n"; - std::exit(1); -} - -int main(int argc, char* argv[]) { - if (argc < 2) usage(); - - std::string_view input{argv[1]}; - if (input.empty()) usage(); - - char head = static_cast( - std::toupper(static_cast(input.front()))); - - std::string_view tail = input.substr(1); - - std::cout << std::format("{}{}\n", head, tail); - return 0; -} -``` - -{% endraw %} - -Capitalize in [C++](/languages/c-plus-plus) was written by: - -- Ford Smith -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/c-sharp/index.md b/docs/projects/capitalize/c-sharp/index.md deleted file mode 100644 index 784b38d1c0..0000000000 --- a/docs/projects/capitalize/c-sharp/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Renato Ramos Nascimento -- Ștefan-Iulian Alecu -date: 2019-10-11 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- capitalize -title: Capitalize in C# -title1: Capitalize -title2: in C# ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [string input, ..] || string.IsNullOrWhiteSpace(input)) -{ - Console.Error.WriteLine("Usage: please provide a string"); - return; -} - -char c = input[0]; - -if (char.IsLower(c)) - input = char.ToUpperInvariant(c) + input[1..]; - -Console.WriteLine(input); -``` - -{% endraw %} - -Capitalize in [C#](/languages/c-sharp) was written by: - -- Jeremy Grifski -- Renato Ramos Nascimento -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/c/index.md b/docs/projects/capitalize/c/index.md deleted file mode 100644 index 9bccf25054..0000000000 --- a/docs/projects/capitalize/c/index.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -authors: -- Jeremy Grifski -- shubhragupta-code -- Softizo -- Ștefan-Iulian Alecu -date: 2019-10-09 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-15 -layout: default -tags: -- c -- capitalize -title: Capitalize in C -title1: Capitalize -title2: in C ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -char *captialize(char str[]) -{ - for (int i = 0; i < strlen(str); i++) - if (i == 0) - str[i] = toupper(str[i]); - else - continue; - return str; -} - -int main(int argc, char *argv[]) -{ - if (argc == 2 && strlen(argv[1]) != 0) - printf("%s\n", captialize(argv[1])); - else if (argc > 2) - printf("Use quotes around multiple strings.\n"); - else - printf("Usage: please provide a string\n"); - - return 0; -} - -``` - -{% endraw %} - -Capitalize in [C](/languages/c) was written by: - -- Jeremy Grifski -- Softizo -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- shubhragupta-code -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - - -### Header files - -```c -#include -#include -#include -``` - -These lines import standard libraries so we can use built-in functions. - -- `` provides character functions like [`toupper()`][2]. -- `` provides input/output functions like [`printf()`][3]. -- `` provides string utilities like [`strlen()`][1]. - -### Main function - -```c -int main(int argc, char *argv[]) -``` - -This is where every C program starts. Here, `argc` represents the number of -command-line arguments, and `argv` represents an array of strings containing -those arguments. So, if we run: - -```console -./capitalize "hello" -``` -then: -- `argc = 2` -- `argv[0] = "./capitalize"` -- `argv[1] = "hello"` - -### Input validation - -```c -if (argc == 2 && strlen(argv[1]) != 0) -``` - -This ensures: - -- exactly one argument is provided -- it is not an empty string - -If the user provides no input, the program prints usage message. If there are -too many arguments, the program warns about quotes, because the user most -likely called the program using `./capitalize hello world` instead of -`./capitalize "hello world"`. - -### Capitalization step - -```c -printf("%s\n", capitalize(argv[1])); -``` - -If input is valid, we call `capitalize()` with the first argument, then print -the result. In the function: - -```c -char *captialize(char str[]) -{ - for (int i = 0; i < strlen(str); i++) - if (i == 0) - str[i] = toupper(str[i]); - else - continue; - return str; -} -``` -we traverse each letter in the string. If `i = 0`, then we capitalize the first -letter of the string using [`toupper`][2], otherwise the string remains the same. - -[1]: https://man7.org/linux/man-pages/man3/strlen.3.html -[2]: https://man7.org/linux/man-pages/man3/toupper.3.html -[3]: https://man7.org/linux/man-pages/man3/printf.3.html - -## How to Run the Solution - -If we want to compile and run the program on a computer, we first need a C -compiler installed. Common choices include GCC, Clang, and Microsoft Visual -C++ (MSVC). - -Once a compiler is available, we can open a terminal in the same directory as -the source file and compile the program. - -For example, using GCC: -```sh -gcc -o capitalize capitalize.c -./capitalize -``` -or using Clang: -```sh -clang -o capitalize capitalize.c -./capitalize -``` -On Windows with the Microsoft compiler: -```sh -cl capitalize.c -capitalize.exe -``` \ No newline at end of file diff --git a/docs/projects/capitalize/clojure/index.md b/docs/projects/capitalize/clojure/index.md deleted file mode 100644 index 39c0fad344..0000000000 --- a/docs/projects/capitalize/clojure/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Jeremy Grifski -- pablocostass -date: 2019-10-10 -featured-image: capitalize-in-every-language.jpg -last-modified: 2019-10-26 -layout: default -tags: -- capitalize -- clojure -title: Capitalize in Clojure -title1: Capitalize -title2: in Clojure ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Clojure](/languages/clojure) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```clojure -(ns capitalize - (:gen-class)) - -(defn- is-valid-input [args] - (and - (not= (count args) 0) - (not= (first args) ""))) - -(defn- print-error [] - (println "Usage: please provide a string")) - -(defn- capitalize [s] - (str - (clojure.string/upper-case - (subs s 0 1)) (subs s 1) - )) - -(defn main [args] - (if (is-valid-input args) - (println (capitalize (first args))) - (print-error) - )) - - -(main *command-line-args*) - -``` - -{% endraw %} - -Capitalize in [Clojure](/languages/clojure) was written by: - -- Jeremy Grifski -- pablocostass - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/cobol/index.md b/docs/projects/capitalize/cobol/index.md deleted file mode 100644 index 6c298223b2..0000000000 --- a/docs/projects/capitalize/cobol/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-30 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- capitalize -- cobol -title: Capitalize in COBOL -title1: Capitalize -title2: in COBOL ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. capitalize. - -data division. -working-storage section. - -01 arg-count pic 9(4) comp. -01 input-text pic x(4096). -01 c pic x. -01 tmp-ord pic 9(4) comp. - -procedure division. - -main. - accept arg-count from argument-number - - if arg-count < 1 - perform show-usage - end-if - - accept input-text from argument-value - - if input-text = spaces - perform show-usage - end-if - - move input-text(1:1) to c - - if c >= "a" and c <= "z" - compute tmp-ord = function ord(c) - 32 - move function char(tmp-ord) to c - move c to input-text(1:1) - end-if - - display function trim(input-text) - goback. - -show-usage. - display "Usage: please provide a string" - stop run. - -``` - -{% endraw %} - -Capitalize in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/coffeescript/index.md b/docs/projects/capitalize/coffeescript/index.md deleted file mode 100644 index 4fd880af1c..0000000000 --- a/docs/projects/capitalize/coffeescript/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Brendan V -date: 2025-10-30 -featured-image: capitalize-in-every-language.jpg -last-modified: 2025-10-30 -layout: default -tags: -- capitalize -- coffeescript -title: Capitalize in CoffeeScript -title1: Capitalize in -title2: CoffeeScript ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -Usage = "Usage: please provide a string" - -capitalize = (arg) -> - charList = [] - for char, i in arg - if i == 0 - charList.push(char.toUpperCase()) - else - charList.push(char) - return charList.join("") - -main = () -> - args = process.argv[2] - if args - capitalize(args) - else - return Usage - -console.log main() -``` - -{% endraw %} - -Capitalize in [CoffeeScript](/languages/coffeescript) was written by: - -- Brendan V - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/commodore-basic/index.md b/docs/projects/capitalize/commodore-basic/index.md deleted file mode 100644 index c14345f476..0000000000 --- a/docs/projects/capitalize/commodore-basic/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-17 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-09-17 -layout: default -tags: -- capitalize -- commodore-basic -title: Capitalize in Commodore BASIC -title1: Capitalize in -title2: Commodore BASIC ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input string -10 GOSUB 1000 -20 IF S$ = "" THEN GOTO 80 -30 R1$ = LEFT$(S$, 1) -40 IF R1$ >= "a" AND R1$ <= "z" THEN R1$ = CHR$(ASC(R1$) - 32) -50 R$ = R1$ + MID$(S$, 2) -60 PRINT R$ -70 END -80 PRINT "Usage: please provide a string" -90 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 13 OR C = 255 THEN RETURN: REM end of value or input -1050 S$ = S$ + A$ -1060 GOTO 1020 - -``` - -{% endraw %} - -Capitalize in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/dart/index.md b/docs/projects/capitalize/dart/index.md deleted file mode 100644 index d281ae44ee..0000000000 --- a/docs/projects/capitalize/dart/index.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Paddy -- rzuckerm -- slashdoom -date: 2019-10-17 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- capitalize -- dart -title: Capitalize in Dart -title1: Capitalize -title2: in Dart ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -import 'dart:io'; - -main(List args) { - - if (args.isEmpty || args[0].isEmpty) { - print("Usage: please provide a string"); - exit(1); - } - - print(capitalize(args[0])); -} - -String capitalize(String input) => - '${input[0].toUpperCase()}${input.substring(1)}'; - -``` - -{% endraw %} - -Capitalize in [Dart](/languages/dart) was written by: - -- Jeremy Grifski -- Paddy - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- slashdoom - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -It's probably worth noting up front that there is a [strings library][1] available that includes a capitalize function with more error checking than we have here. Since it's not one of the Dart built-in libraries, this would need to be installed with `pub get` or `flutter pub get`. It would probably be worthwhile in a larger Dart/Flutter project where the package's additional functions may also be useful. - -The built-in library that we are going to use, `dart:io`, is imported at the top and will give us access to the stdin and stdout properties and the exit function. - -Dart uses the function name `main` as an entry point for the program and since we don't expect any return data from `main` no type has been specified. Within the main function's parameters, you'll see `List args` which will define `args` as a list of strings and fill this list with input from the command line in the form of arguments which in this case are simply strings separated by spaces. - -For example: - -``` -dart capitalize.dart "Hello World" -``` - -...would fill the args list as `[Hello World]`. - -Our first check tests if any data was passed to the script via arguments by checking the isEmpty property of the `args` list. -- If `args` is empty, we print out an error message and use the `dart:io` `exit()` function to exit out of the script with a proper error code. -- Otherwise, we assume that data was entered as an argument and continue on. - -Our next check tests the first string in the args list since this is the only item in the list that we're actually going to process for capitalization. -- If `args[0]` is empty, we print out an error message and use the `dart:io` `exit()` function to exit out of the script with a proper error code. -- Otherwise, we assume we have a good string to process and continue on. - -With this check complete we're ready to proceed and capitalize the string input. Because we want to print out the result we call our `capitalize()` function within the `print()` function. Within capitalize's parameters we pass the `args[0]` list element that we've tested. - -Because our capitalize function is a one line piece of code, we're able to use Dart's shorthand function syntax which uses `"=>"` as a simple way to return the outcome of the one line expression as the value of the function. - -Even though the capitalize expression (`'${input[0].toUpperCase()}${input.substring(1)}';`) is a single line, there's quite a bit going on here so let's break it down a bit. - -The first concept in use here is string interpolation. This lets us access the value of a variable or expression inside of a string using `${expression}`. For example: - -```dart -String x = 'hello'; -String y = 'world'; -print('${x} ${y}!'); // prints "hello world!" -``` - -Next, Dart lets us access the characters in a string by position (starting at position 0) using the variable name followed by the position enclosed in `[]`. So `input[0]` gives us the first character of the input string which is what we need to capitalize. We do this be applying the `toUpperCase` method to that character and return the result with string interpolation as mentioned before. - -Now all we need to do is append the remainder of our original string without the first character. We can do this with the `substring` method. - -```dart -String substring (int startIndex, [int endIndex]) -``` - -Applying substring with a start index of 1 and no end index returns everything expect for the first character since substring, like the `[]` index, starts with the first character being position 0. By again wrapping this with string interpolation we've now returned the full string with the first character capitalized which will get printed from the `main()` function's `print()` statement. - -[1]: https://api.dart.dev/stable/2.19.6/dart-core/String-class.html - - -## How to Run the Solution - -To run the Dart capitalize program, download the dart file from GitHub, install the Dart SDK as described at [dart.dev][2], and run the following from the command line: - -```console -dart capitalize.dart "string to be capitalized" -``` - -Alternatively, you can copy the source code into [DartPad][3], an online Dart interpreter. Just keep in mind that you won't have access to the command line arguments or stdin and stdout using this method so you'll have to populate the args variable in the code instead. For example: - -[2]: https://dart.dev/ -[3]: https://dartpad.dev/ diff --git a/docs/projects/capitalize/elixir/index.md b/docs/projects/capitalize/elixir/index.md deleted file mode 100644 index 66c4f47bee..0000000000 --- a/docs/projects/capitalize/elixir/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Jonas Halstrup -date: 2020-10-06 -featured-image: capitalize-in-every-language.jpg -last-modified: 2020-10-06 -layout: default -tags: -- capitalize -- elixir -title: Capitalize in Elixir -title1: Capitalize -title2: in Elixir ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Elixir](/languages/elixir) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elixir -defmodule Capitalize do - - @doc """ - Capitalize the fitst entry of a list of strings and return the list as a single string. - Return an error-string if the list is empty. - - Three cases of command line arguments: - 1. No argument / empty string -> return error string - 2. Single quoted string -> Assume fist word starts at index 0, capitalize first letter - 3. Multiple strings/words -> capitalize first word - """ - def main([]) do "Usage: please provide a string" end - def main([ "" | []]) do "Usage: please provide a string" end - - def main([ head | [] ]) do - capitalize_word(head) - end - - def main( [head | tail] ) do - [ capitalize_word(head) | tail] |> Enum.join(" ") - end - - defp capitalize_word(word) do - first_letter = String.first(word) - first_letter_up = String.capitalize(first_letter) - String.replace_prefix(word, first_letter, first_letter_up) - end -end - -Capitalize.main(System.argv()) |> IO.puts -``` - -{% endraw %} - -Capitalize in [Elixir](/languages/elixir) was written by: - -- Jonas Halstrup - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/elvish/index.md b/docs/projects/capitalize/elvish/index.md deleted file mode 100644 index fd1dba2c8b..0000000000 --- a/docs/projects/capitalize/elvish/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-18 -featured-image: capitalize-in-every-language.jpg -last-modified: 2025-01-18 -layout: default -tags: -- capitalize -- elvish -title: Capitalize in Elvish -title1: Capitalize -title2: in Elvish ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -use str - -fn die { - echo 'Usage: please provide a string' - exit 1 -} - -if (> 1 (count $args)) { - die -} - -var s = $args[0] - -if (> 1 (count $s)) { - die -} - -echo (str:join '' [(str:to-upper $s[0]) $s[1..]]) - -``` - -{% endraw %} - -Capitalize in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/euphoria/index.md b/docs/projects/capitalize/euphoria/index.md deleted file mode 100644 index 0eb558274e..0000000000 --- a/docs/projects/capitalize/euphoria/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-17 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-02-17 -layout: default -tags: -- capitalize -- euphoria -title: Capitalize in Euphoria -title1: Capitalize -title2: in Euphoria ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/text.e - -procedure usage() - puts(STDOUT, "Usage: please provide a string\n") - abort(0) -end procedure - -function capitalize(sequence s) - return upper(s[1]) & s[2..$] -end function - --- Parse 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Capitalize string and show it -sequence s = argv[4] -s = capitalize(s) -printf(STDOUT, "%s\n", {s}) - -``` - -{% endraw %} - -Capitalize in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/f-sharp/index.md b/docs/projects/capitalize/f-sharp/index.md deleted file mode 100644 index de2a53db3a..0000000000 --- a/docs/projects/capitalize/f-sharp/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-06 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-04-06 -layout: default -tags: -- capitalize -- f-sharp -title: Capitalize in F# -title1: Capitalize -title2: in F# ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Capitalizer = - let private capitalize (input: string) = - let chars = input.ToCharArray() - chars.[0] <- Char.ToUpper chars.[0] - String chars - - let run input = capitalize input |> Ok - -module Helpers = - let private (|NonEmptyString|_|) (s: string) = - if String.IsNullOrWhiteSpace s then None else Some s - - let parseArgs = - function - | [| NonEmptyString input |] -> Ok input - | _ -> Error "Usage: please provide a string" - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.bind Capitalizer.run |> Helpers.handleResult - -``` - -{% endraw %} - -Capitalize in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/fortran/index.md b/docs/projects/capitalize/fortran/index.md deleted file mode 100644 index d84a6ebfc7..0000000000 --- a/docs/projects/capitalize/fortran/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- Ștefan-Iulian Alecu -date: 2020-10-29 -featured-image: capitalize-in-every-language.jpg -last-modified: 2025-10-15 -layout: default -tags: -- capitalize -- fortran -title: Capitalize in Fortran -title1: Capitalize -title2: in Fortran ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program capitalize - implicit none - character(len=100) :: cmd - integer :: argc - - argc = command_argument_count() - if (argc /= 1) call usage() - - call get_command_argument(1, cmd) - cmd = adjustl(trim(cmd)) - if (len_trim(cmd) == 0) call usage() - - cmd(1:1) = upper(cmd(1:1)) - - write(*,*) cmd - -contains - - subroutine usage() - write(*,*) "Usage: please provide a string" - stop - end subroutine - - pure elemental function upper(str) result(string) - character(*), intent(in) :: str - character(len(str)) :: string - integer :: i, iend - integer, parameter :: toupper = iachar('A') - iachar('a') - - iend = len_trim(str) - string = str(:iend) - - do concurrent (i = 1:iend) - select case (str(i:i)) - case ('a':'z') - string(i:i) = achar(iachar(str(i:i)) + toupper) - end select - end do - end function upper - -end program capitalize - -``` - -{% endraw %} - -Capitalize in [Fortran](/languages/fortran) was written by: - -- Mallikarjuna S J -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/gnu-make/index.md b/docs/projects/capitalize/gnu-make/index.md deleted file mode 100644 index 9b56b0c9d0..0000000000 --- a/docs/projects/capitalize/gnu-make/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-05 -featured-image: capitalize-in-every-language.jpg -last-modified: 2025-10-05 -layout: default -tags: -- capitalize -- gnu-make -title: Capitalize in GNU Make -title1: Capitalize -title2: in GNU Make ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -USAGE := Usage: please provide a string - -# Letter constants -LOWERCASE_LETTERS := a b c d e f g h i j k l m n o p q r s t u v w x y z -UPPERCASE_LETTERS := A B C D E F G H I J K L M N O P Q R S T U V W X Y Z -LETTER_INDEXES := 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 - -# Space replacement constants -EMPTY := -SPACE := $(EMPTY) $(EMPTY) -SPACE_REPLACEMENT := « - -# Get rest of words in a list -# Arg 1: The list -# Return: List with first word removed -REST = $(wordlist 2,$(words $(1)),$(1)) - -# Repeatedly apply a function -# Arg 1: Name of function. This function must take two arguments: -# - Function Arg1: Current value -# - Function Arg2: New value -# Arg 2: The list to repeated apply the function to -# Arg 3: Initial value -_REDUCE = $(if $(4),$(call _REDUCE,$(1),$(call $(1),$(2),$(3)),$(firstword $(4)),$(call REST,$(4))),$(call $(1),$(2),$(3))) -REDUCE = $(call _REDUCE,$(1),$(3),$(firstword $(2)),$(call REST,$(2))) - -# Replace spaces in a string with a replacement character to prevent it from being treated -# as a separate word -# Arg 1: The string -# Return: The string with space replaced -REPLACE_SPACE = $(subst $(SPACE),$(SPACE_REPLACEMENT),$(1)) - -# Restore spaces in a string -# Arg 1: The string with space replacements -# Return: The string with space replacements converted to spaces -RESTORE_SPACE = $(subst $(SPACE_REPLACEMENT),$(SPACE),$(1)) - -# Capitalize the first letter of a string -# Arg 1: The string -# Return First letter of string capitalized if it is a lowercase letter. Otherwise, -# string is unchanged -_CAPITALIZE_LETTER = $(patsubst $(word $(2),$(LOWERCASE_LETTERS))%,$(word $(2),$(UPPERCASE_LETTERS))%,$(1)) -CAPITALIZE = $(call RESTORE_SPACE,$(call REDUCE,_CAPITALIZE_LETTER,$(LETTER_INDEXES),$(call REPLACE_SPACE,$(1)))) - -# If arguments, display usage statement -# Else display capitalized string -ifeq (,$(ARGV1)) -$(info $(USAGE)) -else -$(info $(call CAPITALIZE,$(ARGV1))) -endif - -.PHONY: -all: ;@: - -``` - -{% endraw %} - -Capitalize in [GNU Make](/languages/gnu-make) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/go/index.md b/docs/projects/capitalize/go/index.md deleted file mode 100644 index e3c22c46dc..0000000000 --- a/docs/projects/capitalize/go/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Nathaniel Niosco -date: 2019-10-09 -featured-image: capitalize-in-every-language.jpg -last-modified: 2019-10-26 -layout: default -tags: -- capitalize -- go -title: Capitalize in Go -title1: Capitalize -title2: in Go ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strings" -) - -func exitWithError() { - fmt.Println("Usage: please provide a string") - os.Exit(1) -} - -func uppercaseFirst(str string) string { - s := string(str[0]) - u := strings.ToUpper(s) - up := u + str[1:] - return up -} - -func main() { - if len(os.Args) != 2 || len(os.Args[1]) == 0 { - exitWithError() - } - - s := os.Args[1] - up := uppercaseFirst(s) - - fmt.Println(up) -} - -``` - -{% endraw %} - -Capitalize in [Go](/languages/go) was written by: - -- Jeremy Grifski -- Nathaniel Niosco - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/groovy/index.md b/docs/projects/capitalize/groovy/index.md deleted file mode 100644 index e7e5eedb55..0000000000 --- a/docs/projects/capitalize/groovy/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- robin -- rzuckerm -date: 2019-07-01 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-07-25 -layout: default -tags: -- capitalize -- groovy -title: Capitalize in Groovy -title1: Capitalize -title2: in Groovy ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -class Capitalize { - static void main(String... args) { - if(args?.length >= 1 && args[0]?.length() >= 1) { - println args[0]?.capitalize() - } - else { - println "Usage: please provide a string" - } - } -} - -``` - -{% endraw %} - -Capitalize in [Groovy](/languages/groovy) was written by: - -- robin -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/haskell/index.md b/docs/projects/capitalize/haskell/index.md deleted file mode 100644 index d7bc444f0f..0000000000 --- a/docs/projects/capitalize/haskell/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Amanda Eubanks -- Jeremy Grifski -date: 2019-10-13 -featured-image: capitalize-in-every-language.jpg -last-modified: 2019-10-26 -layout: default -tags: -- capitalize -- haskell -title: Capitalize in Haskell -title1: Capitalize -title2: in Haskell ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Data.Char -import System.Environment - -capitalize :: String -> String -capitalize (head:tail) = toUpper head : tail -capitalize [] = [] - -main = do - args <- getArgs - case args of - [inputStr] -> case inputStr of - [] -> putStrLn "Usage: please provide a string" - _ -> putStrLn $ capitalize inputStr - _ -> putStrLn "Usage: please provide a string" - -``` - -{% endraw %} - -Capitalize in [Haskell](/languages/haskell) was written by: - -- Amanda Eubanks -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/index.md b/docs/projects/capitalize/index.md deleted file mode 100644 index 83077dcdce..0000000000 --- a/docs/projects/capitalize/index.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -date: 2019-03-31 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-16 -layout: default -tags: -- capitalize -title: Capitalize -title1: Capitalize -title2: '' ---- - - - -Welcome to the Capitalize page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -This simple program picks a string and return the first letter of it in uppercase. - - -## Requirements - -For this sample program, each solution should return the string with the first letter in uppercase. -For example, the following code should return "Capitalize": - -```console -$ ./capitalize.lang "capitalize" -Capitalize -``` - -Here are some additional examples: - -``` -string -> String -react -> React -java -> Java -car -> Car -a long string term -> A long string term -``` - -In addition, there should be some error handling for situations where the user -doesn't input a string. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Capitalize. -In order to keep things simple, we split up the testing as follows: - -- Capitalize Valid Tests -- Capitalize Invalid Tests - -### Capitalize Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: Lowercase String | "hello" | "Hello" | -| Sample Input: Uppercase String | "Hello" | "Hello" | -| Sample Input: Long String | "hello world" | "Hello world" | -| Sample Input: Mixed Casing | "heLLo World" | "HeLLo World" | -| Sample Input: Symbols | "12345" | "12345" | - -### Capitalize Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | - -All of these tests should output the following: - -``` -Usage: please provide a string -``` - - -## Articles - -There are 49 articles: - -- [Capitalize in ALGOL 60](/projects/capitalize/algol60) -- [Capitalize in ALGOL 68](/projects/capitalize/algol68) -- [Capitalize in AWK](/projects/capitalize/awk) -- [Capitalize in Ada](/projects/capitalize/ada) -- [Capitalize in Bash](/projects/capitalize/bash) -- [Capitalize in Beef](/projects/capitalize/beef) -- [Capitalize in Brainfuck](/projects/capitalize/brainfuck) -- [Capitalize in C](/projects/capitalize/c) -- [Capitalize in C#](/projects/capitalize/c-sharp) -- [Capitalize in C++](/projects/capitalize/c-plus-plus) -- [Capitalize in COBOL](/projects/capitalize/cobol) -- [Capitalize in Clojure](/projects/capitalize/clojure) -- [Capitalize in CoffeeScript](/projects/capitalize/coffeescript) -- [Capitalize in Commodore BASIC](/projects/capitalize/commodore-basic) -- [Capitalize in Dart](/projects/capitalize/dart) -- [Capitalize in Elixir](/projects/capitalize/elixir) -- [Capitalize in Elvish](/projects/capitalize/elvish) -- [Capitalize in Euphoria](/projects/capitalize/euphoria) -- [Capitalize in F#](/projects/capitalize/f-sharp) -- [Capitalize in Fortran](/projects/capitalize/fortran) -- [Capitalize in GNU Make](/projects/capitalize/gnu-make) -- [Capitalize in Go](/projects/capitalize/go) -- [Capitalize in Groovy](/projects/capitalize/groovy) -- [Capitalize in Haskell](/projects/capitalize/haskell) -- [Capitalize in Java](/projects/capitalize/java) -- [Capitalize in JavaScript](/projects/capitalize/javascript) -- [Capitalize in Julia](/projects/capitalize/julia) -- [Capitalize in Kotlin](/projects/capitalize/kotlin) -- [Capitalize in Lisp](/projects/capitalize/lisp) -- [Capitalize in Lua](/projects/capitalize/lua) -- [Capitalize in Mathematica](/projects/capitalize/mathematica) -- [Capitalize in OCaml](/projects/capitalize/ocaml) -- [Capitalize in Objective-C](/projects/capitalize/objective-c) -- [Capitalize in Octave](/projects/capitalize/octave) -- [Capitalize in PHP](/projects/capitalize/php) -- [Capitalize in Pascal](/projects/capitalize/pascal) -- [Capitalize in Perl](/projects/capitalize/perl) -- [Capitalize in PowerShell](/projects/capitalize/powershell) -- [Capitalize in Python](/projects/capitalize/python) -- [Capitalize in R](/projects/capitalize/r) -- [Capitalize in Ruby](/projects/capitalize/ruby) -- [Capitalize in Rust](/projects/capitalize/rust) -- [Capitalize in Scala](/projects/capitalize/scala) -- [Capitalize in Swift](/projects/capitalize/swift) -- [Capitalize in TI-BASIC](/projects/capitalize/ti-basic) -- [Capitalize in Tcl](/projects/capitalize/tcl) -- [Capitalize in TypeScript](/projects/capitalize/typescript) -- [Capitalize in Visual Basic](/projects/capitalize/visual-basic) -- [Capitalize in m4](/projects/capitalize/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/capitalize/java/index.md b/docs/projects/capitalize/java/index.md deleted file mode 100644 index 33d0d51746..0000000000 --- a/docs/projects/capitalize/java/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- dyllew3 -- Jeremy Grifski -date: 2019-10-11 -featured-image: capitalize-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- capitalize -- java -title: Capitalize in Java -title1: Capitalize -title2: in Java ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class Capitalize { - - public static boolean isLetter(char someChar) { - return (someChar >= 'a' && someChar <= 'z') || (someChar >= 'A' && someChar <= 'Z'); - } - - public static boolean isUpperCase(char someChar) { - return (someChar >= 'A' && someChar <= 'Z'); - } - - public static void main(String[] args) { - if (args.length == 0 || args[0].equals("")) { - System.out.println("Usage: please provide a string"); - System.exit(1); - } - String sentence = args[0]; - - char firstChar = sentence.charAt(0); - if (isLetter(firstChar) && !isUpperCase(firstChar)) { - char[] charArray = sentence.toCharArray(); - charArray[0] = Character.toUpperCase(firstChar); - sentence = new String(charArray); - } - System.out.println(sentence); - - } -} - -``` - -{% endraw %} - -Capitalize in [Java](/languages/java) was written by: - -- dyllew3 -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/javascript/index.md b/docs/projects/capitalize/javascript/index.md deleted file mode 100644 index 054d38a3fd..0000000000 --- a/docs/projects/capitalize/javascript/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Daniel Luna -- Jeremy Grifski -date: 2019-03-31 -featured-image: capitalize-in-every-language.jpg -last-modified: 2019-10-26 -layout: default -tags: -- capitalize -- javascript -title: Capitalize in JavaScript -title1: Capitalize in -title2: JavaScript ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -function capitalize(stringToCapitalize) { - return stringToCapitalize[0].toUpperCase() + stringToCapitalize.slice(1); -} - -function main() { - if (process.argv.length == 3 && process.argv[2].length > 0) { - let input = process.argv[2]; - console.log(capitalize(input)); - } else { - console.log("Usage: please provide a string"); - } -} - -main(); - -``` - -{% endraw %} - -Capitalize in [JavaScript](/languages/javascript) was written by: - -- Daniel Luna -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/julia/index.md b/docs/projects/capitalize/julia/index.md deleted file mode 100644 index 3026443646..0000000000 --- a/docs/projects/capitalize/julia/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- smjalageri -date: 2022-10-02 -featured-image: capitalize-in-every-language.jpg -last-modified: 2022-10-02 -layout: default -tags: -- capitalize -- julia -title: Capitalize in Julia -title1: Capitalize -title2: in Julia ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -#!/usr/bin/julia -# Capitalize first character of the input string -# Function to print Error message -function err() - println("Usage: please provide a string") -end -# Function to capitalize the input string -function capitalize(n) - if (length(n) in [0,1]) - err() - else - println(uppercasefirst(n)) - end -end - -try - capitalize(ARGS[1]) -catch e - err() -end - -``` - -{% endraw %} - -Capitalize in [Julia](/languages/julia) was written by: - -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/kotlin/index.md b/docs/projects/capitalize/kotlin/index.md deleted file mode 100644 index 1e5fec5533..0000000000 --- a/docs/projects/capitalize/kotlin/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Blake.Ke -- Saurabh -date: 2019-10-11 -featured-image: capitalize-in-every-language.jpg -last-modified: 2020-10-08 -layout: default -tags: -- capitalize -- kotlin -title: Capitalize in Kotlin -title1: Capitalize -title2: in Kotlin ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) { - if (args.isNullOrEmpty() || args[0].isBlank()) { - println("Usage: please provide a string") - } else { - // Kotlin provides a simple `capitalize()` function in the standard - // library for all String objects - println(args[0].capitalize()) - } -} - -``` - -{% endraw %} - -Capitalize in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- Saurabh - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/lisp/index.md b/docs/projects/capitalize/lisp/index.md deleted file mode 100644 index 8df5fe07fc..0000000000 --- a/docs/projects/capitalize/lisp/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2020-10-09 -featured-image: capitalize-in-every-language.jpg -last-modified: 2020-10-11 -layout: default -tags: -- capitalize -- lisp -title: Capitalize in Lisp -title1: Capitalize -title2: in Lisp ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -;;Taken from the Common Lisp Cookbook Project (strings page) -(defun split-string (string) - (loop for i = 0 then (1+ j) - as j = (position #\Space string :start i) - collect (subseq string i j) - while j)) - -(defun join-string (lst) - (when lst - (concatenate 'string (car lst) " " (join-string (cdr lst))))) - - (defun capitalize (str) - (concatenate 'string - (string-upcase (subseq str 0 1)) (subseq str 1))) - -(defparameter input (split-string (cadr *posix-argv*))) -(cond - ((= (length (car input)) 0) (write-line "Usage: please provide a string")) - (t (write-line (join-string (cons (capitalize (car input)) (cdr input)))))) - -``` - -{% endraw %} - -Capitalize in [Lisp](/languages/lisp) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/lua/index.md b/docs/projects/capitalize/lua/index.md deleted file mode 100644 index 8f19e21d8a..0000000000 --- a/docs/projects/capitalize/lua/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Berry Semexan -- Jeremy Grifski -date: 2019-10-17 -featured-image: capitalize-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- capitalize -- lua -title: Capitalize in Lua -title1: Capitalize -title2: in Lua ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -if (#arg < 1 or arg[1] == '') -then - print('Usage: please provide a string') -else - str = {...} - s = "" - for i,v in pairs(str) do - s = s .. v .. " " - end - s, _ = s:gsub("^%l", string.upper) - print(s) -end - -``` - -{% endraw %} - -Capitalize in [Lua](/languages/lua) was written by: - -- Berry Semexan -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/m4/index.md b/docs/projects/capitalize/m4/index.md deleted file mode 100644 index c03c847e61..0000000000 --- a/docs/projects/capitalize/m4/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-11 -featured-image: capitalize-in-every-language.jpg -last-modified: 2025-08-11 -layout: default -tags: -- capitalize -- m4 -title: Capitalize in m4 -title1: Capitalize -title2: in m4 ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a string -m4exit(`1')') - -dnl capitalize(str) -define(`capitalize', `translit(substr(`$1', 0, 1), `a-z', `A-Z')`'substr(`$1', 1)') -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1), 1, `show_usage()', `capitalize(ARGV1)') - -``` - -{% endraw %} - -Capitalize in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/mathematica/index.md b/docs/projects/capitalize/mathematica/index.md deleted file mode 100644 index 763ddcbb1b..0000000000 --- a/docs/projects/capitalize/mathematica/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-16 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-01-16 -layout: default -tags: -- capitalize -- mathematica -title: Capitalize in Mathematica -title1: Capitalize in -title2: Mathematica ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual capitalization operating on Mathematica strings: *) - -capitalize = StringReplace[ - StartOfString ~~ l : LetterCharacter -> ToUpperCase[l]]; - -(* The outer function provides the 'user interface': *) - -capitalizeMain = s \[Function] - Catch[ - capitalize[ - If[ - StringQ[s] \[And] \[Not] StringMatchQ[s, ""], - s, - Throw["Usage: please provide a string"]]]]; - - -(* Valid Tests *) -Print /@ capitalizeMain /@ { - "hello", - "Hello", - "hello world", - "heLLo World", - "12345" - }; - - -(* Invalid Tests *) -capitalizeMain[""] - -``` - -{% endraw %} - -Capitalize in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/objective-c/index.md b/docs/projects/capitalize/objective-c/index.md deleted file mode 100644 index cd0eca96c4..0000000000 --- a/docs/projects/capitalize/objective-c/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Cristiano Lopes -- rzuckerm -- Ștefan-Iulian Alecu -date: 2020-10-03 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- capitalize -- objective-c -title: Capitalize in Objective-C -title1: Capitalize in -title2: Objective-C ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -@interface NSString (CapitalizeFirst) -- (nullable NSString*)stringByCapitalizingFirstCharacter; -@end - -@implementation NSString (CapitalizeFirst) - -- (NSString*)stringByCapitalizingFirstCharacter { - if (self.length == 0) return nil; - - NSRange firstCharRange = [self rangeOfComposedCharacterSequenceAtIndex:0]; - NSString* firstLetter = - [[self substringWithRange:firstCharRange] uppercaseString]; - - return [self stringByReplacingCharactersInRange:firstCharRange - withString:firstLetter]; -} - -@end - -int main(int argc, const char* argv[]) { - @autoreleasepool { - NSString* usage = @"Usage: please provide a string"; - NSString* input = argc > 1 ? @(argv[1]) : @""; - - NSString* trimmed = - [input stringByTrimmingCharactersInSet: - NSCharacterSet.whitespaceAndNewlineCharacterSet]; - - NSString* result = [trimmed stringByCapitalizingFirstCharacter]; - - puts((result ?: usage).UTF8String); - } - - return 0; -} - -``` - -{% endraw %} - -Capitalize in [Objective-C](/languages/objective-c) was written by: - -- Cristiano Lopes -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/ocaml/index.md b/docs/projects/capitalize/ocaml/index.md deleted file mode 100644 index 3371c44c72..0000000000 --- a/docs/projects/capitalize/ocaml/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-16 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-16 -layout: default -tags: -- capitalize -- ocaml -title: Capitalize in OCaml -title1: Capitalize -title2: in OCaml ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let () = print_endline ( - match Array.to_list Sys.argv with - | [] | [_] | [_; ""] -> "Usage: please provide a string" - | _::args -> args |> String.concat " " |> String.capitalize_ascii) -``` - -{% endraw %} - -Capitalize in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/octave/index.md b/docs/projects/capitalize/octave/index.md deleted file mode 100644 index b0028dfefa..0000000000 --- a/docs/projects/capitalize/octave/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- capitalize -- octave -title: Capitalize in Octave -title1: Capitalize -title2: in Octave ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function capitalize() - usage = 'Usage: please provide a string'; - arg_list = argv(); - nargin = length(arg_list); - if nargin == 0 - disp(usage); - return; - end - - string = arg_list{1}; - if length(string) == 0 - disp(usage); - return; - end - - disp(strcat(upper(string(1:1)), string(2:end))); -end - -``` - -{% endraw %} - -Capitalize in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/pascal/index.md b/docs/projects/capitalize/pascal/index.md deleted file mode 100644 index c04a56222c..0000000000 --- a/docs/projects/capitalize/pascal/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- smjalageri -date: 2020-10-17 -featured-image: capitalize-in-every-language.jpg -last-modified: 2020-10-18 -layout: default -tags: -- capitalize -- pascal -title: Capitalize in Pascal -title1: Capitalize -title2: in Pascal ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program Capitalise(input, output, stdErr); -(* Accept a String from commandline, convert first character to upper case - Pascal Strings begins with 1, not 0 -*) -var -buf: string; -begin - buf := paramStr(1); - if buf = '' then - writeln('Usage: please provide a string') - else - buf[1] := UpCase(buf[1]); - writeln(buf); -end. - -``` - -{% endraw %} - -Capitalize in [Pascal](/languages/pascal) was written by: - -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/perl/index.md b/docs/projects/capitalize/perl/index.md deleted file mode 100644 index 2df4ddba59..0000000000 --- a/docs/projects/capitalize/perl/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Gabriela Kandová -- Ștefan-Iulian Alecu -date: 2019-10-17 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- capitalize -- perl -title: Capitalize in Perl -title1: Capitalize -title2: in Perl ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -sub usage { - say "Usage: please provide a string"; - exit; -} - -my ($string) = @ARGV; -usage() unless defined $string && length $string; - -say ucfirst $string; - -``` - -{% endraw %} - -Capitalize in [Perl](/languages/perl) was written by: - -- Gabriela Kandová -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/php/index.md b/docs/projects/capitalize/php/index.md deleted file mode 100644 index fd01f43daa..0000000000 --- a/docs/projects/capitalize/php/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Dowayne Breedt -- Jeremy Grifski -date: 2019-10-12 -featured-image: capitalize-in-every-language.jpg -last-modified: 2019-10-26 -layout: default -tags: -- capitalize -- php -title: Capitalize in PHP -title1: Capitalize -title2: in PHP ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Capitalize](/projects/capitalize) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide a string" - Exit 1 -} - -function Get-Capitalize([string]$Str) { - ([string]$Str[0]).ToUpper() + (-join $Str[1..$Str.Length]) -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -Write-Host (Get-Capitalize $args[0]) - -``` - -{% endraw %} - -Capitalize in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/python/index.md b/docs/projects/capitalize/python/index.md deleted file mode 100644 index 5c3b1859d1..0000000000 --- a/docs/projects/capitalize/python/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Manan Gill -- rzuckerm -- shubhragupta-code -date: 2019-10-09 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- capitalize -- python -title: Capitalize in Python -title1: Capitalize -title2: in Python ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def capitalize(input): - if len(input) > 0: - print(input[0].capitalize() + input[1:]) - - -if __name__ == '__main__': - if(len(sys.argv) == 1 or len(sys.argv[1]) == 0): - print('Usage: please provide a string') - else: - capitalize(sys.argv[1]) - -``` - -{% endraw %} - -Capitalize in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Manan Gill - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -We will consider this code block by block on the order of execution. - -```python -if __name__ == '__main__': - if(len(sys.argv) == 1 or len(sys.argv[1]) == 0): - print('Usage: please provide a string') - else: - capitalize(sys.argv[1]) -``` -This code checks if the main module is run. If it is, it then checks if the length of argument string provided by the user is 1 or empty string. If it is, it then prints correct usage pattern. Otherwise, it passes control to capitalize function passing argument string provided by the user. - -```python -def capitalize(input): - if len(input) > 0: - print(input[0].capitalize() + input[1:]) -``` -If the length provided by the user string is greater than 0, then it prints first letter of the string capitalized and concatenates the rest of the string. - - -## How to Run the Solution - -Capitalize in Python. After that, we should make sure we have the -[latest Python interpreter][1]. From there, we can simply run the following -command in the terminal: - -```console -python capitalize.py -``` - -Alternatively, we can copy the solution into an [online Python interpreter][2] -and hit run. - -[1]: https://docs.python.org/3/tutorial/interpreter.html -[2]: https://www.onlinegdb.com/online_python_interpreter diff --git a/docs/projects/capitalize/r/index.md b/docs/projects/capitalize/r/index.md deleted file mode 100644 index b2d6d480f4..0000000000 --- a/docs/projects/capitalize/r/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Veena ManikPrabhu -date: 2020-10-19 -featured-image: capitalize-in-every-language.jpg -last-modified: 2020-10-19 -layout: default -tags: -- capitalize -- r -title: Capitalize in R -title1: Capitalize -title2: in R ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -args<-commandArgs(TRUE) -if(length(args) > 0){ - if (args[1] != ""){ - len = length(args) - array_string <- strsplit(args[1], "")[[1]] - for (i in 1:len){ - if (i == 1){ - array_string[i] <- toupper(substr(array_string[i], 1, 1)) - } - #Convert to Character Vector.... else prints with spaces in between - a = as.character(array_string) - cat(a,fill = FALSE, sep = "") - } - }else{ - cat("Usage: please provide a string") - } -}else{ - cat("Usage: please provide a string") -} - -``` - -{% endraw %} - -Capitalize in [R](/languages/r) was written by: - -- Veena ManikPrabhu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/ruby/index.md b/docs/projects/capitalize/ruby/index.md deleted file mode 100644 index cf81e08335..0000000000 --- a/docs/projects/capitalize/ruby/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Couraxe -- Ștefan-Iulian Alecu -date: 2020-10-08 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- capitalize -- ruby -title: Capitalize in Ruby -title1: Capitalize -title2: in Ruby ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def capitalize_str(str) - return str if str.empty? - - str[0].upcase + str[1..] -end - -input = ARGV.first.to_s - -if input.strip.empty? - warn "Usage: please provide a string" -else - puts capitalize_str(input) -end - -``` - -{% endraw %} - -Capitalize in [Ruby](/languages/ruby) was written by: - -- Couraxe -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/rust/index.md b/docs/projects/capitalize/rust/index.md deleted file mode 100644 index c57e4e0d45..0000000000 --- a/docs/projects/capitalize/rust/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- rzuckerm -date: 2019-10-26 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-04-04 -layout: default -tags: -- capitalize -- rust -title: Capitalize in Rust -title1: Capitalize -title2: in Rust ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -// Accept a string in command line from User and Capitalize the first letter of that string -// Rust is built to support not just ASCII, but Unicode by-default. -// Do note, each character in string is multi-byte UTF-8 supported, which needs upto 3 bytes (to accommodate Japanese letters) -// Best part of Rust compiler issues warning to remove unused variables, functions, ... -fn main() { - //confirm string is passed as commandline argument - let mut input_value = std::env::args().nth(1).unwrap_or_else(|| "".to_string()); - if input_value.len() < 1 { - println!("Usage: please provide a string"); - std::process::exit(0); - } - - // Trim the trailing newline - input_value = input_value.trim_end().to_string(); - // convert to vector - let mut buff: Vec = input_value.chars().collect(); - // Change the 1'st letter to capital case - buff[0] = buff[0].to_uppercase().nth(0).unwrap(); - // convert to string for printing - let buff_hold: String = buff.into_iter().collect(); - // {} will print string without double quotes {:?} will print string with double quotes - println!("{}", buff_hold); -} - -``` - -{% endraw %} - -Capitalize in [Rust](/languages/rust) was written by: - -- Mallikarjuna S J -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/scala/index.md b/docs/projects/capitalize/scala/index.md deleted file mode 100644 index 749770cab6..0000000000 --- a/docs/projects/capitalize/scala/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- capitalize -- scala -title: Capitalize in Scala -title1: Capitalize -title2: in Scala ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -object Capitalize: - def main(args: Array[String]): Unit = - args.headOption.filter(_.nonEmpty) match - case Some(str) => println(str.capitalize) - case None => println("Usage: please provide a string") -``` - -{% endraw %} - -Capitalize in [Scala](/languages/scala) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/swift/index.md b/docs/projects/capitalize/swift/index.md deleted file mode 100644 index 0a01a82c7f..0000000000 --- a/docs/projects/capitalize/swift/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- capitalize -- swift -title: Capitalize in Swift -title1: Capitalize -title2: in Swift ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let args = CommandLine.arguments.dropFirst() - -let sentence = args - .joined(separator: " ") - .trimmingCharacters(in: .whitespacesAndNewlines) - -guard !sentence.isEmpty else { - print("Usage: please provide a string") - exit(1) -} - -let result = sentence.prefix(1).uppercased() + sentence.dropFirst() - -print(result) -``` - -{% endraw %} - -Capitalize in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/tcl/index.md b/docs/projects/capitalize/tcl/index.md deleted file mode 100644 index 36f1412ee4..0000000000 --- a/docs/projects/capitalize/tcl/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-07 -featured-image: capitalize-in-every-language.jpg -last-modified: 2025-10-07 -layout: default -tags: -- capitalize -- tcl -title: Capitalize in Tcl -title1: Capitalize -title2: in Tcl ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a string} - exit 1 -} - -if {$argc < 1} { usage } - -set buf [string trim [lindex $argv 0]] -if {$buf eq ""} { usage } - -set first [string toupper [string index $buf 0]] -set rest [string range $buf 1 end] -puts "${first}${rest}" - -``` - -{% endraw %} - -Capitalize in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/ti-basic/index.md b/docs/projects/capitalize/ti-basic/index.md deleted file mode 100644 index f75810b850..0000000000 --- a/docs/projects/capitalize/ti-basic/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-01 -featured-image: capitalize-in-every-language.jpg -last-modified: 2025-02-01 -layout: default -tags: -- capitalize -- ti-basic -title: Capitalize in TI-BASIC -title1: Capitalize -title2: in TI-BASIC ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -"abcdefghijklmnopqrstuvwxyz"->Str2 -"ABCDEFGHIJKLMNOPQRSTUVWXYZ"->Str3 -If length(Str1)=0 Then Disp "Usage: please provide a string" -Else - inString(Str2,sub(Str1,1,1))->N - If N>0 Then Disp sub(Str3,N,1)+sub(Str1,2,length(Str1)-1) - Else Disp Str1 - End -End - -``` - -{% endraw %} - -Capitalize in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/typescript/index.md b/docs/projects/capitalize/typescript/index.md deleted file mode 100644 index a3c1b74e2c..0000000000 --- a/docs/projects/capitalize/typescript/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Ray -- rzuckerm -date: 2019-10-03 -featured-image: capitalize-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- capitalize -- typescript -title: Capitalize in TypeScript -title1: Capitalize in -title2: TypeScript ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -if (process.argv.length < 3 || process.argv[2].length < 1) { - console.log("Usage: please provide a string") - process.exit(0) -} - -let myStr: string = process.argv[2]; - -const capitalize = (str: string) => str[0].toUpperCase() + str.slice(1); - -console.log(capitalize(myStr)); - -``` - -{% endraw %} - -Capitalize in [TypeScript](/languages/typescript) was written by: - -- Ray -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/capitalize/visual-basic/index.md b/docs/projects/capitalize/visual-basic/index.md deleted file mode 100644 index fe87bd5e71..0000000000 --- a/docs/projects/capitalize/visual-basic/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: capitalize-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- capitalize -- visual-basic -title: Capitalize in Visual Basic -title1: Capitalize in -title2: Visual Basic ---- - - - -Welcome to the [Capitalize](/projects/capitalize) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Module Capitalize - - Sub Main(args As String()) - - If args.Length = 0 OrElse String.IsNullOrWhiteSpace(args(0)) Then - Console.WriteLine("Usage: please provide a string") - Return - End If - - Dim input = args(0) - - Dim output = - Char.ToUpperInvariant(input(0)) & - If(input.Length > 1, input.Substring(1), String.Empty) - - Console.WriteLine(output) - - End Sub - -End Module -``` - -{% endraw %} - -Capitalize in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/ada/index.md b/docs/projects/convex-hull/ada/index.md deleted file mode 100644 index 9012bc12fd..0000000000 --- a/docs/projects/convex-hull/ada/index.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-09 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-09 -layout: default -tags: -- ada -- convex-hull -title: Convex Hull in Ada -title1: Convex Hull -title2: in Ada ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Containers; use Ada.Containers; -with Ada.Containers.Vectors; - -procedure Convex_Hull is - - Input_Error : exception; - - type Point is record - X, Y : Integer; - end record; - - function Cross_Product (O, A, B : Point) return Integer - is ((A.X - O.X) * (B.Y - O.Y) - (A.Y - O.Y) * (B.X - O.X)); - - function "<" (Left, Right : Point) return Boolean - is (Left.X < Right.X or else (Left.X = Right.X and then Left.Y < Right.Y)); - - package Int_Vectors is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - package Point_Vectors is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Point); - - package Point_Sorting is new Point_Vectors.Generic_Sorting; - - function Parse_List (S : String) return Int_Vectors.Vector is - V : Int_Vectors.Vector; - Token_Start : Positive := S'First; - begin - if S'Length = 0 then - raise Input_Error; - end if; - - for I in S'Range loop - if S (I) = ',' or else I = S'Last then - declare - Token_End : constant Natural := - (if S (I) = ',' then I - 1 else I); - - Token : constant String := - Trim (S (Token_Start .. Token_End), Ada.Strings.Both); - begin - if Token'Length = 0 then - raise Input_Error; - end if; - - V.Append (Integer'Value (Token)); - end; - - Token_Start := I + 1; - end if; - end loop; - - return V; - - exception - when others => - raise Input_Error; - end Parse_List; - - function Convex_Hull_Of - (Pts : Point_Vectors.Vector) return Point_Vectors.Vector - is - use Point_Vectors; - Sorted : Vector := Pts; - Lower : Vector; - Upper : Vector; - begin - Point_Sorting.Sort (Sorted); - - for P of Sorted loop - while Lower.Length >= 2 loop - declare - A : constant Point := Lower.Element (Lower.Last_Index - 1); - B : constant Point := Lower.Element (Lower.Last_Index); - begin - exit when Cross_Product (A, B, P) > 0; - Lower.Delete_Last; - end; - end loop; - - Lower.Append (P); - end loop; - - for I in reverse Sorted.First_Index .. Sorted.Last_Index loop - declare - P : constant Point := Sorted.Element (I); - begin - while Upper.Length >= 2 loop - declare - A : constant Point := Upper.Element (Upper.Last_Index - 1); - B : constant Point := Upper.Element (Upper.Last_Index); - begin - exit when Cross_Product (A, B, P) > 0; - Upper.Delete_Last; - end; - end loop; - - Upper.Append (P); - end; - end loop; - - if Lower.Length > 0 then - Lower.Delete_Last; - end if; - - if Upper.Length > 0 then - Upper.Delete_Last; - end if; - - for P of Upper loop - Lower.Append (P); - end loop; - - return Lower; - end Convex_Hull_Of; - - procedure Print_Points (V : Point_Vectors.Vector) is - begin - for P of V loop - Put_Line - ("(" - & Trim (P.X'Image, Ada.Strings.Left) - & ", " - & Trim (P.Y'Image, Ada.Strings.Left) - & ")"); - end loop; - end Print_Points; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide at least 3 x and y coordinates as separate lists (e.g. ""100, 440, 210"")"); - end Print_Usage; - -begin - if Argument_Count /= 2 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - begin - declare - Xs : constant Int_Vectors.Vector := Parse_List (Argument (1)); - Ys : constant Int_Vectors.Vector := Parse_List (Argument (2)); - Points : Point_Vectors.Vector; - begin - if Xs.Length /= Ys.Length or else Xs.Length < 3 then - raise Input_Error; - end if; - - for I in Xs.First_Index .. Xs.Last_Index loop - Points.Append ((X => Xs.Element (I), Y => Ys.Element (I))); - end loop; - - Print_Points (Convex_Hull_Of (Points)); - end; - exception - when Input_Error | Constraint_Error => - Print_Usage; - Set_Exit_Status (Failure); - end; - -end Convex_Hull; - -``` - -{% endraw %} - -Convex Hull in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/algol60/index.md b/docs/projects/convex-hull/algol60/index.md deleted file mode 100644 index 5b52b1103e..0000000000 --- a/docs/projects/convex-hull/algol60/index.md +++ /dev/null @@ -1,325 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-24 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- algol60 -- convex-hull -title: Convex Hull in ALGOL 60 -title1: Convex Hull -title2: in ALGOL 60 ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide at least 3 x and y coordinates as separate " - "lists (e.g. \"100, 440, 210\")\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Find Convex Hull using Jarvis' algorithm - Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/; - integer procedure convexHull(xCoords, yCoords, n, hullX, hullY); - value n; - integer array xCoords, yCoords, hullX, hullY; - integer n; - begin - integer procedure findLeftmostPoint; - begin - integer i, minIndex, minX, maxY, x, y; - - minIndex := 1; - minX := maxint; - maxY := -maxint - 1; - for i := 1 step 1 until n do - begin - comment In the event of a tie, pick the point with the greater - y-coord; - x := xCoords[i]; - y := yCoords[i]; - if x < minX | (x = minX & y > maxY) then - begin - minX := x; - maxY := y; - minIndex := i - end - end; - - findLeftmostPoint := minIndex - end findLeftmostPoint; - - comment Get orientation of three points: - - zero: points are in a line - - negative: points are counter-clockwise - - positive: points are clockwise; - integer procedure orientation(p, q, r); - value p, q, r; - integer p, q, r; - begin - orientation := - (yCoords[q] - yCoords[p]) * (xCoords[r] - xCoords[q]) - - (xCoords[q] - xCoords[p]) * (yCoords[r] - yCoords[q]) - end orientation; - - integer i, j, l, p, q; - - comment The first point is the leftmost point with the highest y-coord - in the event of a tie; - l := findLeftmostPoint; - p := l; - i := 0; - - comment Repeat until wrapped around to first hull point - Store convex hull point; - hloop: - i := i + 1; - hullX[i] := xCoords[p]; - hullY[i] := yCoords[p]; - - q := 1 + p - n * (p % n); - for j := 1 step 1 until n do - begin - comment If point j is more counter-clockwise, then update end point - (q); - if orientation(p, j, q) < 0 then q := j - end; - - p := q; - if p != l then goto hloop; - - convexHull := i - end convexHull; - - procedure outputPoints(xCoords, yCoords, numPoints); - value numPoints; - integer array xCoords, yCoords; - integer numPoints; - begin - integer i; - - for i := 1 step 1 until numPoints do - begin - outstring(1, "("); - outIntegerNoSpace(xCoords[i]); - outstring(1, ", "); - outIntegerNoSpace(yCoords[i]); - outstring(1, ")"); - outstring(1, "\n") - end - end outputPoints; - - integer argc, n; - integer array xCoords[1:100], yCoords[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 2 then usage; - - comment Get X-coordinates from 1st argument. Exit if invalid; - n := inIntegerArray(xCoords, 100); - if n < 3 then usage; - - comment Get Y-coordinates from 1st argument. Exit if invalid; - if inIntegerArray(yCoords, n + 1) != n then usage; - - comment Get convex hull of points and output points; - begin - integer array hullX[1:n], hullY[1:n]; - integer numHullPoints; - numHullPoints := convexHull(xCoords, yCoords, n, hullX, hullY); - outputPoints(hullX, hullY, numHullPoints) - end -end - -``` - -{% endraw %} - -Convex Hull in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/algol68/index.md b/docs/projects/convex-hull/algol68/index.md deleted file mode 100644 index 4ccb68edfb..0000000000 --- a/docs/projects/convex-hull/algol68/index.md +++ /dev/null @@ -1,282 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-14 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2023-02-14 -layout: default -tags: -- algol68 -- convex-hull -title: Convex Hull in ALGOL 68 -title1: Convex Hull -title2: in ALGOL 68 ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. ""100, 440, 210"")")) -); - -# Combine values into a set of points # -MODE POINT = STRUCT(INT x, INT y); -OP = =(POINT p1, POINT p2) BOOL: (x OF p1 = x OF p2) AND (y OF p1 = y OF p2); - -PROC form points = (REF []INT x values, REF []INT y values) REF []POINT: -( - INT n = UPB x values; - HEAP [n]POINT points; - FOR k TO n - DO - points[k] := POINT(x values[k], y values[k]) - OD; - - points -); - -COMMENT -Find Convex Hull using Jarvis' algorithm -Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/ -COMMENT -PROC convex hull = (REF []POINT points) REF []POINT: -( - INT n := UPB points; - - # hull will be the set of points which form the convex hull. # - # Final set size is i # - HEAP [n]POINT hull; - - # The first point is the leftmost point with the highest y-coord in the # - # event of a tie # - INT l := find leftmost point(points); - - # Repeat until wrapped around to first hull point # - INT p := l; - INT q; - INT i := 0; - DO - # Store conex hull point # - i +:= 1; - hull[i] := points[p]; - - q := 1 + p MOD n; - FOR j TO n - DO - # If point j is more counter-clockwise, then update end point (q) # - IF orientation(points[p], points[j], points[q]) < 0 - THEN - q := j - FI - OD; - - p := q - UNTIL p = l - OD; - hull[1:i] -); - -PROC find leftmost point = (REF []POINT points) INT: -( - INT n := UPB points; - INT min x := max int; - INT max y := -max int; - INT min index := 1; - INT x; - INT y; - FOR k TO n - DO - # In the event of a tie, pick the point with the greater y-coord # - x := x OF points[k]; - y := y OF points[k]; - IF (x < min x) OR (x = min x AND y > max y) - THEN - min x := x; - max y := y; - min index := k - FI - OD; - - min index -); - -COMMENT -Get orientation of three points - -0 = points are in a line -> 0 = points are counter-clockwise -< 0 = points are clockwise -COMMENT -PROC orientation = (POINT p, POINT q, POINT r) INT: -( - ( - (y OF q - y OF p) * (x OF r - x OF q) - - (x OF q - x OF p) * (y OF r - y OF q) - ) -); - -# Show points # -PROC show points = (REF []POINT points) VOID: -( - INT n := UPB points; - FOR k TO n - DO - printf(($"("g", "g")"l$, whole(x OF points[k], 0), whole(y OF points[k], 0))) - OD -); - -# Parse 1st and 2nd command-line arguments # -[2]REF []INT values; -[2]INT argnums := (4, 5); -FOR k TO 2 -DO - STRING s := argv(argnums[k]); - PARSEINTLIST_RESULT list result := parse int list(s); - values[k] := values OF list result; - IF NOT valid OF list result OR UPB values[k] < 3 - THEN - usage; - stop - FI -OD; - -# Make sure same number of points # -IF UPB values[1] /= UPB values[2] -THEN - usage; - stop -FI; - -# Combine values into set of points # -REF []POINT points = form points(values[1], values[2]); - -# Get convex hull of points and show points # -REF []POINT hull points = convex hull(points); -show points(hull points) - -``` - -{% endraw %} - -Convex Hull in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/awk/index.md b/docs/projects/convex-hull/awk/index.md deleted file mode 100644 index 7b75b01521..0000000000 --- a/docs/projects/convex-hull/awk/index.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-30 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2025-04-30 -layout: default -tags: -- awk -- convex-hull -title: Convex Hull in AWK -title1: Convex Hull -title2: in AWK ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -function form_points(x_points, y_points, points, idx) { - for (idx in x_points) { - points[idx]["x"] = x_points[idx] - points[idx]["y"] = y_points[idx] - } -} - -# Find Convex Hull using Jarvis' algorithm -# Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/ -function convex_hull(points, num_points, hull_points, i, j, l, p, q) { - # The first point is the leftmost point with the highest y-coord in the - # event of a tie - l = find_leftmost_point(points) - - # Repeat until wrapped around to first hull point - p = l - i = 0 - do { - # Store convex hull point - i++ - hull_points[i]["x"] = points[p]["x"] - hull_points[i]["y"] = points[p]["y"] - - q = 1 + (p % num_points) - for (j = 1; j <= num_points; j++) { - # If point j is counter-clockwise, then update end point (q) - if (orientation(points[p], points[j], points[q]) < 0) { - q = j - } - } - - p = q - } while (p != l) -} - -function find_leftmost_point(points, idx, min_index, x_min, y_max, x, y) { - x_min = 1e999 - y_max = -1e999 - min_index = 0 - for (idx in points) { - x = points[idx]["x"] - y = points[idx]["y"] - if ((x < x_min) || (x == x_min && y > y_max)) { - x_min = x - y_max = y - min_index = idx - } - } - - return min_index -} - -# Get orientation of three points -# -# 0 = points are in a line -# > 0 = points are clockwise -# < 0 = points are counter-clockwise -function orientation(p, q, r) { - return (q["y"] - p["y"]) * (r["x"] - q["x"]) - \ - (q["x"] - p["x"]) * (r["y"] - q["y"]) -} - -function show_points(points, idx) { - for (idx in points) { - printf("(%d, %d)\n", points[idx]["x"], points[idx]["y"]) - } -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], x_points) - x_len = length(x_points) - str_to_array(ARGV[2], y_points) - y_len = length(y_points) - if (x_len < 3 || y_len < 3 || x_len != y_len) { - usage() - } - - form_points(x_points, y_points, points) - convex_hull(points, x_len, hull_points) - show_points(hull_points) -} - -``` - -{% endraw %} - -Convex Hull in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/beef/index.md b/docs/projects/convex-hull/beef/index.md deleted file mode 100644 index a7d28b955d..0000000000 --- a/docs/projects/convex-hull/beef/index.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-18 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2024-02-18 -layout: default -tags: -- beef -- convex-hull -title: Convex Hull in Beef -title1: Convex Hull -title2: in Beef ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace ConvexHull; - -struct Point -{ - public T x; - public T y; - - public this(T xValue, T yValue) - { - x = xValue; - y = yValue; - } - - public override void ToString(String str) - { - str.AppendF("({}, {})", x, y); - } -} - -class PointsList : List> -{ - public this() - { - } - - public this(List xValues, List yValues) - { - for (int i < xValues.Count) - { - this.Add(.(xValues[i], yValues[i])); - } - } - - public override void ToString(String str) - { - for (Point point in this) - { - str.AppendF("{}\n", point); - } - } -} - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210") - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Find Convex Hull using Jarvis' algorithm - // Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/ - public static void ConvexHull(PointsList points, PointsList hullPoints) - where T : operator T - T, operator T * T - where int : operator T <=> T - { - int n = points.Count; - - // Initialize hull points - hullPoints.Clear(); - - // The first point is the leftmost point with the highest y-coord in the - // event of a tie - int l = 0; - for (int i in 1.. points[i].y)) - { - l = i; - } - } - - // Repeat until wrapped around to first hull point - int p = l; - repeat - { - // Store convex hull point - hullPoints.Add(points[p]); - - int q = (p + 1) % n; - for (int j < n) - { - // If point j is more counter-clockwise, then update end point (q) - if (Orientation(points[p], points[j], points[q]) < 0) - { - q = j; - } - } - - p = q; - } - while (p != l); - } - - // Get orientation of three points - // - // 0 = points are in a line - // > 0 = points are clockwise - // < 0 = points are counter-clockwise - public static int Orientation(Point p, Point q, Point r) - where T : operator T - T, operator T * T - where int : operator T <=> T - { - return (q.y - p.y) * (r.x - q.x) <=> (q.x - p.x) * (r.y - q.y); - } - - public static int Main(String[] args) - { - if (args.Count < 2) - { - Usage(); - } - - List xValues = scope .(); - if (ParseIntList(args[0], xValues) case .Err) - { - Usage(); - } - - List yValues = scope .(); - if (ParseIntList(args[1], yValues) case .Err) - { - Usage(); - } - - if (xValues.Count != yValues.Count || xValues.Count < 3) - { - Usage(); - } - - PointsList points = scope .(xValues, yValues); - PointsList hullPoints = scope .(); - ConvexHull(points, hullPoints); - Console.WriteLine(hullPoints); - - return 0; - } -} - -``` - -{% endraw %} - -Convex Hull in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/c-plus-plus/index.md b/docs/projects/convex-hull/c-plus-plus/index.md deleted file mode 100644 index ee2011dfb7..0000000000 --- a/docs/projects/convex-hull/c-plus-plus/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- convex-hull -title: Convex Hull in C++ -title1: Convex Hull -title2: in C++ ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include - -namespace views = std::views; -namespace ranges = std::ranges; - -struct Point { - int x{}, y{}; - auto operator<=>(const Point&) const = default; -}; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210"))" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -auto to_sv = [](auto&& r) { - return std::string_view{std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; -}; - -auto parse_ints(std::string_view s) { - return s | views::split(',') | views::transform(to_sv) | - views::transform(trim) | views::transform(to_int); -} - -std::vector parse_coordinates(std::string_view xs, std::string_view ys) { - auto xv = parse_ints(xs); - auto yv = parse_ints(ys); - - std::vector pts; - - auto xi = xv.begin(); - auto yi = yv.begin(); - - for (; xi != xv.end() && yi != yv.end(); ++xi, ++yi) { - if (!*xi || !*yi) usage(); - pts.emplace_back(**xi, **yi); - } - - if (xi != xv.end() || yi != yv.end() || pts.size() < 3) usage(); - - return pts; -} - -constexpr long long orientation(Point a, Point b, Point c) noexcept { - return 1LL * (b.x - a.x) * (c.y - a.y) - 1LL * (b.y - a.y) * (c.x - a.x); -} - -template -std::vector build_half(R&& range) { - std::vector hull; - for (const auto& p : range) { - while (hull.size() >= 2 && - orientation(hull[hull.size() - 2], hull.back(), p) <= 0) { - hull.pop_back(); - } - hull.push_back(p); - } - hull.pop_back(); - return hull; -} - -std::vector convex_hull(std::vector pts) { - ranges::sort(pts); - auto [first, last] = ranges::unique(pts); - pts.erase(first, last); - - if (pts.size() < 3) return pts; - - auto lower = build_half(pts); - auto upper = build_half(pts | views::reverse); - - lower.insert(lower.end(), upper.begin(), upper.end()); - return lower; -} - -int main(int argc, char* argv[]) { - if (argc != 3) usage(); - - auto points = parse_coordinates(argv[1], argv[2]); - auto result = convex_hull(std::move(points)); - - for (const auto& p : result) { - std::cout << std::format("({}, {})\n", p.x, p.y); - } -} -``` - -{% endraw %} - -Convex Hull in [C++](/languages/c-plus-plus) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/c-sharp/index.md b/docs/projects/convex-hull/c-sharp/index.md deleted file mode 100644 index e6d00d7865..0000000000 --- a/docs/projects/convex-hull/c-sharp/index.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-29 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- convex-hull -title: Convex Hull in C# -title1: Convex -title2: Hull in C# ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Runtime.InteropServices; - -if ( - args is not [var xInput, var yInput] - || !TryParsePoints(xInput.AsSpan(), yInput.AsSpan(), out var points) -) -{ - return Usage(); -} - -points.Sort(); - -var hull = BuildHull(CollectionsMarshal.AsSpan(points), out int size); -for (int i = 0; i < size; i++) - Console.WriteLine(hull[i]); - -return 0; - -static bool TryParsePoints(ReadOnlySpan x, ReadOnlySpan y, out List points) -{ - points = []; - - if (x.IsWhiteSpace() || y.IsWhiteSpace()) - return false; - - var list = new List(); - - while (true) - { - if (!TryNext(ref x, out int xVal) || !TryNext(ref y, out int yVal)) - break; - - points.Add(new(xVal, yVal)); - } - - return x.IsEmpty && y.IsEmpty && points.Count >= 3; - - static bool TryNext(ref ReadOnlySpan span, out int value) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - span = comma >= 0 ? span[(comma + 1)..] : []; - return int.TryParse(token, out value); - } -} - -static Point[] BuildHull(Span points, out int size) -{ - int numPoints = points.Length; - if (numPoints < 3) - { - size = numPoints; - return points.ToArray(); - } - - var hull = new Point[numPoints * 2]; - int h = 0; - - for (int i = 0; i < numPoints; i++) - { - var p = points[i]; - - while (h > 1 && Cross(hull[h - 2], hull[h - 1], p) <= 0) - h--; - - hull[h++] = p; - } - - int lower = h; - - for (int i = numPoints - 2; i >= 0; i--) - { - var p = points[i]; - - while (h > lower && Cross(hull[h - 2], hull[h - 1], p) <= 0) - h--; - - hull[h++] = p; - } - - size = h - 1; - return hull; - - static long Cross(Point o, Point a, Point b) => - (long)(a.X - o.X) * (b.Y - o.Y) - (long)(a.Y - o.Y) * (b.X - o.X); -} - -static int Usage() -{ - Console.Error.WriteLine( - """Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")""" - ); - return 1; -} - -public readonly record struct Point(int X, int Y) : IComparable -{ - public int CompareTo(Point other) => X != other.X ? X.CompareTo(other.X) : Y.CompareTo(other.Y); - - public override string ToString() => $"({X}, {Y})"; -} - -``` - -{% endraw %} - -Convex Hull in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/c/index.md b/docs/projects/convex-hull/c/index.md deleted file mode 100644 index 8c6d36b89d..0000000000 --- a/docs/projects/convex-hull/c/index.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2024-11-16 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- convex-hull -title: Convex Hull in C -title1: Convex -title2: Hull in C ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include -#include - -typedef struct -{ - int x; - int y; -} Point; - -void printUsageAndExit() -{ - printf("Usage: please provide at least 3 x and y coordinates as separate " - "lists (e.g. \"100, 440, 210\")\n"); - exit(1); -} - -int compare(const void *p1, const void *p2) -{ - Point *point1 = (Point *)p1; - Point *point2 = (Point *)p2; - - if (point1->x != point2->x) - return point1->x - point2->x; - return point1->y - point2->y; -} - -int orientation(Point p, Point q, Point r) -{ - int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); - return (val == 0) ? 0 : (val > 0) ? 1 : 2; -} - -void convexHull(Point points[], int n) -{ - Point hull[n]; - int hullCount = 0; - - qsort(points, n, sizeof(Point), compare); - - int l = 0; - for (int i = 1; i < n; i++) - if (points[i].x < points[l].x) - l = i; - - int p = l, q; - do - { - hull[hullCount++] = points[p]; - q = (p + 1) % n; - - for (int i = 0; i < n; i++) - if (orientation(points[p], points[i], points[q]) == 2) - q = i; - - p = q; - } while (p != l); - - for (int i = 0; i < hullCount; i++) - printf("(%d, %d)\n", hull[i].x, hull[i].y); -} - -// Function to check if a string is a valid number -bool isInteger(const char *s) -{ - char *end; - strtol(s, &end, 10); // Convert string to long - return (*end == '\0' - || *end == '\n'); // Check if the entire string was valid -} - -// Function to trim whitespace from a string -char *trimWhitespace(char *str) -{ - // Trim leading whitespace - while (isspace((unsigned char)*str)) - str++; - // Trim trailing whitespace - char *end = str + strlen(str) - 1; - while (end > str && isspace((unsigned char)*end)) - end--; - *(end + 1) = '\0'; // Null terminate after the last non-space character - return str; -} - -// Function to parse input string and populate the array -int parseInput(const char *input, int **arr, int *size) -{ - char *token; - int capacity = 10; // Initial capacity - *arr = malloc(capacity * sizeof(int)); - if (*arr == NULL) - return false; - - // Tokenize the input string based on commas - char *inputCopy = strdup(input); - if (inputCopy == NULL) - { - free(*arr); - *arr = NULL; - return false; - } - - token = strtok(inputCopy, ","); - *size = 0; - while (token) - { - trimWhitespace(token); // Trim whitespace around token - if (!isInteger(token)) - { - free(*arr); - free(inputCopy); - *arr = NULL; - return false; // Exit if a number is invalid - } - - if (*size >= capacity) - { - capacity *= 2; - *arr = realloc(*arr, capacity * sizeof(int)); - if (*arr == NULL) - { - free(inputCopy); - return false; - } - } - (*arr)[(*size)++] = atoi(token); - token = strtok(NULL, ","); - } - - // Resize the array to the actual size - *arr = realloc(*arr, *size * sizeof(int)); - free(inputCopy); // Free the input copy - if (*arr == NULL) - return false; - - return true; // Successful parsing -} - -void parseCoordinates(char *inputX, char *inputY) -{ - int *xCoords = NULL; - int *yCoords = NULL; - int xSize = 0; - int ySize = 0; - if (!parseInput(inputX, &xCoords, &xSize) - || !parseInput(inputY, &yCoords, &ySize) - || xSize != ySize - || xSize < 3) - { - if (xCoords != NULL) - free(xCoords); - - if (yCoords != NULL) - free(yCoords); - - printUsageAndExit(); - } - - int count = xSize; - Point *points = malloc(sizeof(Point) * count); - if (points == NULL) - { - free(xCoords); - free(yCoords); - printUsageAndExit(); - } - - for (int i = 0; i < count; i++) - { - points[i].x = xCoords[i]; - points[i].y = yCoords[i]; - } - - free(xCoords); - free(yCoords); - - convexHull(points, count); - free(points); -} - -int main(int argc, char *argv[]) -{ - if (argc != 3) - printUsageAndExit(); - - char *inputX = argv[1]; - char *inputY = argv[2]; - - if (strlen(inputX) == 0 || strlen(inputY) == 0) - printUsageAndExit(); - - parseCoordinates(inputX, inputY); - return 0; -} - -``` - -{% endraw %} - -Convex Hull in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/cobol/index.md b/docs/projects/convex-hull/cobol/index.md deleted file mode 100644 index 689278a16b..0000000000 --- a/docs/projects/convex-hull/cobol/index.md +++ /dev/null @@ -1,224 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-01 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-01 -layout: default -tags: -- cobol -- convex-hull -title: Convex Hull in COBOL -title1: Convex Hull -title2: in COBOL ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. convex-hull. - -data division. -working-storage section. - -01 arg-processing. - 05 arg-count pic 9(4) comp-5. - 05 arg-x pic x(4096). - 05 arg-y pic x(4096). - 05 arg-len pic 9(4) comp-5. - -01 point-cloud. - 05 n pic 9(4) comp-5 value 0. - 05 points occurs 100 times indexed by pt-idx, inner-idx, k-idx. - 10 pt-x pic s9(9) comp-5. - 10 pt-y pic s9(9) comp-5. - -01 hull-logic. - 05 k pic 9(4) comp-5 value 0. - 05 hull-indices occurs 200 times pic 9(4) comp-5. - 05 min-k pic 9(4) comp-5. - 05 start-idx pic s9(4) comp-5. - 05 cross-product pic s9(18) comp-5. - 88 is-strictly-clockwise value -999999999999999999 thru -1. - -01 parsing-helpers. - 05 delim pic x value ",". - 05 ptr pic 9(4) comp-5. - 05 val-str pic x(20). - 05 temp-x pic s9(9) comp-5. - 05 temp-y pic s9(9) comp-5. - 05 char-idx pic 9(4) comp-5. - -01 display-format. - 05 out-x pic -(9)9. - 05 out-y pic -(9)9. - 05 out-line pic x(50). - -procedure division. - -main. - accept arg-count from argument-number - if arg-count < 2 - perform show-usage - end-if - - accept arg-x from argument-value - accept arg-y from argument-value - - perform parse-input - - if n < 3 - perform show-usage - end-if - - perform sort-points - perform build-convex-hull - perform display-results - goback. - -parse-input. - move 1 to ptr - compute arg-len = function length(function trim(arg-x)) - perform varying n from 1 by 1 until ptr > arg-len - move spaces to val-str - unstring arg-x delimited by delim into val-str pointer ptr - if val-str = spaces - exit perform - end-if - perform validate-val-str - compute pt-x(n) = function numval(val-str) - end-perform - compute n = n - 1 - - move 1 to ptr - compute arg-len = function length(function trim(arg-y)) - perform varying inner-idx from 1 by 1 until inner-idx > n - if ptr > arg-len - perform show-usage - end-if - move spaces to val-str - unstring arg-y delimited by delim into val-str pointer ptr - if val-str = spaces - perform show-usage - end-if - perform validate-val-str - compute pt-y(inner-idx) = function numval(val-str) - end-perform - - move spaces to val-str - unstring arg-y delimited by delim into val-str pointer ptr - if val-str not = spaces - perform show-usage - end-if. - -validate-val-str. - perform varying char-idx from 1 by 1 until - char-idx > function length(function trim(val-str)) - if val-str(char-idx:1) not numeric and - val-str(char-idx:1) not = "-" and - val-str(char-idx:1) not = " " - perform show-usage - end-if - end-perform. - -sort-points. - perform varying pt-idx from 1 by 1 until pt-idx > n - 1 - perform varying inner-idx from 1 by 1 until - inner-idx > n - pt-idx - compute k-idx = inner-idx + 1 - if pt-x(inner-idx) > pt-x(k-idx) or - (pt-x(inner-idx) = pt-x(k-idx) and - pt-y(inner-idx) > pt-y(k-idx)) - move pt-x(inner-idx) to temp-x - move pt-y(inner-idx) to temp-y - move pt-x(k-idx) to pt-x(inner-idx) - move pt-y(k-idx) to pt-y(inner-idx) - move temp-x to pt-x(k-idx) - move temp-y to pt-y(k-idx) - end-if - end-perform - end-perform. - -build-convex-hull. - move 0 to k - - perform varying pt-idx from 1 by 1 until pt-idx > n - perform pop-back-points - add 1 to k - move pt-idx to hull-indices(k) - end-perform - - compute min-k = k + 1 - compute start-idx = n - 1 - perform varying pt-idx from start-idx by -1 until pt-idx < 1 - perform pop-back-points - add 1 to k - move pt-idx to hull-indices(k) - end-perform - subtract 1 from k. - -pop-back-points. - perform until k < 2 - perform calculate-cross-product - if is-strictly-clockwise - subtract 1 from k - else - exit perform - end-if - end-perform. - -calculate-cross-product. - compute cross-product = - (pt-x(hull-indices(k)) - pt-x(hull-indices(k - 1))) * - (pt-y(pt-idx) - pt-y(hull-indices(k - 1))) - - (pt-y(hull-indices(k)) - pt-y(hull-indices(k - 1))) * - (pt-x(pt-idx) - pt-x(hull-indices(k - 1))). - -display-results. - perform varying pt-idx from 1 by 1 until pt-idx > k - move pt-x(hull-indices(pt-idx)) to out-x - move pt-y(hull-indices(pt-idx)) to out-y - string "(" function trim(out-x) ", " - function trim(out-y) ")" - delimited by size into out-line - display function trim(out-line) - move spaces to out-line - end-perform. - -show-usage. - display "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. ""100, 440, 210"")" - stop run. - -``` - -{% endraw %} - -Convex Hull in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/commodore-basic/index.md b/docs/projects/convex-hull/commodore-basic/index.md deleted file mode 100644 index 7c910be5e6..0000000000 --- a/docs/projects/convex-hull/commodore-basic/index.md +++ /dev/null @@ -1,191 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-15 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2023-10-15 -layout: default -tags: -- commodore-basic -- convex-hull -title: Convex Hull in Commodore BASIC -title1: Convex Hull in -title2: Commodore BASIC ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99), P(99, 1), H(99, 1) -15 REM Get x values -20 GOSUB 2000 -30 IF V = 0 OR C <> -1 THEN GOTO 200: REM invalid or not end of value -40 NP = NA -50 FOR I = 0 TO NA - 1 -60 P(I, 0) = A(I) -70 NEXT I -75 REM Get y values -80 GOSUB 2000 -90 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end input/value -100 FOR I = 0 TO NA - 1 -110 P(I, 1) = A(I) -120 NEXT I -125 REM Validate number of x and y values -130 IF NP <> NA OR NP < 3 THEN GOTO 200 -135 REM Perform convex hull and show results -140 GOSUB 3000 -150 GOSUB 3500 -160 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide at least 3 x and y coordinates as separate "; -220 PRINT "lists (e.g. "; Q$; "100, 440, 210"; Q$; ")" -230 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Find Convex Hull using Jarvis' algorithm -3001 REM Source: -3002 REM https://www.geeksforgeeks.org/ -3003 REM convex-hull-using-jarvis-algorithm-or-wrapping/ -3004 REM Inputs: -3005 REM - P contains points -3006 REM - NP contains number of points -3007 REM Outputs: -3008 REM - H contains hull points -3009 REM - NH contains number of hull points -3010 REM Initialize hull points -3020 NH = 0 -3030 REM The first point is the leftmost point with the highest y-coord in the -3040 REM event of a tie -3050 LI = 0 -3070 FOR I = 1 TO NP - 1 -3080 IF P(I, 0) < P(LI, 0) THEN GOTO 3100 -3090 IF P(I, 0) <> P(LI, 0) OR P(I, 1) <= P(LI, 1) THEN GOTO 3110 -3100 LI = I -3110 NEXT I -3120 PI = LI -3125 REM Store hull point -3130 H(NH, 0) = P(PI, 0) -3140 H(NH, 1) = P(PI, 1) -3150 NH = NH + 1 -3155 REM Update end point if point found is more counter-clockwise -3160 QI = PI + 1 -3170 IF QI >= NP THEN QI = QI - NP -3180 FOR J = 0 TO NP -1 -3181 REM Determine orientation: -3182 REM - 0 means points in a line -3183 REM - > 0 means points are clockwise -3184 REM - < 0 mean points are counter-clockwise -3190 O = (P(J, 1) - P(PI, 1)) * (P(QI, 0) - P(J, 0)) -3200 O = O - (P(J, 0) - P(PI, 0)) * (P(QI, 1) - P(J, 1)) -3210 IF O < 0 THEN QI = J -3220 NEXT J -3225 REM Repeat until wrapped to first hull point -3230 PI = QI -3240 IF PI <> LI THEN GOTO 3130 -3250 RETURN -3500 REM Display hull points -3501 REM Inputs: -3502 REM - H contains hull points -3503 REM - NH contains number of hull points -3510 IF NA < 1 THEN GOTO 3590 -3520 FOR I = 0 TO NH - 1 -3530 SX$ = STR$(H(I, 0)) -3540 IF H(I, 0) >= 0 THEN SX$ = MID$(SX$, 2): REM strip leading space -3550 SY$ = STR$(H(I, 1)) -3560 IF H(I, 1) >= 0 THEN SY$ = MID$(SY$, 2): REM strip leading space -3570 PRINT "("; SX$; ", "; SY$; ")" -3580 NEXT I -3590 RETURN - -``` - -{% endraw %} - -Convex Hull in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/euphoria/index.md b/docs/projects/convex-hull/euphoria/index.md deleted file mode 100644 index 82dd21d68d..0000000000 --- a/docs/projects/convex-hull/euphoria/index.md +++ /dev/null @@ -1,247 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-25 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2023-03-27 -layout: default -tags: -- convex-hull -- euphoria -title: Convex Hull in Euphoria -title1: Convex Hull -title2: in Euphoria ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/math.e -include std/mathcons.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")\n" - ) - abort(0) -end procedure - --- Indices of coordinates -enum X, Y - --- Combine values into a set of points -function form_points(sequence x_values, sequence y_values) - integer n = length(x_values) - sequence points = {} - for k = 1 to n - do - points &= {{x_values[k], y_values[k]}} - end for - - return points -end function - --- Find Convex Hull using Jarvis' algorithm --- Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/ -function convex_hull(sequence points) - integer n = length(points) - - -- hull will be the set of points which form the convex hull - -- Final set size is i - sequence hull = {} - - -- The first point is the leftmost point with the highest y-coord in the - -- event of a tie - integer l = find_leftmost_point(points) - - -- Repeat until wrapped around to first hull point - integer p = l - integer q - loop - do - -- Store convex hull point - hull &= {points[p]} - - q = 1 + mod(p, n) - for j = 1 to n - do - -- If point j is more counter-clockwise, then update end point (q) - if orientation(points[p], points[j], points[q]) < 0 - then - q = j - end if - end for - - p = q - until p = l - end loop - - return hull -end function - -function find_leftmost_point(sequence points) - integer n = length(points) - atom min_x = PINF - atom max_y = MINF - integer min_index = 1 - integer x - integer y - for k = 1 to n - do - -- In the event of a tie, pick the point with the greater y-coord - x = points[k][X] - y = points[k][Y] - if x < min_x or (x = min_x and y > max_y) - then - min_x = x - max_y = y - min_index = k - end if - end for - - return min_index -end function - --- Get orientation of three points --- --- 0 = points are in a line --- > 0 = points are clockwise --- < 0 = points are counter-clockwise -function orientation(sequence p, sequence q, sequence r) - return ( - (q[Y] - p[Y]) * (r[X] - q[X]) - - (q[X] - p[X]) * (r[Y] - q[Y]) - ) -end function - --- Show points -procedure show_points(sequence points) - for k = 1 to length(points) - do - printf(STDOUT, "(%d, %d)\n", {points[k][X], points[k][Y]}) - end for -end procedure - --- Check 1st and 2nd command-line arguments -sequence argv = command_line() -if length(argv) < 5 or length(argv[4]) = 0 or length(argv[5]) = 0 -then - usage() -end if - --- Parse 1st and 2nd command-line arguments -sequence arg_nums = {4, 5} -sequence values = {} -for k = 1 to 2 -do - sequence result = parse_int_list(argv[arg_nums[k]]) - values &= {result[PARSE_INT_LIST_VALUES]} - if not result[PARSE_INT_LIST_VALID] or length(values[k]) < 3 - then - usage() - end if -end for - --- Make sure same number of points -if length(values[1]) != length(values[2]) -then - usage() -end if - --- Combine values into set of points -sequence points = form_points(values[1], values[2]) - --- Get convex hull of points and show points -sequence hull_points = convex_hull(points) -show_points(hull_points) - -``` - -{% endraw %} - -Convex Hull in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/f-sharp/index.md b/docs/projects/convex-hull/f-sharp/index.md deleted file mode 100644 index 913283a798..0000000000 --- a/docs/projects/convex-hull/f-sharp/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- convex-hull -- f-sharp -title: Convex Hull in F# -title1: Convex -title2: Hull in F# ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -[] -type Point = - { X: int - Y: int } - - static member Create x y = { X = x; Y = y } - static member ToDisplay p = sprintf "(%d, %d)" p.X p.Y - -module ConvexHull = - let private cross a b c = - int64 (b.X - a.X) * int64 (c.Y - a.Y) - int64 (b.Y - a.Y) * int64 (c.X - a.X) - - let private buildHalf (pts: Point seq) = - let hull = ResizeArray() - - for p in pts do - while hull.Count >= 2 && cross hull.[hull.Count - 2] hull.[hull.Count - 1] p < 0L do - hull.RemoveAt(hull.Count - 1) - - hull.Add(p) - - hull - - let convexHull (points: Point array) = - let sorted = points |> Array.distinct |> Array.sortBy (fun p -> p.X, p.Y) - - if sorted.Length < 3 then - sorted - else - let lower = buildHalf sorted - let upper = buildHalf (sorted |> Seq.rev) - - let result = Array.zeroCreate (lower.Count + upper.Count - 2) - lower.CopyTo(0, result, 0, lower.Count - 1) - upper.CopyTo(0, result, lower.Count - 1, upper.Count - 1) - result - - let run (points: Point array) = - points |> convexHull |> Array.map Point.ToDisplay |> String.concat "\n" |> Ok - - -module Helpers = - let usage = - "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")" - - let private (|IntList|_|) (s: string) = - if String.IsNullOrWhiteSpace s then - None - else - let parts = s.Split(',', StringSplitOptions.RemoveEmptyEntries) - let parsed = Array.zeroCreate parts.Length - let mutable allValid = true - let mutable i = 0 - - while allValid && i < parts.Length do - match Int32.TryParse(parts.[i].Trim()) with - | true, n -> - parsed.[i] <- n - i <- i + 1 - | _ -> allValid <- false - - if allValid && parsed.Length >= 2 then Some parsed else None - - let private (|Points|_|) (args: string array) = - match args with - | [| IntList xs; IntList ys |] when xs.Length = ys.Length && xs.Length >= 3 -> - Array.map2 Point.Create xs ys |> Some - | _ -> None - - let parseArgs argv = - match argv with - | Points pts -> Ok pts - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.bind ConvexHull.run |> Helpers.handleResult - -``` - -{% endraw %} - -Convex Hull in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/go/index.md b/docs/projects/convex-hull/go/index.md deleted file mode 100644 index 76cb2b9008..0000000000 --- a/docs/projects/convex-hull/go/index.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- convex-hull -- go -title: Convex Hull in Go -title1: Convex -title2: Hull in Go ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "sort" - "strconv" - "strings" -) - -type Point struct { - x int - y int -} - -const usage = `Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")` - -func parseCoordinates(input string) ([]int, error) { - parts := strings.Split(input, ",") - nums := make([]int, 0, len(parts)) - for _, p := range parts { - val, err := strconv.Atoi(strings.TrimSpace(p)) - if err != nil { - return nil, fmt.Errorf("invalid number %s", p) - } - nums = append(nums, val) - } - return nums, nil -} - -func parsePoints(xArg, yArg string) ([]Point, error) { - xs, errX := parseCoordinates(xArg) - ys, errY := parseCoordinates(yArg) - - if errX != nil || errY != nil { - return nil, fmt.Errorf("failed to parse input coordinates") - } - - if len(xs) != len(ys) { - return nil, fmt.Errorf("coordinate count mismatch: x=%d, y=%d", len(xs), len(ys)) - } - - if len(xs) < 3 { - return nil, fmt.Errorf("at least 3 points are required") - } - - points := make([]Point, len(xs)) - for i := 0; i < len(xs); i++ { - points[i] = Point{x: xs[i], y: ys[i]} - } - return points, nil -} - -func cross(o, a, b Point) int { - return (a.x-o.x)*(b.y-o.y) - (a.y-o.y)*(b.x-o.x) -} - -func convexHull(points []Point) []Point { - n := len(points) - if n <= 2 { - return points - } - - sort.Slice(points, func(i, j int) bool { - if points[i].x != points[j].x { - return points[i].x < points[j].x - } - return points[i].y < points[j].y - }) - - unique := points[:0] - for i := 0; i < len(points); i++ { - if i == 0 || points[i] != points[i-1] { - unique = append(unique, points[i]) - } - } - points = unique - - if len(points) <= 2 { - return points - } - - var hull []Point - - for _, p := range points { - for len(hull) >= 2 && cross(hull[len(hull)-2], hull[len(hull)-1], p) <= 0 { - hull = hull[:len(hull)-1] - } - hull = append(hull, p) - } - - lowerLen := len(hull) - for i := len(points) - 2; i >= 0; i-- { - p := points[i] - for len(hull) > lowerLen && cross(hull[len(hull)-2], hull[len(hull)-1], p) <= 0 { - hull = hull[:len(hull)-1] - } - hull = append(hull, p) - } - - return hull[:len(hull)-1] -} - -func main() { - if len(os.Args) != 3 { - fmt.Fprintln(os.Stderr, usage) - os.Exit(1) - } - - points, err := parsePoints(os.Args[1], os.Args[2]) - if err != nil { - fmt.Fprintf(os.Stderr, usage) - os.Exit(1) - } - - result := convexHull(points) - - for _, p := range result { - fmt.Printf("(%d, %d)\n", p.x, p.y) - } -} -``` - -{% endraw %} - -Convex Hull in [Go](/languages/go) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/haskell/index.md b/docs/projects/convex-hull/haskell/index.md deleted file mode 100644 index da38e1b4fc..0000000000 --- a/docs/projects/convex-hull/haskell/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-23 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-23 -layout: default -tags: -- convex-hull -- haskell -title: Convex Hull in Haskell -title1: Convex Hull -title2: in Haskell ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Data.List (minimumBy, maximumBy) -import Data.Ord (comparing) -import Control.Monad (guard, forM_) -import Text.Read (readMaybe) -import System.Environment (getArgs) - -type Point = (Int, Int) - -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - -cross :: Point -> Point -> Point -> Int -cross (x1, y1) (x2, y2) (x3, y3) = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1) - -dist :: Point -> Point -> Int -dist (x1, y1) (x2, y2) = (x2 - x1) ^ 2 + (y2 - y1) ^ 2 - -jarvis :: [Point] -> [Point] -jarvis points = startingPoint : go startingPoint - where - startingPoint = minimumBy (comparing fst) points - nextPoint prev = maximumBy (comparePoints prev) points - comparePoints prev p1 p2 = - case compare (cross prev p1 p2) 0 of - EQ -> compare (dist prev p1) (dist prev p2) - x -> x - go cur - | next == startingPoint = [] - | otherwise = next : go next - where next = nextPoint cur - -parseArgs :: [String] -> Maybe [Point] -parseArgs [xs, ys] = do - xs' <- stringToListMaybe xs - ys' <- stringToListMaybe ys - guard (length xs' > 2 && length xs' == length ys') - return (zip xs' ys') -parseArgs _ = Nothing - -printPoint :: Point -> IO () -printPoint (x, y) = putStrLn $ "(" ++ show x ++ ", " ++ show y ++ ")" - -main :: IO () -main = do - args <- getArgs - case parseArgs args of - Nothing -> putStrLn "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")" - Just coords -> forM_ (jarvis coords) printPoint - -``` - -{% endraw %} - -Convex Hull in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/index.md b/docs/projects/convex-hull/index.md deleted file mode 100644 index 2a8c164b73..0000000000 --- a/docs/projects/convex-hull/index.md +++ /dev/null @@ -1,150 +0,0 @@ ---- -date: 2019-10-22 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-23 -layout: default -tags: -- convex-hull -title: Convex Hull -title1: Convex -title2: Hull ---- - - - -Welcome to the Convex Hull page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Suppose you have a set of points in the plane. The **convex hull** of this set is the smallest -convex polygon that contains all the points. - -A good way to visualize the problem is this: Imagine each point is a nail sticking out of the plane, -and you stretch a rubber band around them and let it go. The band will contract and assume a shape -that encloses the nails. This shape is the convex hull. - -Note that all vertices of the convex hull are points in the original set. So the convex hull is really -a subset of points from the original set, and there may be points that lie inside the polygon but are -not vertices of the convex hull. - - -## Requirements - -Write a program that receives two command line arguments: strings in the form `x1, x2, x3 ...` and -`y1, y2, y3 ...` respectively, where `(xi, yi)` are the coordinates of the i-th point of the set. - -Your program should be able to parse these lists into some internal representation in your choice -language (ideally an array). From there, the program should compute the convex hull of the set of points, -and output a list in the form - - (x1, y1) - (x2, y2) - ... - -where `(xj, yj)` are the coordinates of the j-th vertex of the convex hull. - -There are many algorithms to solve this problem. You may implement any of them. -Check this [great document by Jeff Erickson][2] for more details about the -problem and the different algorithms to solve it. - -[2]: https://jeffe.cs.illinois.edu/pubs/pdf/convex.pdf - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Convex Hull. -In order to keep things simple, we split up the testing as follows: - -- Convex Hull Valid Tests -- Convex Hull Invalid Tests - -### Convex Hull Valid Tests - -| Description | Input X | Input Y | Output | -| ----------- | ------- | ------- | ------ | -| Sample Input: Triangle | "100, 180, 240" | "220, 120, 20" | "(100, 220)"
"(240, 20)"
"(180, 120)" | -| Sample Input: Pentagon | "100, 140, 320, 480, 280" | "240, 60, 40, 200, 300" | "(100, 240)"
"(140, 60)"
"(320, 40)"
"(480, 200)"
"(280, 300)" | -| Sample Input: Cluster | "260, 280, 300, 320, 600, 360, 20, 240" | "160, 100, 180, 140, 160, 320, 200, 0" | "(20, 200)"
"(240, 0)"
"(600, 160)"
"(360, 320)" | - -### Convex Hull Invalid Tests - -| Description | Input X | Input Y | -| ----------- | ------- | ------- | -| No Input | | | -| Missing Y | "100, 180, 240" | | -| Invalid Shape | "100, 180" | "240, 300" | -| Different Cardinality | "100, 180, 240" | "240, 60, 40, 200, 300" | -| Invalid Integers | "100, 1A0, 240" | "220, 120, 20" | - -All of these tests should output the following: - -``` -Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210") -``` - - -## Articles - -There are 28 articles: - -- [Convex Hull in ALGOL 60](/projects/convex-hull/algol60) -- [Convex Hull in ALGOL 68](/projects/convex-hull/algol68) -- [Convex Hull in AWK](/projects/convex-hull/awk) -- [Convex Hull in Ada](/projects/convex-hull/ada) -- [Convex Hull in Beef](/projects/convex-hull/beef) -- [Convex Hull in C](/projects/convex-hull/c) -- [Convex Hull in C#](/projects/convex-hull/c-sharp) -- [Convex Hull in C++](/projects/convex-hull/c-plus-plus) -- [Convex Hull in COBOL](/projects/convex-hull/cobol) -- [Convex Hull in Commodore BASIC](/projects/convex-hull/commodore-basic) -- [Convex Hull in Euphoria](/projects/convex-hull/euphoria) -- [Convex Hull in F#](/projects/convex-hull/f-sharp) -- [Convex Hull in Go](/projects/convex-hull/go) -- [Convex Hull in Haskell](/projects/convex-hull/haskell) -- [Convex Hull in Java](/projects/convex-hull/java) -- [Convex Hull in JavaScript](/projects/convex-hull/javascript) -- [Convex Hull in Mathematica](/projects/convex-hull/mathematica) -- [Convex Hull in PHP](/projects/convex-hull/php) -- [Convex Hull in Pascal](/projects/convex-hull/pascal) -- [Convex Hull in PowerShell](/projects/convex-hull/powershell) -- [Convex Hull in Python](/projects/convex-hull/python) -- [Convex Hull in Ruby](/projects/convex-hull/ruby) -- [Convex Hull in Rust](/projects/convex-hull/rust) -- [Convex Hull in Swift](/projects/convex-hull/swift) -- [Convex Hull in Tcl](/projects/convex-hull/tcl) -- [Convex Hull in TypeScript](/projects/convex-hull/typescript) -- [Convex Hull in Visual Basic](/projects/convex-hull/visual-basic) -- [Convex Hull in m4](/projects/convex-hull/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/convex-hull/java/index.md b/docs/projects/convex-hull/java/index.md deleted file mode 100644 index 9d16367ff9..0000000000 --- a/docs/projects/convex-hull/java/index.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -authors: -- Jeremy Grifski -- jsonW0 -date: 2019-10-28 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- convex-hull -- java -title: Convex Hull in Java -title1: Convex Hull -title2: in Java ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -public class ConvexHull { - public static void main(String[] args) { - if (args.length < 2) - System.out.println( - "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")"); - else { - String xInput = args[0]; - String yInput = args[1]; - String[] tempX = xInput.split(", "); - String[] tempY = yInput.split(", "); - if (tempX.length != tempY.length || tempX.length < 3) { - System.out.println( - "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")"); - return; - } - Point[] points = new Point[tempX.length]; - int minX = Integer.MAX_VALUE; - int mindex = 0; - for (int a = 0; a < tempX.length; a++) { - if (!tempX[a].matches("-?\\d+") || !tempY[a].matches("-?\\d+")) { - System.out.println( - "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")"); - return; - } - points[a] = new Point(Integer.parseInt(tempX[a]), Integer.parseInt(tempY[a])); - if (points[a].x <= minX) { - minX = points[a].x; - mindex = a; - } - } - Stack result = new Stack(); - int considerdex = mindex; - do { - result.push(points[considerdex]); - int nextdex = (considerdex + 1) % points.length; - for (int contenderdex = 0; contenderdex < points.length; contenderdex++) { - if (isCounterClockwise(points[considerdex], points[nextdex], points[contenderdex])) - nextdex = contenderdex; - } - considerdex = nextdex; - } while (considerdex != mindex); - int k = result.size(); - for (int a = 0; a < k; a++) { - System.out.println(result.pop().toString()); - } - } - } - - public static boolean isCounterClockwise(Point a, Point b, Point c) { - return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x); - } -} - -class Point { - public int x; - public int y; - - public Point(int a, int b) { - x = a; - y = b; - } - - public String toString() { - return "(" + x + ", " + y + ")"; - } -} -``` - -{% endraw %} - -Convex Hull in [Java](/languages/java) was written by: - -- Jeremy Grifski -- jsonW0 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/javascript/index.md b/docs/projects/convex-hull/javascript/index.md deleted file mode 100644 index a161bfaec0..0000000000 --- a/docs/projects/convex-hull/javascript/index.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -authors: -- Griffin Annshual -- rzuckerm -date: 2023-11-01 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- convex-hull -- javascript -title: Convex Hull in JavaScript -title1: Convex Hull -title2: in JavaScript ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -/** - * Calculate the Convex Hull of a set of 2D points using Graham's Scan algorithm. - * - * @param {Array} points - An array of 2D points represented as objects with x and y properties. - * @returns {Array} - An array of points on the convex hull in counter-clockwise order. - */ -function convexHull(points) { - function orientation(p, q, r) { - const val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); - if (val === 0) return 0; - return val > 0 ? 1 : -1; - } - - const n = points.length - if (n < 3) return points; - - let minPointIndex = 0; - for (let i = 0; i < n; i++) { - if ( - (points[i].y < points[minPointIndex].y) || - (points[i].y == points[minPointIndex].y && points[i].x < points[minPointIndex].x) - ) { - minPointIndex = i; - } - } - const sortedPoints = [...points].sort((a, b) => { - const angleA = Math.atan2(a.y - points[minPointIndex].y, a.x - points[minPointIndex].x); - const angleB = Math.atan2(b.y - points[minPointIndex].y, b.x - points[minPointIndex].x); - return angleA - angleB; - }) - - const convexHull = [sortedPoints[0], sortedPoints[1]]; - - for (let i = 2; i < n; i++) { - while ( - convexHull.length > 1 && - orientation( - convexHull[convexHull.length - 2], - convexHull[convexHull.length - 1], - sortedPoints[i] - ) !== -1 - ) { - convexHull.pop(); - } - convexHull.push(sortedPoints[i]); - } - - return convexHull; -} - -/** - * Executable function for Convex Hull calculation with command-line input. - * - * @param {string} inputX - Comma-separated X coordinates as a string. - * @param {string} inputY - Comma-separated Y coordinates as a string. - */ -function main(inputX, inputY) { - if (inputX == undefined || inputY == undefined){ - inputX = " "; - inputY = " "; - } - const xArray = inputX.split(",").map(Number); - const yArray = inputY.split(",").map(Number); - - if ( - xArray.length < 3 || - yArray.length < 3 || - xArray.length !== yArray.length || - xArray.some(item => isNaN(item))|| yArray.some(item => isNaN(item)) - ) { - console.log( - 'Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")' - ); - return; - } - - const points = xArray.map((x, i) => ({ x, y: yArray[i] })); - - const convexHullResult = convexHull(points); - convexHullResult.forEach((point) => console.log(`(${point.x}, ${point.y})`)); -} - -// Run the executable function with command-line arguments -const inputX = process.argv[2]; -const inputY = process.argv[3]; -main(inputX, inputY); - -``` - -{% endraw %} - -Convex Hull in [JavaScript](/languages/javascript) was written by: - -- Griffin Annshual -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/m4/index.md b/docs/projects/convex-hull/m4/index.md deleted file mode 100644 index c1f2ceb36e..0000000000 --- a/docs/projects/convex-hull/m4/index.md +++ /dev/null @@ -1,245 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-11-14 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2025-11-14 -layout: default -tags: -- convex-hull -- m4 -title: Convex Hull in m4 -title1: Convex -title2: Hull in m4 ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210") -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl 2D versions of "array_get" and "array_set" -dnl array2_get(varname, idx1, idx2) -define(`array2_get', `defn(format(``%s[%s][%s]'', `$1', `$2', `$3'))') - -dnl array2_set(varname, idx1, idx2, value) -define(`array2_set', `define(format(``%s[%s][%s]'', `$1', `$2', `$3'), `$4')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl form_points(x_varname, y_varname, points_varname): -dnl points_varname["length"] = x_varname["length"] -dnl for i = 0 to points_varname["length"] - 1: -dnl points_varname[i]["x"] = x_varname[i] -dnl points_varname[i]["y"] = y_varname[i] -define(`form_points', -`array_set(`$3', `length', array_get(`$1', `length'))dnl -_form_points(`$1', `$2', `$3', 0)dnl -'dnl -) - -dnl x_varname=$1, y_varname=$2, points_varname=$3, i=$4 -define(`_form_points', -`ifelse(eval($4 < array_get(`$1', `length')), 1, -`array2_set(`$3', `$4', `x', array_get(`$1', `$4'))dnl -array2_set(`$3', `$4', `y', array_get(`$2', `$4'))dnl -_form_points(`$1', `$2', `$3', incr($4))dnl -'dnl -)'dnl -) - -dnl show_points(points_varname): -dnl for i = 0 to points_varname["length"] - 1 -dnl Output "(" + points_varname[i]["x"] + ", " + points_varname[i]["y"] + ")" -define(`show_points', `_show_points(`$1', 0)') - -dnl points_varname=$1, i=$2 -define(`_show_points', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`(array2_get(`$1', `$2', `x'), array2_get(`$1', `$2', `y')) -_show_points(`$1', incr($2))dnl -'dnl -)'dnl -) - -dnl Find Convex Hull using Jarvis' algorithm -dnl Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/ -dnl convex_hull(points_varname, hull_points_varname): -dnl // The first point is the leftmost point with the highest y-coord in the -dnl // event of a tie -dnl l = find_leftmost_point(points_varname) -dnl -dnl // Repeat until wrapped around to first hull point -dnl p = l -dnl i = 0 -dnl do -dnl // Store convex hull point -dnl hull_points_varname[i]["x"] = points_varname[p]["x"] -dnl hull_points_varname[i]["y"] = points_varname[p]["y"] -dnl i = i + 1 -dnl hull_points_varname["length"] = i -dnl -dnl q = (p + 1) % points_varname["length"] -dnl for j = 0 to points_varname["length"] - 1: -dnl // If point j is counter-clockwise, then update end point (q) -dnl if orientation(points_varname, p, j, q) < 0: -dnl q = j -dnl -dnl p = q -dnl while p != l -define(`convex_hull', -`pushdef(`l', `find_leftmost_point(`$1')')dnl -pushdef(`p', l)dnl -pushdef(`q', `')dnl -_convex_hull_outer(`$1', `$2', 0)dnl -popdef(`q')dnl -popdef(`p')dnl -popdef(`l')dnl -'dnl -) - -dnl points_varname=$1, hull_points_varname=$2, i=$3 -define(`_convex_hull_outer', -`array2_set(`$2', `$3', `x', array2_get(`$1', p, `x'))dnl -array2_set(`$2', `$3', `y', array2_get(`$1', p, `y'))dnl -array_set(`$2', `length', incr($3))dnl -define(`q', eval((p + 1) % array_get(`$1', `length')))dnl -_convex_hull_inner(`$1', 0)dnl -define(`p', q)dnl -ifelse(eval(p != l), 1, `_convex_hull_outer(`$1', `$2', incr($3))')dnl -'dnl -) - -dnl points_varname=$1, j=$2 -define(`_convex_hull_inner', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`ifelse(eval(orientation(`$1', p, `$2', q) < 0), 1, `define(`q', `$2')')dnl -_convex_hull_inner(`$1', incr($2))dnl -'dnl -)'dnl -) - -dnl Get orientation of three points -dnl -dnl 0 = points are in a line -dnl > 0 = points are clockwise -dnl < 0 = points are counter-clockwise -dnl orientation(points_varname, p, q, r): -dnl return (points_varname[q]["y"] - points_varname[p]["y"]) * -dnl (points_varname[r]["x"] - points_varname[q]["x"]) - -dnl (points_varname[q]["x"] - points_varname[p]["x"]) * -dnl (points_varname[r]["y"] - points_varname[q]["y"]) -define(`orientation', -`eval( -(array2_get(`$1', `$3', `y') - array2_get(`$1', `$2', `y')) * -(array2_get(`$1', `$4', `x') - array2_get(`$1', `$3', `x')) - -(array2_get(`$1', `$3', `x') - array2_get(`$1', `$2', `x')) * -(array2_get(`$1', `$4', `y') - array2_get(`$1', `$3', `y')) -)'dnl -) - -dnl M4 does not have infinity so choose smallest integer value as minus infinity -dnl and the largest integer value for infinity -define(`MINUS_INF', -2147483648) -define(`INF', 2147483647) - -dnl find_leftmost_point(points_varname): -dnl x_min = INF -dnl y_max = MINUS_INF -dnl min_idx = -1 -dnl for i = 0 to points_varname["length"] - 1: -dnl if points_varname[i]["x"] < x_min or -dnl (points_varname[i]["x"] == x_min and points_varname[i]["y"] > y_max): -dnl x_min = points_varname[i]["x"] -dnl y_max = points_varname[i]["y"] -dnl min_idx = i -dnl return min_idx -define(`find_leftmost_point', `_find_leftmost_point(`$1', INF, MINUS_INF, -1, 0)') - -dnl points_varname=$1, x_min=$2, y_max=$3, min_idx=$4, i=$5 -define(`_find_leftmost_point', -`ifelse(eval($5 >= array_get(`$1', `length')), 1, `$4', -`ifelse(eval(array2_get(`$1', `$5', `x') < $2 || -(array2_get(`$1', `$5', `x') == $2 && array2_get(`$1', `$5', `y') > $3)), 1, -`_find_leftmost_point(`$1', array2_get(`$1', `$5', `x'), array2_get(`$1', `$5', `y'), $5, incr($5))', -`_find_leftmost_point(`$1', `$2', `$3', `$4', incr($5))'dnl -)'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 2 || - !parse_int_list(`x_values', ARGV1) || - !parse_int_list(`y_values', ARGV2) -), 1, `show_usage()')dnl -ifelse(eval(array_get(`x_values', `length') < 3 || - array_get(`y_values', `length') < 3 || - array_get(`x_values', `length') != array_get(`y_values', `length') -), 1, `show_usage()')dnl -form_points(`x_values', `y_values', `points')dnl -convex_hull(`points', `hull_points')dnl -show_points(`hull_points')dnl - -``` - -{% endraw %} - -Convex Hull in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/mathematica/index.md b/docs/projects/convex-hull/mathematica/index.md deleted file mode 100644 index b1f594809a..0000000000 --- a/docs/projects/convex-hull/mathematica/index.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-18 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2023-01-18 -layout: default -tags: -- convex-hull -- mathematica -title: Convex Hull in Mathematica -title1: Convex Hull in -title2: Mathematica ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Convex hull option convexHull1 is based on the built-in ConvexHullMesh: *) - -convexHull1 = Function[{ps}, - Module[{mesh = ConvexHullMesh[ps]}, - Round /@ Part[ - MeshCoordinates[mesh], - First[First[MeshCells[mesh, 2]]]]]]; - -(* If that is considered cheating, then option convexHull2 implements it directly using Jarvis' algorithm: *) - -convexHull2 = Function[{inputList}, - Module[{orientation, l = inputList, i, j}, - (* compute the direction in which three vertices are oriented *) - orientation = Function[{a, b, c}, Det[{a - b, c - b}]]; - - (* keep sorting the convex hull vertices to the beginning of the list; - 'i' is the index of the last vertex in the convex hull; - 'j' is the index of the next vertex selected to be permuted to the front *) - For[ - (* initially *) - i = 0; (* no vertices selected into the convex hull *) - j = First[OrderingBy[l, First, 1]], (* find the first vertex by minimum x-coordinate *) - - (* continue as long as the next selected vertex is not already in the convex hull *) - j > i, - - (* iteration done in the body *), - - (* permute the next selected vertex to the front of the list *) - i++; - l = Permute[l, If[i != j, Cycles[{{i, j}}], {}]]; - - (* find the next vertex that is clockwise to all other vertices *) - - j = Mod[i + 1, Length[l], 1]; - Do[ (* for all vertices *) - (* if 'k' is such that 'i', 'j', 'k' are counterclockwise, let 'k' become the new 'j' *) - If[orientation @@ l[[{i, j, k}]] > 0, j = k], - {k, Length[l]}]; - ]; - (* return only the front part of the list containing the convex hull *) - Take[l, i]]]; - -(* The outer function provides the 'user interface' (e.g., the string parsing): *) - -convexHullMain = Function[{lx, ly}, - Module[{e = "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. \"100, 440, 210\")"}, - Catch[ - convexHull2[ - Transpose[ - If[MatrixQ[#] \[And] Length[First[#]] >= 3, - #, Throw[e]] &[ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct two arguments to convexHull: list of x coordinates, list of y coordinates *) - {StringSplit[lx, ", "], StringSplit[ly, ", "]}, - {-1} (* at each leaf *)]]]]]]]; - - -(* Valid Tests *) - -Print /@ Apply[convexHullMain] /@ { - {"100, 180, 240", "220, 120, 20"}, - {"100, 140, 320, 480, 280", "240, 60, 40, 200, 300"}, - {"260, 280, 300, 320, 600, 360, 20, 240", - "160, 100, 180, 140, 160, 320, 200, 0"} - }; - - -(* Invalid Tests *) - -convexHullMain["100, 180", "240, 60, 40, 200, 300"] -convexHullMain["100, 180, 240", "240, 60, 40, 200, 300"] -convexHullMain["100, 180, 240", ""] -convexHullMain["100, 1A0, 240", "220, 120, 20"] - -``` - -{% endraw %} - -Convex Hull in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/pascal/index.md b/docs/projects/convex-hull/pascal/index.md deleted file mode 100644 index ffdee9312e..0000000000 --- a/docs/projects/convex-hull/pascal/index.md +++ /dev/null @@ -1,243 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- convex-hull -- pascal -title: Convex Hull in Pascal -title1: Convex Hull -title2: in Pascal ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program ConvexHull; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - Sysutils; - -type - TPoint = record - X, Y: integer; - end; - - TPointList = specialize TList; - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim.IsEmpty then - ShowUsage; - - Tokens := S.Split([',']); - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; - - if Result.Count < 3 then - begin - Result.Free; - ShowUsage; - end; -end; - -function CheckListLengths(const Xs, Ys: TIntegerList): boolean; -begin - if Xs.Count <> Ys.Count then - Exit(False); - - if Xs.Count < 3 then - Exit(false); - - Result := True; -end; - -procedure QuickSortPoints(List: TPointList; Lo, Hi: integer); -var - i, j: integer; - Pivot, Temp: TPoint; - - procedure SwapElements(Index1, Index2: integer); - var - Temp: TPoint; - begin - Temp := List[Index1]; - List[Index1] := List[Index2]; - List[Index2] := Temp; - end; - -begin - while Lo < Hi do - begin - i := Lo; - j := Hi; - Pivot := List[Lo + (Hi - Lo) div 2]; - - repeat - while (List[i].X < Pivot.X) or ((List[i].X = Pivot.X) and - (List[i].Y < Pivot.Y)) do - Inc(i); - while (List[j].X > Pivot.X) or ((List[j].X = Pivot.X) and - (List[j].Y > Pivot.Y)) do - Dec(j); - - if i <= j then - begin - SwapElements(i, j); - Inc(i); - Dec(j); - end; - until i > j; - - if (j - Lo) < (Hi - i) then - begin - if Lo < j then QuickSortPoints(List, Lo, j); - Lo := i; - end - else - begin - if i < Hi then QuickSortPoints(List, i, Hi); - Hi := j; - end; - end; -end; - -function Cross(const O, A, B: TPoint): int64; -begin - Result := int64(A.X - O.X) * (B.Y - O.Y) - int64(A.Y - O.Y) * (B.X - O.X); -end; - -procedure BuildHull(const Points: TPointList; Hull: TPointList); -var - PointCount, i: integer; - CurrentIndex, NextIndex, LeftmostIndex: integer; -begin - PointCount := Points.Count; - if PointCount < 3 then - begin - Hull.AddRange(Points); - Exit; - end; - - // Find the leftmost point (with lowest X; if tie, highest Y) - LeftmostIndex := 0; - for i := 1 to PointCount - 1 do - if (Points[i].X < Points[LeftmostIndex].X) or - ((Points[i].X = Points[LeftmostIndex].X) and - (Points[i].Y > Points[LeftmostIndex].Y)) then - LeftmostIndex := i; - - CurrentIndex := LeftmostIndex; - repeat - Hull.Add(Points[CurrentIndex]); - - NextIndex := (CurrentIndex + 1) mod PointCount; - for i := 0 to PointCount - 1 do - if Cross(Points[CurrentIndex], Points[i], Points[NextIndex]) < 0 then - NextIndex := i; - - CurrentIndex := NextIndex; - until CurrentIndex = LeftmostIndex; -end; - -var - Xs, Ys: TIntegerList; - Points, Hull: TPointList; - i: integer; - Pt: TPoint; -begin - if ParamCount <> 2 then - ShowUsage; - - Xs := ParseIntegerList(ParamStr(1)); - Ys := ParseIntegerList(ParamStr(2)); - - if not CheckListLengths(Xs, Ys) then - begin - Xs.Free; - Ys.Free; - ShowUsage; - end; - - Points := TPointList.Create; - Hull := TPointList.Create; - try - for i := 0 to Xs.Count - 1 do - begin - Pt.X := Xs[i]; - Pt.Y := Ys[i]; - Points.Add(Pt); - end; - - QuickSortPoints(Points, 0, Points.Count - 1); - BuildHull(Points, Hull); - - for i := 0 to Hull.Count - 1 do - Writeln('(', Hull[i].X, ', ', Hull[i].Y, ')'); - - finally - Xs.Free; - Ys.Free; - Points.Free; - Hull.Free; - end; -end. - -``` - -{% endraw %} - -Convex Hull in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/php/index.md b/docs/projects/convex-hull/php/index.md deleted file mode 100644 index 5bbc8b991c..0000000000 --- a/docs/projects/convex-hull/php/index.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2023-03-27 -layout: default -tags: -- convex-hull -- php -title: Convex Hull in PHP -title1: Convex Hull -title2: in PHP ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -// Combine values into a set of points -function form_points($x_values, $y_values) -{ - return array_map( - function ($x, $y) { return new Point($x, $y); }, - $x_values, $y_values - ); -} - -// Find Convex Hull using Jarvis' algorithm -// Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/ -function convex_hull($points) -{ - $n = count($points); - - // Initialize hull points - $hull_points = array(); - - // The first point is the leftmost point with the highest y-coord in the - // event of a tie - $l = find_leftmost_point($points); - - // Repeat until wrapped around to first hull point - $p = $l; - do - { - // Store convex hull point - array_push($hull_points, $points[$p]); - - $q = ($p + 1) % $n; - for ($j = 0; $j < $n; $j++) - { - // If point j is more counter-clockwise, then update end point (q) - if (orientation($points[$p], $points[$j], $points[$q]) < 0) - { - $q = $j; - } - } - - $p = $q; - } - while ($p != $l); - - return $hull_points; -} - -function find_leftmost_point($points) -{ - $n = count($points); - $leftmost_point = new Point(PHP_INT_MAX, PHP_INT_MIN); - $leftmost_index = 0; - foreach ($points as $k => $point) - { - // In the event of a tie, pick the point with the greater y-coord - if ( - $point->x < $leftmost_point->x or - ($point->x == $leftmost_point->x and $point->y > $leftmost_point->y) - ) - { - $leftmost_point = $point; - $leftmost_index = $k; - } - } - - return $leftmost_index; -} - -// Get orientation of three points -// -// 0 = points are in a line -// > 0 = points are clockwise -// < 0 = points are counter-clockwise -function orientation($p, $q, $r) -{ - return ( - ($q->y - $p->y) * ($r->x - $q->x) - - ($q->x - $p->x) * ($r->y - $q->y) - ); -} - - -function show_points($points) -{ - foreach ($points as $point) - { - printf("%s\n", $point->to_string()); - } -} - -class Point -{ - public $x; - public $y; - - public function __construct($x, $y) - { - $this->x = $x; - $this->y = $y; - } - - public function to_string() - { - return "({$this->x}, {$this->y})"; - } -} - -// Exit if too few arguments -if (count($argv) < 3 || empty($argv[1]) || empty($argv[2])) -{ - usage(); -} - -// Exit if 1st or 2nd argument invalid -$x_values = parse_int_array($argv[1]); -$y_values = parse_int_array($argv[2]); -if ($x_values === FALSE || $y_values === FALSE) -{ - usage(); -} - -// Exit if not same number of points or less than 3 points -$num_x = count($x_values); -$num_y = count($y_values); -if ($num_x != $num_y || $num_x < 3) -{ - usage(); -} - -// Combine values into set of points -$points = form_points($x_values, $y_values); - -// Get convex hull of points and show points -$hull_points = convex_hull($points); -show_points($hull_points); - -``` - -{% endraw %} - -Convex Hull in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/powershell/index.md b/docs/projects/convex-hull/powershell/index.md deleted file mode 100644 index 5bc4218e01..0000000000 --- a/docs/projects/convex-hull/powershell/index.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-28 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2025-07-28 -layout: default -tags: -- convex-hull -- powershell -title: Convex Hull in PowerShell -title1: Convex Hull -title2: in PowerShell ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -class Point { - [int]$X - [int]$Y - - Point([int]$x, [int]$y) { - $this.X = $x - $this.Y = $y - } - - [string] ToString() { - return "($($this.X), $($this.Y))" - } -} - -function Get-Points([int[]]$X, [int[]]$Y) { - @(0..($X.Length - 1) | ForEach-Object { [Point]::new($X[$_], $Y[$_]) }) -} - -# Find Convex Hull using Jarvis' algorithm -# Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/ -function Invoke-ConvexHull([Point[]]$Points) { - $n = $Points.Length - - # The first point is the leftmost point with the highest y-coord in the event of a tie - $l = Find-LeftmostPoint $Points - - # Repeat until wrapped around to first hull point - $p = $l - do { - # Output convex hull point - $Points[$p] - - $q = ($p + 1) % $n - for ($j = 0; $j -lt $n; $j++) { - # If point j is more counter-clockwise, then update end point (q) - if ((Get-Orientation $Points[$p] $Points[$j] $Points[$q]) -lt 0) { - $q = $j - } - } - - $p = $q - } while ($p -ne $l) -} - -function Find-LeftmostPoint([Point[]]$Points) { - $leftmostPoint = [Point]::new([int]::MaxValue, [int]::MinValue) - $leftmostIndex = 0 - for ($i = 0; $i -lt $Points.Length; $i++) { - # In the event of a tie, pick the point with the greater y-coord - if ($Points[$i].X -lt $leftmostPoint.X -or - ($Points[$i].X -eq $leftmostPoint.X -and $Points[$i].Y -gt $leftmostPoint.Y) - ) { - $leftmostPoint = $Points[$i] - $leftmostIndex = $i - } - } - - $leftmostIndex -} - -# Get orientation of three points -# -# 0 = points are in a line -# > 0 = points are clockwise -# < 0 = points are counter-clockwise -function Get-Orientation([Point]$P, [Point]$Q, [Point]$R) { - ($Q.Y - $P.Y) * ($R.X - $Q.X) - ($Q.X - $P.X) * ($R.Y - $Q.Y) -} - -if ($args.Length -lt 2 -or -not $args[0] -or -not $args[1]) { - Show-Usage -} - -try { - $x = Parse-IntList $args[0] - $y = Parse-IntList $args[1] - if ($x.Length -ne $y.Length -or $x.Length -lt 3) { - Show-Usage - } -} catch { - Show-Usage -} - -# Combine values into set of points -$points = Get-Points $X $Y - -# Get convex hull of points and show them -$hullPoints = Invoke-ConvexHull $points -Write-Output ($hullPoints -join "`n") - -``` - -{% endraw %} - -Convex Hull in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/python/index.md b/docs/projects/convex-hull/python/index.md deleted file mode 100644 index 33170c546f..0000000000 --- a/docs/projects/convex-hull/python/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Vicrobot -date: 2019-10-22 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2022-05-14 -layout: default -tags: -- convex-hull -- python -title: Convex Hull in Python -title1: Convex Hull -title2: in Python ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -from math import sqrt -import sys - -usage = 'Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")' - - -def dist(point1, point2): - x1, y1 = point1 - x2, y2 = point2 - return sqrt(abs((x2 - x1)**2 + (y2 - y1)**2)) - - -def farthest(point, set_of_points): - d = [(dist(point, i), i) for i in set_of_points] - d = list(set(d)) - d = sorted(d, reverse=True) - return d[0][1] - - -def orient(point1, point2, point3): - x1, y1 = point1 - x2, y2 = point2 - x3, y3 = point3 - val = ((x2-x1) * (y3-y1)) - ((y2 - y1) * (x3-x1)) - if val == 0: - return 0 - elif val > 0: - return 1 - else: - return 2 - - -def next_hurdle(setofpoints, pivot, final_list): - z = setofpoints - final_list = final_list[1:] - k = [] - for i in z: - if i in final_list: - continue - bool1 = 1 - for j in z: - if orient(pivot, i, j) == 1: - bool1 = 0 - break - if bool1 == 1: - k.append(i) - return farthest(pivot, k) - - -def foo(z): - final_list = [] - topmost = [(i, j) for i, j in z if j == max(Y)] - v1 = sorted(topmost)[0] - final_list.append(v1) - next_point = v1[0], v1[1] + 1 - pivot = v1 - while next_point != v1: - next_point = next_hurdle(z, pivot, final_list) - pivot = next_point - final_list.append(next_point) - return final_list - - -if __name__ == '__main__': - if len(sys.argv) != 3: - print(usage) - sys.exit() - - X = [i.strip() for i in sys.argv[1].split(',') if i] - Y = [i.strip() for i in sys.argv[2].split(',') if i] - - if len(X) != len(Y) or len(X) < 3 or not all(x.isdigit() for x in X) or not all(y.isdigit() for y in Y): - print(usage) - sys.exit() - - X = [int(i) for i in X] - Y = [int(i) for i in Y] - Z = list(set((zip(X, Y)))) - - convex_polygon_coords = foo(Z) - for coord in convex_polygon_coords: - print(coord) - -``` - -{% endraw %} - -Convex Hull in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Vicrobot - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/ruby/index.md b/docs/projects/convex-hull/ruby/index.md deleted file mode 100644 index 1038d971da..0000000000 --- a/docs/projects/convex-hull/ruby/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- convex-hull -- ruby -title: Convex Hull in Ruby -title1: Convex Hull -title2: in Ruby ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = 'Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")' - -def usage! - warn USAGE - exit 1 -end - -def parse_list(str) - str.split(",").map { Integer(it.strip) } -rescue ArgumentError, NoMethodError - usage! -end - -def cross(o, a, b) - (a[0] - o[0]) * (b[1] - o[1]) - - (a[1] - o[1]) * (b[0] - o[0]) -end - -def build_hull(points) - hull = [] - - points.each do |p| - hull.pop while hull.size >= 2 && cross(hull[-2], hull[-1], p) <= 0 - hull << p - end - - hull -end - -def convex_hull(points) - points = points.sort - - lower = build_hull(points) - upper = build_hull(points.reverse) - - lower + upper[1..-2] -end - -x_str, y_str = ARGV -usage! if x_str.nil? || y_str.nil? - -x = parse_list(x_str) -y = parse_list(y_str) - -usage! if x.size != y.size || x.size < 3 - -points = x.zip(y) - -convex_hull(points).each do |x, y| - puts "(#{x}, #{y})" -end - -``` - -{% endraw %} - -Convex Hull in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/rust/index.md b/docs/projects/convex-hull/rust/index.md deleted file mode 100644 index a664b5880d..0000000000 --- a/docs/projects/convex-hull/rust/index.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-22 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- convex-hull -- rust -title: Convex Hull in Rust -title1: Convex Hull -title2: in Rust ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::fmt; - -fn usage() -> ! { - println!( - "Usage: please provide at least 3 x and y coordinates as separate lists \ - (e.g. \"100, 440, 210\")" - ); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -#[derive(Clone, Copy)] -struct Point { - x: i32, - y: i32, -} - -impl Point { - fn new(x: i32, y: i32) -> Self { - Self {x: x, y: y} - } -} - -impl fmt::Debug for Point { - // Show point - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "({}, {})", self.x, self.y) - } -} - -fn form_points(x_values: &Vec, y_values: &Vec) -> Vec { - x_values.iter() - .zip(y_values.iter()) - .map(|(x, y)| Point::new(*x, *y)) - .collect() -} - -// Find Convex Hull using Jarvis' algorithm -// Source: https://www.geeksforgeeks.org/convex-hull-using-jarvis-algorithm-or-wrapping/ -fn convex_hull(points: &Vec) -> Vec { - let n = points.len(); - - // Initialize hull points - let mut hull_points: Vec = vec![]; - - // The first point is the leftmost point with the highest y-coord in the - // event of a tie - let l = points.iter() - .enumerate() - .map(|(n, point)| (point.x, -point.y, n)) - .min() - .unwrap() - .2; - - // Repeat until wrapped around to first hull point - let mut p = l; - loop { - // Store convex hull point - hull_points.push(points[p]); - - let mut q = (p + 1) % n; - for j in 0..n { - // If point j is more counter-clockwise, then update end point (q) - if orientation(&points[p], &points[j], &points[q]) < 0 { - q = j; - } - } - - p = q; - if p == l { - break; - } - } - - hull_points -} - -// Get orientation of three points -// -// 0 = points are in a line -// > 0 = points are clockwise -// < 0 = points are counter-clockwise -fn orientation(p: &Point, q: &Point, r: &Point) -> i32 { - (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y) -} - -fn show_points(points: &Vec) { - for point in points { - println!("{point:?}"); - } -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let x_values: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 2nd command-line argument to list of integers - let y_values: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if not same number of points or less than 3 points - let num_x = x_values.len(); - let num_y = y_values.len(); - if num_x != num_y || num_x < 3 || num_y < 3 { - usage(); - } - - // Combine values into set of points - let points: Vec = form_points(&x_values, &y_values); - - // Get convex hull of points and show points - let hull_points = convex_hull(&points); - show_points(&hull_points); -} - -``` - -{% endraw %} - -Convex Hull in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/swift/index.md b/docs/projects/convex-hull/swift/index.md deleted file mode 100644 index 432e74d384..0000000000 --- a/docs/projects/convex-hull/swift/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- convex-hull -- swift -title: Convex Hull in Swift -title1: Convex Hull -title2: in Swift ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210") - """ - -struct Point: Comparable { - let x: Int - let y: Int - - static func < (lhs: Point, rhs: Point) -> Bool { - return lhs.x < rhs.x || (lhs.x == rhs.x && lhs.y < rhs.y) - } -} - -enum Orientation { - case clockwise, counterClockwise, collinear -} - -func orientation(_ a: Point, _ b: Point, _ c: Point) -> Orientation { - let value = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x) - - if value == 0 { return .collinear } - return value > 0 ? .counterClockwise : .clockwise -} - -func convexHull(from points: [Point]) -> [Point] { - guard points.count > 2 else { return points } - - let sorted = points.sorted() - - func buildHalfHull(_ points: [Point]) -> [Point] { - var hull: [Point] = [] - hull.reserveCapacity(points.count) - - for p in points { - while hull.count >= 2 - && orientation(hull[hull.count - 2], hull[hull.count - 1], p) - != .counterClockwise - { - hull.removeLast() - } - hull.append(p) - } - - return hull - } - - let lower = buildHalfHull(sorted) - let upper = buildHalfHull(sorted.reversed()) - - return lower.dropLast() + upper.dropLast() -} - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseList(_ input: String) -> [Int]? { - let parts = input.split(separator: ",") - let values = parts.map { Int($0.trimmed) } - - guard values.count >= 3, - values.allSatisfy({ $0 != nil }) - else { - return nil - } - - return values.compactMap { $0 } -} - -func parsePoints(from args: [String]) -> [Point]? { - guard args.count == 3, - let xs = parseList(args[1]), - let ys = parseList(args[2]), - xs.count == ys.count - else { return nil } - - return zip(xs, ys).map(Point.init) -} - -guard let points = parsePoints(from: CommandLine.arguments) else { - print(usage) - exit(1) -} - -print(convexHull(from: points).map { "(\($0.x), \($0.y))" }.joined(separator: "\n")) - -``` - -{% endraw %} - -Convex Hull in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/tcl/index.md b/docs/projects/convex-hull/tcl/index.md deleted file mode 100644 index a177896701..0000000000 --- a/docs/projects/convex-hull/tcl/index.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2025-10-08 -layout: default -tags: -- convex-hull -- tcl -title: Convex Hull in Tcl -title1: Convex Hull -title2: in Tcl ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")} - exit 1 -} - -proc parseList {s} { - set s [string trim $s] - if {$s eq ""} { - usage - } - - set tokens [split $s ","] - set result {} - - foreach token $tokens { - set t [string trim $token] - if {![string is integer -strict $token]} { usage } - lappend result [expr {$token}] - } - - if {[llength $result] < 3} { usage } - return $result -} - -if {$argc != 2} { usage } - -set xs [parseList [lindex $argv 0]] -set ys [parseList [lindex $argv 1]] - -if {[llength $xs] != [llength $ys]} { usage } - -set points {} -for {set i 0} {$i < [llength $xs]} {incr i} { - lappend points [list [lindex $xs $i] [lindex $ys $i]] -} - -proc cross {a b c} { - set x1 [expr {[lindex $b 0] - [lindex $a 0]}] - set y1 [expr {[lindex $b 1] - [lindex $a 1]}] - set x2 [expr {[lindex $c 0] - [lindex $a 0]}] - set y2 [expr {[lindex $c 1] - [lindex $a 1]}] - return [expr {$x1 * $y2 - $y1 * $x2}] -} - -proc pointCompare {a b} { - if {[lindex $a 0] < [lindex $b 0]} { return -1 } - if {[lindex $a 0] > [lindex $b 0]} { return 1 } - if {[lindex $a 1] < [lindex $b 1]} { return -1 } - if {[lindex $a 1] > [lindex $b 1]} { return 1 } - return 0 -} - -proc convexHull {points} { - set n [llength $points] - if {$n < 3} { return $points } - - set sorted [lsort -command pointCompare $points] - - set lower {} - foreach p $sorted { - while {[llength $lower] >= 2} { - set q [lindex $lower end-1] - set r [lindex $lower end] - if {[cross $q $r $p] > 0} { break } - set lower [lrange $lower 0 end-1] - } - lappend lower $p - } - - set upper {} - foreach p [lreverse $sorted] { - while {[llength $upper] >= 2} { - set q [lindex $upper end-1] - set r [lindex $upper end] - if {[cross $q $r $p] > 0} { break } - set upper [lrange $upper 0 end-1] - } - lappend upper $p - } - - set hull [concat [lrange $lower 0 end-1] [lrange $upper 0 end-1]] - return $hull -} - -set hull [convexHull $points] - -foreach pt $hull { - set x [string trim [lindex $pt 0]] - set y [string trim [lindex $pt 1]] - puts "($x, $y)" -} - - -``` - -{% endraw %} - -Convex Hull in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/typescript/index.md b/docs/projects/convex-hull/typescript/index.md deleted file mode 100644 index 2154b00162..0000000000 --- a/docs/projects/convex-hull/typescript/index.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- convex-hull -- typescript -title: Convex Hull in TypeScript -title1: Convex Hull -title2: in TypeScript ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -type Point = { x: number; y: number }; - -function getInputs(xArg?: string, yArg?: string): Point[] | null { - if (!xArg || !yArg) return null; - - const xParts = xArg.split(","); - const yParts = yArg.split(","); - - if (xParts.length !== yParts.length || xParts.length < 3) return null; - - const points: Point[] = []; - for (let i = 0; i < xParts.length; i++) { - const x = xParts[i].trim(); - const y = yParts[i].trim(); - - if (!/^-?\d+$/.test(x) || !/^-?\d+$/.test(y)) return null; - - points.push({ x: Number(x), y: Number(y) }); - } - - return points; -} - -const cross = (o: Point, a: Point, b: Point) => - (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x); - -function convexHull(points: Point[]): Point[] { - if (points.length <= 2) return points; - - points.sort((a, b) => a.x - b.x || a.y - b.y); - - const uniquePoints: Point[] = []; - for (let i = 0; i < points.length; i++) { - if ( - i === 0 || - points[i].x !== points[i - 1].x || - points[i].y !== points[i - 1].y - ) { - uniquePoints.push(points[i]); - } - } - - if (uniquePoints.length <= 2) return uniquePoints; - - const hull: Point[] = []; - - for (const p of uniquePoints) { - while ( - hull.length >= 2 && - cross(hull[hull.length - 2], hull[hull.length - 1], p) <= 0 - ) { - hull.pop(); - } - hull.push(p); - } - - const lowerHullLength = hull.length; - for (let i = uniquePoints.length - 2; i >= 0; i--) { - const p = uniquePoints[i]; - while ( - hull.length > lowerHullLength && - cross(hull[hull.length - 2], hull[hull.length - 1], p) <= 0 - ) { - hull.pop(); - } - hull.push(p); - } - - hull.pop(); - return hull; -} - -function main(): void { - const points = getInputs(process.argv[2], process.argv[3]); - - if (!points) { - console.error( - 'Usage: please provide at least 3 x and y coordinates as separate lists (e.g. "100, 440, 210")', - ); - process.exit(1); - } - - convexHull(points!).forEach((p) => console.log(`(${p.x}, ${p.y})`)); -} - -main(); - -``` - -{% endraw %} - -Convex Hull in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/convex-hull/visual-basic/index.md b/docs/projects/convex-hull/visual-basic/index.md deleted file mode 100644 index a2feeba3e6..0000000000 --- a/docs/projects/convex-hull/visual-basic/index.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: convex-hull-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- convex-hull -- visual-basic -title: Convex Hull in Visual Basic -title1: Convex Hull in -title2: Visual Basic ---- - - - -Welcome to the [Convex Hull](/projects/convex-hull) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Module ConvexHull - - Public Structure Point - Implements IComparable(Of Point) - - Public ReadOnly X As Integer - Public ReadOnly Y As Integer - - Public Sub New(x As Integer, y As Integer) - Me.X = x - Me.Y = y - End Sub - - Public Function CompareTo(other As Point) As Integer _ - Implements IComparable(Of Point).CompareTo - - Dim cx = X.CompareTo(other.X) - If cx <> 0 Then Return cx - Return Y.CompareTo(other.Y) - End Function - - Public Overrides Function ToString() As String - Return $"({X}, {Y})" - End Function - End Structure - - Sub Main(args As String()) - - If args.Length <> 2 Then - ShowUsage() - Return - End If - - Dim xCoords = ParseList(args(0)) - Dim yCoords = ParseList(args(1)) - - If xCoords Is Nothing OrElse yCoords Is Nothing OrElse - xCoords.Count <> yCoords.Count OrElse xCoords.Count < 3 Then - - ShowUsage() - Return - End If - - Dim points As New List(Of Point)(xCoords.Count) - - For i = 0 To xCoords.Count - 1 - points.Add(New Point(xCoords(i), yCoords(i))) - Next - - Dim hull = BuildHull(points) - - For Each p In hull - Console.WriteLine(p) - Next - - End Sub - - Private Function BuildHull(points As List(Of Point)) As List(Of Point) - - Dim n = points.Count - Dim hull As New List(Of Point) - - Dim start = 0 - For i = 1 To n - 1 - If points(i).CompareTo(points(start)) < 0 Then - start = i - End If - Next - - Dim current = start - - Do - hull.Add(points(current)) - - Dim nextIdx = If(current + 1 = n, 0, current + 1) - - For i = 0 To n - 1 - If Cross(points(current), points(i), points(nextIdx)) > 0 Then - nextIdx = i - End If - Next - - current = nextIdx - - Loop While current <> start - - Return hull - - End Function - - Private Function Cross(o As Point, a As Point, b As Point) As Long - Return CLng(a.X - o.X) * (b.Y - o.Y) - - CLng(a.Y - o.Y) * (b.X - o.X) - End Function - - Private Function ParseList(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - Return Nothing - End If - - Dim result As New List(Of Integer) - - For Each part In input.Split(","c) - - Dim value As Integer - - If Not Integer.TryParse(part.Trim(), value) Then - Return Nothing - End If - - result.Add(value) - - Next - - If result.Count < 3 Then - Return Nothing - End If - - Return result - - End Function - - Private Sub ShowUsage() - Console.Error.WriteLine( - "Usage: please provide at least 3 x and y coordinates as separate lists (e.g. ""100, 440, 210"")" - ) - End Sub - -End Module -``` - -{% endraw %} - -Convex Hull in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/ada/index.md b/docs/projects/depth-first-search/ada/index.md deleted file mode 100644 index d41c95e095..0000000000 --- a/docs/projects/depth-first-search/ada/index.md +++ /dev/null @@ -1,205 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-09 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-09 -layout: default -tags: -- ada -- depth-first-search -title: Depth First Search in Ada -title1: Depth First -title2: Search in Ada ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Containers; use Ada.Containers; -with Ada.Containers.Vectors; - -procedure Depth_First_Search is - Data_Format_Error : exception; - - package Integer_Lists is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - subtype Int_List is Integer_Lists.Vector; - type Boolean_Array is array (Natural range <>) of Boolean; - - function To_Int_List (Raw_Input : String) return Int_List is - Result : Int_List; - - function Clean_Item (S : String) return String is - Item : constant String := Trim (S, Ada.Strings.Both); - begin - if Item'Length = 0 then - raise Data_Format_Error; - end if; - return Item; - end Clean_Item; - - procedure Append_Item (S : String) is - begin - Result.Append (Integer'Value (Clean_Item (S))); - exception - when Constraint_Error => - raise Data_Format_Error; - end Append_Item; - - Start : Positive := Raw_Input'First; - Separator : Natural; - begin - if Raw_Input'Length = 0 then - raise Data_Format_Error; - end if; - - loop - Separator := Index (Raw_Input (Start .. Raw_Input'Last), ","); - - declare - Last_Index : constant Positive := - (if Separator = 0 then Raw_Input'Last else Separator - 1); - begin - Append_Item (Raw_Input (Start .. Last_Index)); - end; - - exit when Separator = 0; - Start := Separator + 1; - end loop; - - return Result; - end To_Int_List; - - function Cell - (Graph : Int_List; Rows : Natural; From, To : Natural) return Boolean - is (Graph.Element (From * Rows + To) = 1); - - function Has_Path_To - (Target : Integer; - Node : Natural; - Grid : Int_List; - Labels : Int_List; - Order : Natural; - Visited : in out Boolean_Array) return Boolean is - begin - if Visited (Node) then - return False; - end if; - - if Labels.Element (Node) = Target then - return True; - end if; - - Visited (Node) := True; - - for Neighbor in Visited'Range loop - if Cell (Grid, Order, Node, Neighbor) and then not Visited (Neighbor) - then - if Has_Path_To (Target, Neighbor, Grid, Labels, Order, Visited) - then - return True; - end if; - end if; - end loop; - - return False; - end Has_Path_To; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide a tree in an adjacency matrix form " - & "(""0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, " - & "0, 0, 1, 0, 0, 0, 0, 1, 0, 0"") together with a list of vertex values " - & "(""1, 3, 5, 2, 4"") and the integer to find (""4"")"); - end Print_Usage; - -begin - if Argument_Count /= 3 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - declare - Adjacency_Data : constant Int_List := To_Int_List (Argument (1)); - Vertex_Values : constant Int_List := To_Int_List (Argument (2)); - Target_Search : constant Integer := Integer'Value (Argument (3)); - Total_Cells : constant Natural := Natural (Adjacency_Data.Length); - Matrix_Size : constant Natural := - Natural (Sqrt (Float (Total_Cells))); - - begin - if Matrix_Size * Matrix_Size /= Total_Cells - or else Matrix_Size /= Natural (Vertex_Values.Length) - then - raise Data_Format_Error; - end if; - - declare - Seen : Boolean_Array (0 .. Matrix_Size - 1) := (others => False); - - Found : constant Boolean := - (Matrix_Size > 0 - and then - Has_Path_To - (Target => Target_Search, - Node => 0, - Grid => Adjacency_Data, - Labels => Vertex_Values, - Order => Matrix_Size, - Visited => Seen)); - - begin - if Found then - Put_Line ("true"); - else - Put_Line ("false"); - end if; - end; - end; - -exception - when Data_Format_Error | Constraint_Error => - Print_Usage; - Set_Exit_Status (Failure); -end Depth_First_Search; - -``` - -{% endraw %} - -Depth First Search in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/algol60/index.md b/docs/projects/depth-first-search/algol60/index.md deleted file mode 100644 index 8102993386..0000000000 --- a/docs/projects/depth-first-search/algol60/index.md +++ /dev/null @@ -1,317 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-17 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-04-17 -layout: default -tags: -- algol60 -- depth-first-search -title: Depth First Search in ALGOL 60 -title1: Depth First Search -title2: in ALGOL 60 ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a tree in an adjacency matrix form " - "(\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") " - "together with a list of vertex values (\"1, 3, 5, 2, 4\") " - "and the integer to find (\"4\")" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Create graph from connection matrix and vertex values. - The graph is in this form: - - column 1: Vertex values - - column 2: Number of children for each vertex value - - column 3 ... n + 2: Index of each child - - where n = number of vertices; - procedure createGraph(connMtx, connMtxLen, vert, vertLen, graph); - value connMtxLen, vertLen; - integer array connMtx, vert, graph; - integer connMtxLen, vertLen; - begin - integer i, j, idx; - - idx := 0; - for i := 1 step 1 until vertLen do - begin - comment Store this vertex value and initialize number of children; - graph[i, 1] := vert[i]; - graph[i, 2] := 0; - - comment Connect child nodes for this vertex; - for j := 1 step 1 until vertLen do - begin - idx := idx + 1; - if idx <= connMtxLen then - begin - if connMtx[idx] != 0 then - begin - graph[i, 2] := graph[i, 2] + 1; - graph[i, graph[i, 2] + 2] := j - end - end - end - end - end createGraph; - - comment Returns index if target value found, 0 otherwise; - integer procedure depthFirstSearch(graph, vertLen, target); - value vertLen, target; - integer array graph; - integer vertLen, target; - begin - integer procedure depthFirstSearchRec(visited, nodeIdx); - value nodeIdx; - boolean array visited; - integer nodeIdx; - begin - integer foundIdx, childIdx, i; - - comment Indicate target value not found; - foundIdx := 0; - - comment If node index is valid and value matches target, return - this node index; - if nodeIdx > 0 then - begin - if graph[nodeIdx, 1] = target then foundIdx := nodeIdx - else - begin - comment Otherwise, indicate node is visited; - visited[nodeIdx] := true; - - comment Perform Depth First Search on each unvisited child of - this node (if any). Stop when target value is found; - i := 0; - searchloop: - i := i + 1; - if i <= graph[nodeIdx, 2] & foundIdx = 0 then - begin - childIdx := graph[nodeIdx, i + 2]; - if !visited[childIdx] then - begin - foundIdx := depthFirstSearchRec(visited, childIdx); - visited[childIdx] := true - end; - - goto searchloop - end - end - end; - - depthFirstSearchRec := foundIdx - end depthFirstSearchRec; - - integer i; - boolean array visited[1:vertLen]; - - comment Indicate no nodes visited; - for i := 1 step 1 until vertLen do visited[i] := false; - - comment Do Depth First Search for target value starting at - root node (1); - depthFirstSearch := depthFirstSearchRec(visited, 1) - end depthFirstSearch; - - integer argc, connMtxLen, vertLen, ch, target, idx; - integer array connMtx[1:256], vert[1:16]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 3 then usage; - - comment Get connection matrix input from 1st argument. Exit if invalid; - connMtxLen := inIntegerArray(connMtx, 256); - if connMtxLen < 1 then usage; - - comment Get vertex values from 2nd argument. Exit if invalid; - vertLen := inIntegerArray(vert, 16); - if vertLen < 1 then usage; - - comment Get target value from 3nd argument. Exit if invalid; - if !inValidInteger(target, ch, false) then usage; - - begin - comment Create a graph from the connect matrix and vertex values; - integer array graph[1:vertLen, 1:vertLen + 2]; - createGraph(connMtx, connMtxLen, vert, vertLen, graph); - - comment Depth First Search for target value. Indicate if found; - idx := depthFirstSearch(graph, vertLen, target); - if idx > 0 then outstring(1, "true\n") - else outstring(1, "false\n") - end -end - -``` - -{% endraw %} - -Depth First Search in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/algol68/index.md b/docs/projects/depth-first-search/algol68/index.md deleted file mode 100644 index 66934ab478..0000000000 --- a/docs/projects/depth-first-search/algol68/index.md +++ /dev/null @@ -1,289 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-29 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2023-03-24 -layout: default -tags: -- algol68 -- depth-first-search -title: Depth First Search in ALGOL 68 -title1: Depth First Search -title2: in ALGOL 68 ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(( - $gl$, - ( - "Usage: please provide a tree in an adjacency matrix form " - + "(""0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0"") " - + "together with a list of vertex values (""1, 3, 5, 2, 4"") " - + "and the integer to find (""4"")" - ) - )) -); - -COMMENT -Create tree from adjacency matrix and vertex values. -The tree consists of a sequence of nodes. -Each node consists of a vertex value and sequence of child indices -COMMENT -MODE NODE = STRUCT(INT value, REF []INT children); - -PROC create tree = (REF []INT adjacency matrix, REF []INT vertex values) REF []NODE: -( - # Initialize nodes # - INT num vertices := UPB vertex values; - HEAP [num vertices]NODE nodes; - INT num adjacencies := UPB adjacency matrix; - - # Get children for this vertex value based on non-zero values of adjacency matrix # - INT index := 0; - FOR row TO num vertices - DO - # Count number of children # - INT num children := 0; - FOR col TO num vertices - WHILE (index + col) < num adjacencies - DO - IF adjacency matrix[index + col] > 0 - THEN - num children +:= 1 - FI - OD; - - # Add child node indices to this node # - HEAP [num children]INT children; - num children := 0; - FOR col TO num vertices - WHILE index < num adjacencies - DO - index +:= 1; - IF adjacency matrix[index] > 0 - THEN - num children +:= 1; - children[num children] := col - FI - OD; - - nodes[row] := NODE(vertex values[row], children) - OD; - - nodes -); - -PROC depth first search = (REF []NODE tree, INT target) REF NODE: -( - # Initialize visit nodes # - INT num vertices = UPB tree; - HEAP [num vertices]BOOL visited; - FOR k TO num vertices - DO - visited[k] := FALSE - OD; - - # Perform depth first recursively starting at root of tree # - INT found index := depth first search rec(tree, target, 1, visited); - (found index > 0 | tree[found index] | NIL) -); - -PROC depth first search rec = ( - REF []NODE tree, INT target, INT node index, REF []BOOL visited -) INT: -( - INT found index := 0; - - # If node is invalid or value of this node matches target, return this node index # - IF node index = 0 OREL value OF tree[node index] = target - THEN - found index := node index - ELSE - # Indicate this node is visited # - visited[node index] := TRUE; - - # Perform depth first search on each unvisited child of this node (if any). # - # Stop when match found # - INT child index; - REF []INT children := children OF tree[node index]; - FOR k TO UPB children - WHILE found index = 0 - DO - child index := children[k]; - IF NOT visited[child index] - THEN - found index := depth first search rec(tree, target, child index, visited); - visited[child index] := TRUE - FI - OD - FI; - - found index -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT adjacency matrix := values OF list result; -IF NOT valid OF list result -THEN - usage; - stop -FI; - -# Parse 2nd command-line argument # -s := argv(5); -list result := parse int list(s); -REF []INT vertex values = values OF list result; -IF NOT valid OF list result -THEN - usage; - stop -FI; - -# Parse 3rd command-line argument # -s := argv(6); -PARSEINT_RESULT result := parse int(s); -INT value := value OF result; -IF NOT valid OF result -THEN - usage; - stop -FI; - -# Create tree from adjacency matrix and vertex values # -REF []NODE tree := create tree(adjacency matrix, vertex values); - -# Run depth first search and indicate if value is found # -REF NODE node := depth first search(tree, value); -printf(($gl$, (node ISNT REF NODE(NIL) | "true" | "false"))) - -``` - -{% endraw %} - -Depth First Search in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/awk/index.md b/docs/projects/depth-first-search/awk/index.md deleted file mode 100644 index b81fa8699f..0000000000 --- a/docs/projects/depth-first-search/awk/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-10 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2025-04-27 -layout: default -tags: -- awk -- depth-first-search -title: Depth First Search in AWK -title1: Depth First -title2: Search in AWK ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a tree in an adjacency matrix form " \ - "(\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") " \ - "together with a list of vertex values (\"1, 3, 5, 2, 4\") " \ - "and the integer to find (\"4\")" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -# Create tree from adjacency matrix and vertex values. The tree consists of a sequence -# of nodes. Each node consists a node value and of child vertex values -function create_tree(nodes, adjacency_matrix, vertex_values, u, v, node_value) { - idx = 0 - for (u in vertex_values) { - # Store node value - node_value = vertex_values[u] - nodes[node_value][node_value] = 1 - - # Store child indices for this node based on non-zero values of adjacency matrix - num_children = 0 - for (v in vertex_values) { - if (adjacency_matrix[++idx]) { - nodes[node_value][vertex_values[v]] = 1 - } - } - } -} - -function depth_first_search(nodes, target, \ - value, visited, node_value, sp, stack, found, child_value) { - # Get root node value - for (value in nodes) { - node_value = value - break - } - - # Do depth first search iteratively using a stack of node values to try - - # Push root index to stack - sp = 0 - stack[++sp] = node_value - - # While stack is not empty - while (sp > 0) { - found = 0 - - # Pop node index from stack - node_value = stack[sp--] - - # If node is invalid or value of this node matches target, return this node index - if (node_value == target) { - found = 1 - break - } - - # Indicate this node is visited - visited[node_value] = 1 - - # Push all unvisited child indices to the stack - for (child_value in nodes[node_value]) { - if (!(child_value in visited)) { - stack[++sp] = child_value - } - } - } - - return found -} - -BEGIN { - if (ARGC < 4) { - usage() - } - - str_to_array(ARGV[1], adjacency_matrix) - str_to_array(ARGV[2], vertex_values) - target = str_to_number(ARGV[3]) - if (!length(adjacency_matrix) || adjacency_matrix[1] == "ERROR" || \ - !length(vertex_values) || vertex_values[1] == "ERROR" || \ - target == "ERROR") { - usage() - } - - create_tree(nodes, adjacency_matrix, vertex_values) - found = depth_first_search(nodes, target) - print (found) ? "true" : "false" -} - -``` - -{% endraw %} - -Depth First Search in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/beef/index.md b/docs/projects/depth-first-search/beef/index.md deleted file mode 100644 index eb14257cdd..0000000000 --- a/docs/projects/depth-first-search/beef/index.md +++ /dev/null @@ -1,248 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-04 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2024-02-04 -layout: default -tags: -- beef -- depth-first-search -title: Depth First Search in Beef -title1: Depth First -title2: Search in Beef ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace DepthFirstSearch; - -class Node -{ - public T mId; - public List *> mChildren = new .() ~ delete _; - - public this(T id) - { - mId = id; - } - - public void AddChild(Node *node) - { - mChildren.Add(node); - } -} - -class Graph -{ - public List> mVertices = new .() ~ DeleteContainerAndItems!(_); - - public void AddNode(T id) - { - Node node = new .(id); - mVertices.Add(node); - } -} - -class Program -{ - public static void Usage() - { - Console.WriteLine( - scope String("Usage: please provide a tree in an adjacency matrix form") - .. AppendF( - " {}", - """ - ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") - """ - ) - .. AppendF( - " {}", - """ - together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4") - """ - ) - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - public static Graph CreateGraph(List connectionMatrix, List vertices) - where T : IHashable - where int : operator T <=> T - { - // Create graph - Graph graph = new .(); - - // Add vertices - for (T id in vertices) - { - graph.AddNode(id); - } - - // Add edges - int row = 0; - int col = 0; - int numVertices = vertices.Count; - for (int connection in connectionMatrix) - { - col++; - if (col >= numVertices) - { - row++; - col = 0; - } - - if (connection != 0) - { - graph.mVertices[row].AddChild(&graph.mVertices[col]); - } - } - - return graph; - } - - public static Node *DepthFirstSearch(Graph graph, T target) - where T : IHashable - where int : operator T <=> T - { - HashSet visited = scope .(); - return DepthFirstSearchRec(&graph.mVertices[0], target, visited); - } - - public static Node *DepthFirstSearchRec(Node *node, T target, HashSet visited) - where T : IHashable - where int : operator T <=> T - { - Node *found = null; - - // If no node or target value found, return current node - if (node == null || (*node).mId == target) - { - return node; - } - - // Indicate node is visited - visited.Add((*node).mId); - - // Perform depth first search on unvisited child node until found - for (Node *childNode in (*node).mChildren) - { - if (!visited.Contains((*childNode).mId)) - { - found = DepthFirstSearchRec(childNode, target, visited); - if (found != null) - { - break; - } - } - } - - return found; - } - - public static int Main(String[] args) - { - if (args.Count < 3) - { - Usage(); - } - - List connectionMatrix = scope .(); - if (ParseIntList(args[0], connectionMatrix) case .Err) - { - Usage(); - } - - List vertices = scope .(); - if (ParseIntList(args[1], vertices) case .Err) - { - Usage(); - } - - int32 target = ?; - switch (ParseInt(args[2])) - { - case .Ok(out target): - case .Err: - Usage(); - } - - Graph graph = CreateGraph(connectionMatrix, vertices); - Node *result = DepthFirstSearch(graph, target); - Console.WriteLine((result != null) ? "true" : "false"); - delete graph; - - return 0; - } -} - -``` - -{% endraw %} - -Depth First Search in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/c-plus-plus/index.md b/docs/projects/depth-first-search/c-plus-plus/index.md deleted file mode 100644 index 450d8bb6f0..0000000000 --- a/docs/projects/depth-first-search/c-plus-plus/index.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -authors: -- Ajay Maheshwari -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2022-10-03 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- depth-first-search -title: Depth First Search in C++ -title1: Depth First -title2: Search in C++ ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace views = std::views; -namespace ranges = std::ranges; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4"))" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -auto to_sv = [](auto&& r) { - return std::string_view{std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; -}; - -bool can_reach_node(size_t start, int target, - const std::vector& values, - const std::vector& matrix) { - const size_t n = values.size(); - if (n == 0) return false; - - std::vector visited(n, 0); - std::stack st; - st.push(start); - - while (!st.empty()) { - size_t u = st.top(); - st.pop(); - - if (visited[u]) continue; - visited[u] = true; - - if (values[u] == target) return true; - - for (size_t v = 0; v < n; ++v) { - if (matrix[u * n + v] != 0 && !visited[v]) { - st.push(v); - } - } - } - return false; -} - -int main(int argc, char* argv[]) { - if (argc != 4) usage(); - - auto parse_vec = [](std::string_view input) -> std::vector { - auto ints_view = input | views::split(',') | views::transform(to_sv) | - views::transform(trim) | views::transform(to_int); - - std::vector numbers; - numbers.reserve(ranges::distance(ints_view)); - - for (auto v : ints_view) { - if (!v) usage(); - numbers.push_back(*v); - } - return numbers; - }; - - const auto matrix = parse_vec(argv[1]); - const auto values = parse_vec(argv[2]); - const auto target = to_int(argv[3]); - - if (!target || values.empty()) usage(); - - const std::size_t n = values.size(); - if (matrix.size() != n * n) usage(); - - const bool reached = can_reach_node(0, *target, values, matrix); - std::cout << std::format("{}\n", reached); -} -``` - -{% endraw %} - -Depth First Search in [C++](/languages/c-plus-plus) was written by: - -- Ajay Maheshwari -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/c-sharp/index.md b/docs/projects/depth-first-search/c-sharp/index.md deleted file mode 100644 index 4e745d40d4..0000000000 --- a/docs/projects/depth-first-search/c-sharp/index.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-29 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- depth-first-search -title: Depth First Search in C# -title1: Depth First -title2: Search in C# ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var matrixRaw, var verticesRaw, var targetRaw] || - !int.TryParse(targetRaw, out int target) || - !TryParseList(verticesRaw.AsSpan(), out var vertices) || - !TryParseList(matrixRaw.AsSpan(), out var matrix)) -{ - return Usage(); -} - -int n = vertices.Count; -if (matrix.Count != n * n) - return Usage(); - -List[] graph = new List[n]; -for (int i = 0; i < n; i++) - graph[i] = []; - -for (int r = 0; r < n; r++) -{ - int baseIdx = r * n; - - for (int c = 0; c < n; c++) - if (matrix[baseIdx + c] != 0) - graph[r].Add(c); -} - -Console.WriteLine( - DFS(graph, vertices, target).ToString().ToLowerInvariant() -); - -return 0; - -static bool DFS(List[] graph, List values, int target) -{ - int n = values.Count; - var visited = new bool[n]; - var stack = new int[n]; - int sp = 0; - - stack[sp++] = 0; - - while (sp > 0) - { - int v = stack[--sp]; - if (visited[v]) continue; - - visited[v] = true; - if (values[v] == target) return true; - - foreach (int next in graph[v]) - if (!visited[next]) - stack[sp++] = next; - } - - return false; -} - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return true; -} - -static int Usage() -{ - Console.Error.WriteLine( - """Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")""" - ); - return 1; -} - -``` - -{% endraw %} - -Depth First Search in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/c/index.md b/docs/projects/depth-first-search/c/index.md deleted file mode 100644 index 2e86a2c35f..0000000000 --- a/docs/projects/depth-first-search/c/index.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-18 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- depth-first-search -title: Depth First Search in C -title1: Depth First -title2: Search in C ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include -#include - -#define MAX_NODES 100 - -int adjacency_matrix[MAX_NODES][MAX_NODES]; -int vertex_values[MAX_NODES]; -int num_nodes; -bool visited[MAX_NODES]; - -bool dfs(int node, int target) -{ - if (vertex_values[node] == target) - return true; - visited[node] = true; - for (int i = 0; i < num_nodes; i++) - { - if (adjacency_matrix[node][i] && !visited[i]) - { - if (dfs(i, target)) - return true; - } - } - return false; -} - -bool depth_first_search(int target) -{ - memset(visited, 0, sizeof(visited)); - for (int i = 0; i < num_nodes; i++) - if (!visited[i] && dfs(i, target)) - return true; - return false; -} - -void parse_matrix(char *input) -{ - char *token = strtok(input, ", "); - int i = 0, j = 0; - while (token != NULL) - { - adjacency_matrix[i][j] = atoi(token); - j++; - if (j == num_nodes) - { - i++; - j = 0; - } - token = strtok(NULL, ", "); - } -} - -void parse_values(char *input) -{ - char *token = strtok(input, ", "); - int i = 0; - while (token != NULL) - { - vertex_values[i++] = atoi(token); - token = strtok(NULL, ", "); - } -} - -int main(int argc, char *argv[]) -{ - if (argc != 4 || !*argv[1] || !*argv[2] || !*argv[3]) - { - printf("Usage: please provide a tree in an adjacency matrix form (\"0, " - "1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, " - "1, 0, 0\") together with a list of vertex values (\"1, 3, 5, " - "2, 4\") and the integer to find (\"4\")"); - return 1; - } - - char *matrix_str = argv[1]; - char *values_str = argv[2]; - int target = atoi(argv[3]); - - int total_elements = 1; - for (char *p = matrix_str; *p; p++) - if (*p == ',') - total_elements++; - - num_nodes = (int)sqrt(total_elements); - - parse_matrix(matrix_str); - parse_values(values_str); - - bool result = depth_first_search(target); - printf(result ? "true\n" : "false\n"); - - return 0; -} - -``` - -{% endraw %} - -Depth First Search in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/cobol/index.md b/docs/projects/depth-first-search/cobol/index.md deleted file mode 100644 index 9899200ac8..0000000000 --- a/docs/projects/depth-first-search/cobol/index.md +++ /dev/null @@ -1,204 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-01 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-01 -layout: default -tags: -- cobol -- depth-first-search -title: Depth First Search in COBOL -title1: Depth First -title2: Search in COBOL ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. depth-first-search. - -data division. -working-storage section. - -01 argument-count pic 9(4) comp. - -01 tree-input pic x(8192). -01 vertex-values-input pic x(4096). -01 target-value-input pic x(128). - -01 adjacency-matrix. - 05 adjacency-cell pic 9 occurs 10000 times. - -01 node-value. - 05 node pic s9(9) comp occurs 100 times. - -01 node-stack. - 05 stack-node pic 9(4) comp occurs 100 times. -01 stack-top pic 9(4) comp value 0. - -01 visited-nodes. - 05 visited-node pic 9 comp occurs 100 times. - -01 node-count pic 9(4) comp value 0. -01 cell-count pic 9(4) comp value 0. - -01 i pic 9(4) comp. -01 j pic 9(4) comp. -01 matrix-index pic 9(4) comp. -01 current-node pic 9(4) comp. - -01 target-node-value pic s9(9) comp. - -procedure division. - -main. - accept argument-count from argument-number - - if argument-count not = 3 - perform show-usage - end-if - - accept tree-input from argument-value - accept vertex-values-input from argument-value - accept target-value-input from argument-value - - if tree-input = spaces - or vertex-values-input = spaces - or target-value-input = spaces - perform show-usage - end-if - - move function numval(target-value-input) to target-node-value - - perform parse-adjacency-matrix - perform parse-vertex-values - - if node-count = 0 - perform show-usage - end-if - - perform depth-first-search - - goback. - -parse-adjacency-matrix. - move 0 to cell-count - - perform varying i from 1 by 1 - until i > function length(function trim(tree-input)) - - if tree-input(i:1) >= "0" - and tree-input(i:1) <= "9" - - add 1 to cell-count - move function numval(tree-input(i:1)) - to adjacency-cell(cell-count) - end-if - end-perform - - compute node-count = - function integer(function sqrt(cell-count)) - - if node-count * node-count not = cell-count - perform show-usage - end-if. - -parse-vertex-values. - move 0 to node-count - move 1 to j - - perform varying i from 1 by 1 - until i > function length(function trim(vertex-values-input)) - - if vertex-values-input(i:1) >= "0" - and vertex-values-input(i:1) <= "9" - - add 1 to node-count - move function numval(vertex-values-input(i:1)) - to node(node-count) - end-if - end-perform. - - if node-count = 0 - perform show-usage - end-if. - -depth-first-search. - move 1 to stack-top - move 1 to stack-node(stack-top) - - perform varying i from 1 by 1 until i > node-count - move 0 to visited-node(i) - end-perform - - perform until stack-top = 0 - - move stack-node(stack-top) to current-node - subtract 1 from stack-top - - if visited-node(current-node) = 1 - exit perform - end-if - - move 1 to visited-node(current-node) - - if node(current-node) = target-node-value - display "true" - goback - end-if - - perform varying i from node-count by -1 until i = 0 - compute matrix-index = - (current-node - 1) * node-count + i - - if adjacency-cell(matrix-index) = 1 - and visited-node(i) = 0 - - add 1 to stack-top - move i to stack-node(stack-top) - end-if - end-perform - - end-perform - - display "false" - goback. - -show-usage. - display 'Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")' - stop run. - -``` - -{% endraw %} - -Depth First Search in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/commodore-basic/index.md b/docs/projects/depth-first-search/commodore-basic/index.md deleted file mode 100644 index 946dcd8f74..0000000000 --- a/docs/projects/depth-first-search/commodore-basic/index.md +++ /dev/null @@ -1,222 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-21 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2023-10-21 -layout: default -tags: -- commodore-basic -- depth-first-search -title: Depth First Search in Commodore BASIC -title1: Depth First Search -title2: in Commodore BASIC ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -15 REM Adjacency matrix -20 DIM AM%(99) -25 REM Vertices -30 DIM VX(9) -35 REM Graph: -36 REM - G%(i, j) contains vertex index for child node j, vertex i or -37 REM negative to indicate no more child nodes -40 DIM G%(9, 10) -45 REM Visited nodes: 1 if visited, 0 otherwise -50 DIM VS%(9) -55 REM Stack - 2 elements for vertex -60 DIM SK%(19) -65 REM Get adjacency matrix -70 GOSUB 2000 -80 IF V = 0 OR C <> -1 THEN GOTO 400: REM invalid or end of input/value -90 NM = NA -100 FOR I = 0 TO NA - 1 -110 AM%(I) = 0 -120 IF A(I) <> 0 THEN AM%(I) = 1 -130 NEXT I -135 REM Get vertices -140 GOSUB 2000 -150 IF V = 0 OR C <> -1 THEN GOTO 400: REM invalid or end of input/value -160 NV = NA -170 FOR I = 0 TO NA - 1 -180 VX(I) = A(I) -190 NEXT I -195 REM Get target value -200 GOSUB 1000 -210 IF V = 0 OR C >= 0 THEN GOTO 400: REM invalid or not end of input/value -220 T = NR -225 REM Form graph -230 GOSUB 2500 -235 REM Perform depth search and show result -240 SP = -1: REM Reset stack pointer -250 GOSUB 3000 -260 R$ = "false" -270 IF VI >= 0 THEN R$ = "true" -280 PRINT R$ -290 END -400 Q$ = CHR$(34): REM quote -410 PRINT "Usage: please provide a tree in an adjacency matrix form "; -420 PRINT "("; Q$; "0, 1, 1, 0, 0, 1, 0, 0, 0, 0, "; -430 PRINT "1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0"; Q$; ") "; -440 PRINT "together with a list of vertex values "; -450 PRINT "("; Q$; "1, 3, 5, 2, 4"; Q$; ") and the integer to find "; -460 PRINT "("; Q$; "4"; Q$; ")" -470 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -2500 REM Form graph -2501 REM Inputs: -2502 REM - AM% contains adjacency matrix -2503 REM - NM contains number of items in adjacency matrix -2504 REM - NV contains number of vertices -2505 REM Output: G% contains graph -2510 K = -1 -2520 FOR I = 0 TO NV - 1 -2530 N = -1 -2540 FOR J = 0 TO NV - 1 -2550 K = K + 1 -2560 IF K >= NM THEN GOTO 2600 -2570 IF AM%(K) = 0 THEN GOTO 2600 -2580 N = N + 1 -2590 G%(I, N) = J -2600 NEXT J -2610 G%(I, N + 1) = -1: REM End of child nodes -2620 NEXT I -2630 RETURN -3000 REM Perform depth first search -3001 REM Commodore Basic does not really support recursion because everything -3002 REM is a global variable. However, recursion can be simulated with -3003 REM a "stack". This "stack" is just an array, SK, and a stack index, SP. -3004 REM Inputs: -3005 REM - VX contains vertices -3006 REM - NV contains number of vertices -3007 REM - T contains value to find -3008 REM - G% contains graph -3009 REM Output: VI contains index of vertex found, -1 if not found -3010 REM Initialize visited nodes -3020 FOR I = 0 TO NV - 1 -3030 VS%(I) = 0 -3040 NEXT I -3050 REM Start at root node -3060 NI = 0 -3070 VI = -1 -3100 REM Recursive portion of algorithm -3101 REM Inputs: -3102 REM - NI contains node index -3103 REM - VX contains vertices -3104 REM - NV contains number of vertices -3105 REM - T contains value to find -3106 REM - G% contains graph -3107 REM - VS% contains visited nodes -3108 REM Output: VI contains index of vertex found, -1 if not found -3110 IF VX(NI) = T THEN VI = NI: GOTO 3250: REM Found -3120 VS%(NI) = 1: REM Indicate node visited -3130 J = -1 -3140 J = J + 1 -3150 CI = G%(NI, J): REM Get child node -3160 IF CI < 0 THEN GOTO 3250: REM No more child nodes -3170 IF VS%(CI) <> 0 THEN GOTO 3140: REM Skip visited node -3180 SP = SP + 1: SK%(SP) = J: REM Push child node index -3190 SP = SP + 1: SK%(SP) = NI: REM Push node index -3200 NI = CI: REM Go to child node -3210 GOSUB 3100: REM Perform depth first search on child node -3220 NI = SK%(SP): SP = SP - 1: REM Pop node index -3230 J = SK%(SP): SP = SP - 1: REM Pop child node index -3240 IF VI < 0 THEN GOTO 3140: REM If not found, go to next child node -3250 RETURN - -``` - -{% endraw %} - -Depth First Search in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/euphoria/index.md b/docs/projects/depth-first-search/euphoria/index.md deleted file mode 100644 index 7e2a0f16cf..0000000000 --- a/docs/projects/depth-first-search/euphoria/index.md +++ /dev/null @@ -1,248 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2023-03-24 -layout: default -tags: -- depth-first-search -- euphoria -title: Depth First Search in Euphoria -title1: Depth First Search -title2: in Euphoria ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/utils.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - ( - "Usage: please provide a tree in an adjacency matrix form " - & "(\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") " - & "together with a list of vertex values (\"1, 3, 5, 2, 4\") " - & "and the integer to find (\"4\")\n" - ) - ) - abort(0) -end procedure - --- Indices for node values -enum NODE_VERTEX, NODE_CHILDREN - --- Create tree from adjacency matrix and vertex values. --- The tree consists of a sequence of nodes. --- Each node consists of a vertex value and sequence of child indices -function create_tree(sequence adjacency_matrix, sequence vertex_values) - -- Initialize nodes - sequence nodes = {} - - -- Get children for this vertex value based on non-zero values of adjacency matrix - integer num_vertices = length(vertex_values) - integer num_adjacencies = length(adjacency_matrix) - integer index = 0 - for row = 1 to num_vertices - do - -- Initialize this node with no children - nodes &= {{vertex_values[row], {}}} - - -- Add child node indices to this node - integer col = 0 - while col < num_vertices and index < num_adjacencies - do - col += 1 - index += 1 - if adjacency_matrix[index] > 0 - then - nodes[row][NODE_CHILDREN] &= col - end if - end while - end for - - return nodes -end function - --- Indices for depth_first_search_rec return values -enum DFS_VISITED, DFS_FOUND - -function depth_first_search(sequence tree, integer target) - -- Perform depth first recursively starting at root of tree, - -- indicating no visited nodes and not found - sequence visited = repeat(FALSE, length(tree)) - sequence dfs_result = depth_first_search_rec(tree, target, 1, {visited, {}}) - - -- Indicate where target value is found (if any) - return dfs_result[DFS_FOUND] -end function - -function depth_first_search_rec(sequence tree, integer target, integer node_index, sequence dfs_result) - -- If invalid node, indicate not found - if node_index = 0 - then - return {dfs_result[DFS_VISITED], {}} - end if - - -- If key of this node matches target, indicate found - sequence node = tree[node_index] - if node[NODE_VERTEX] = target - then - return {dfs_result[DFS_VISITED], node} - end if - - -- Indicate this node is visited - dfs_result[DFS_VISITED][node_index] = TRUE - - -- Perform depth first search on each unvisited child of this node (if any) - for k = 1 to length(node[NODE_CHILDREN]) - do - integer child_index = node[NODE_CHILDREN][k] - if not dfs_result[DFS_VISITED][child_index] - then - dfs_result = depth_first_search_rec(tree, target, child_index, dfs_result) - dfs_result[DFS_VISITED][child_index] = TRUE - if length(dfs_result[DFS_FOUND]) > 0 - then - return dfs_result - end if - end if - end for - - return dfs_result -end function - --- Check command-line arguments -sequence argv = command_line() -if ( - length(argv) < 6 - or length(argv[4]) = 0 - or length(argv[5]) = 0 - or length(argv[6]) = 0 -) -then - usage() -end if - --- Parse 1st command-line argument -sequence list_result = parse_int_list(argv[4]) -sequence adjacency_matrix = list_result[PARSE_INT_LIST_VALUES] -if not list_result[PARSE_INT_LIST_VALID] -then - usage() -end if - --- Parse 2nd command-line argument -list_result = parse_int_list(argv[5]) -sequence vertex_values = list_result[PARSE_INT_LIST_VALUES] -if not list_result[PARSE_INT_LIST_VALID] -then - usage() -end if - --- Parse 3rd command-line argument -sequence result = parse_int(argv[6]) -integer target = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] -then - usage() -end if - --- Create tree from adjacency matrix and vertex values -sequence tree = create_tree(adjacency_matrix, vertex_values) - --- Run depth first search and indicate if value is found -sequence node = depth_first_search(tree, target) -puts(STDOUT, iif(length(node) > 0, "true\n", "false\n")) - -``` - -{% endraw %} - -Depth First Search in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/f-sharp/index.md b/docs/projects/depth-first-search/f-sharp/index.md deleted file mode 100644 index d9c8127cbc..0000000000 --- a/docs/projects/depth-first-search/f-sharp/index.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-06 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-04-06 -layout: default -tags: -- depth-first-search -- f-sharp -title: Depth First Search in F# -title1: Depth First -title2: Search in F# ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System -open System.Collections.Generic - -module ActivePatterns = - /// Pattern to safely parse a single integer from a trimmed string - let (|Int|_|) (s: string) = - match Int32.TryParse(s.Trim()) with - | true, n -> Some n - | _ -> None - - /// Pattern to parse a comma-separated list into an int array. - let (|IntList|_|) (s: string) = - if String.IsNullOrWhiteSpace s then - None - else - let parts = s.Split(',', StringSplitOptions.RemoveEmptyEntries) - let parsed = Array.zeroCreate parts.Length - let mutable allValid = true - let mutable i = 0 - - while allValid && i < parts.Length do - match parts.[i] with - | Int x -> - parsed.[i] <- x - i <- i + 1 - | _ -> allValid <- false - - if allValid && parsed.Length > 0 then Some parsed else None - - /// Validates that a 1D array represents a binary square matrix (size * - /// size) and transforms it into a 2D bool array. - let (|AdjacencyMatrix|_|) (size: int) (arr: int array) = - if arr.Length = size * size && Array.forall (fun x -> x = 0 || x = 1) arr then - Some(Array2D.init size size (fun r c -> arr.[r * size + c] = 1)) - else - None - -module DepthFirstSearch = - let run (adj: bool[,], vertices: int array, target: int) = - let n = vertices.Length - let visited = Array.zeroCreate n - let stack = Stack() - stack.Push 0 - - let mutable found = false - - while stack.Count > 0 && not found do - let node = stack.Pop() - - if not visited.[node] then - if vertices.[node] = target then - found <- true - else - visited.[node] <- true - - for i in n - 1 .. -1 .. 0 do - if adj.[node, i] && not visited.[i] then - stack.Push i - - Ok found - -module Helpers = - open ActivePatterns - - let usage = - "Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, " - + "1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and " - + "the integer to find (\"4\")" - - let parseArgs argv = - match argv with - | [| m; v; t |] -> Ok(m, v, t) - | _ -> Error usage - - let validate (mStr, vStr, tStr) = - match vStr, tStr with - | IntList vertices, Int target -> - // Shortcircuit: if the target isn't in the vertex list, why bother - // traversing the graph? - let vSet = HashSet(vertices) - - if not (vSet.Contains target) then - Ok(None) - else - match mStr with - | IntList mat -> - match mat with - // Ensure the matrix size matches the number of vertices provided - | AdjacencyMatrix vertices.Length adj -> Ok(Some(adj, vertices, target)) - | _ -> Error usage - | _ -> Error usage - | _ -> Error usage - - let handleResult = - function - | Ok b -> - printfn "%b" b - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.bind Helpers.validate - |> Result.bind (function - | Some data -> DepthFirstSearch.run data - | None -> Ok false) - |> Helpers.handleResult - -``` - -{% endraw %} - -Depth First Search in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/go/index.md b/docs/projects/depth-first-search/go/index.md deleted file mode 100644 index ac25c1a1e4..0000000000 --- a/docs/projects/depth-first-search/go/index.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- depth-first-search -- go -title: Depth First Search in Go -title1: Depth First -title2: Search in Go ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" - "strings" -) - -const usage = `Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")` - -type Graph struct { - matrix []int - values []int - size int -} - -func main() { - if len(os.Args) != 4 { - printUsage() - } - - matrix, errM := parseList(os.Args[1]) - values, errV := parseList(os.Args[2]) - target, errT := strconv.Atoi(os.Args[3]) - - if errM != nil || errV != nil || errT != nil { - printUsage() - } - - n := len(values) - if len(matrix) != n*n || n == 0 { - printUsage() - } - - g := &Graph{ - matrix: matrix, - values: values, - size: n, - } - - visited := make([]bool, n) - if g.DFS(0, target, visited) { - fmt.Println("true") - } else { - fmt.Println("false") - } -} - -func (g *Graph) DFS(curr, target int, visited []bool) bool { - if g.values[curr] == target { - return true - } - - visited[curr] = true - - for neighbor := 0; neighbor < g.size; neighbor++ { - edgeExists := g.matrix[curr*g.size+neighbor] == 1 - if edgeExists && !visited[neighbor] { - if g.DFS(neighbor, target, visited) { - return true - } - } - } - - return false -} - -func parseList(input string) ([]int, error) { - if strings.TrimSpace(input) == "" { - return nil, fmt.Errorf("empty input") - } - - parts := strings.Split(input, ",") - nums := make([]int, 0, len(parts)) - for _, p := range parts { - val, err := strconv.Atoi(strings.TrimSpace(p)) - if err != nil { - return nil, err - } - nums = append(nums, val) - } - return nums, nil -} - -func printUsage() { - fmt.Println(usage) - os.Exit(1) -} -``` - -{% endraw %} - -Depth First Search in [Go](/languages/go) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/haskell/index.md b/docs/projects/depth-first-search/haskell/index.md deleted file mode 100644 index c56d906a6f..0000000000 --- a/docs/projects/depth-first-search/haskell/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-18 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-18 -layout: default -tags: -- depth-first-search -- haskell -title: Depth First Search in Haskell -title1: Depth First -title2: Search in Haskell ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Data.IntSet (IntSet) -import qualified Data.IntSet as IS -import Data.IntMap (IntMap) -import qualified Data.IntMap.Strict as IM -import Control.Monad (guard, forM) -import Control.Monad.State -import Text.Read (readMaybe) -import Data.Maybe (fromMaybe) -import System.Environment - -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - -parseArgs :: [String] -> Maybe ([Int], [Int], Int) -parseArgs [tree, vertices, target] = do - tree <- stringToListMaybe tree - vertices <- stringToListMaybe vertices - target <- readMaybe target - guard $ (not . null) tree - guard $ (not . null) vertices - guard (length vertices ^ 2 == length tree) - return (tree, vertices, target) -parseArgs _ = Nothing - --- builds a map where the vertices are the keys and the values are lists of neighboring vertices -buildAdjencyMap :: [Int] -> [Int] -> IntMap [Int] -buildAdjencyMap tree vertices = IM.fromListWith (++) [(u, [v]) | (1, (u, v)) <- zip tree coordinates] - where coordinates = [(u, v) | u <- vertices, v <- vertices] - -dfs :: IntMap [Int] -> Int -> Int -> Bool -dfs adj start target = evalState (go start) IS.empty - where - go :: Int -> State IntSet Bool - go n | n == target = return True - go n = do - vis <- get - if IS.member n vis - then - return False - else do - modify (IS.insert n) - let neighs = fromMaybe [] $ IM.lookup n adj - res <- forM neighs go - return (or res) - -main :: IO () -main = do - args <- getArgs - case parseArgs args of - Nothing -> putStrLn "Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\")" - Just (tree, vertices@(v:_), target) -> - let adj = buildAdjencyMap tree vertices - in putStrLn $ if dfs adj v target then "true" else "false" - -``` - -{% endraw %} - -Depth First Search in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/index.md b/docs/projects/depth-first-search/index.md deleted file mode 100644 index c8792f6063..0000000000 --- a/docs/projects/depth-first-search/index.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -date: 2021-11-12 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-18 -layout: default -tags: -- depth-first-search -title: Depth First Search -title1: Depth First -title2: Search ---- - - - -Welcome to the Depth First Search page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -## Description - -Depth first search is a type of graph search algorithm. It is often used on trees -(which are special types of graphs). -It takes linear time to traverse a graph and find a given vertex, specifically O(num_vertices + num_edges). -This search algorithm is often used by web crawlers or in machine learning tasks. -There, the graph that should be traversed is often too big to be do it in a single run. -In such cases, the algorithm can be limited in different ways, for example by limiting depth or visited nodes. - -The algorithm traverses the graph one node after the other, but takes priority in going deeper into -the graph opposed to going broader first. This means, that it visits further children of children before visiting -potential siblings of them. - - -## Requirements - -For the purposes of this project, we'll assume that the search space is a tree represented -as an adjacency matrix together with a list of the vertex values in the tree. -Specifically, we'll accept three inputs on the command line: the tree adjacency matrix, the list of vertex -values (as integers) and the vertex value to find: - -```console -./depth-first-search.lang "0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0" "2, 3, 6, 77, 44, 46, 1, 321, 5" "5" -``` - -Here we've chosen to represent the graph as a serialized list of integers. Since -the input string represents a square matrix, we should be able to take the -square root of the length to determine where the rows are in the string. In this -case, we have 81 values, so we must have 9 nodes. -If we reformat the input string as a matrix, we'll notice that the values in the -matrix represent the edges between vertices. Taking the vertex values into account as well, the resulting matrix -could look something like the following: - -| Mapping | 2 | 3 | 6 | 77 | 44 | 46 | 1 | 321 | 5 | -| ------- | --- | --- | --- | --- | --- | --- | --- | --- | --- | -| 2 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | -| 3 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | -| 6 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | -| 77 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | -| 44 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| 46 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -| 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | -| 321 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | -| 5 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | - -This matrix will result in a tree that looks like this: - -```console - 2 - / | \ - 3 6 77 - / | / \ \ - 44 46 1 321 5 -``` - -If successful, the script should return `true`. Otherwise, the script should return `false`. -If any user input errors occur, the script should output the following usage message: -`Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")`. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Depth First Search. -In order to keep things simple, we split up the testing as follows: - -- Depth First Search Valid Tests -- Depth First Search Invalid Tests - -### Depth First Search Valid Tests - -| Description | Tree Input | Vertex Values | Target Integer Input | Output | -| ----------- | ---------- | ------------- | -------------------- | ------ | -| Sample Input: First True | "0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0" | "1, 3, 5, 2, 4" | "1" | "true" | -| Sample Input: Last True | "0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0" | "1, 3, 5, 2, 4" | "4" | "true" | -| Sample Input: Middle True | "0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0" | "1, 3, 5, 2, 4" | "5" | "true" | -| Sample Input: One True | "0" | "1" | "1" | "true" | -| Sample Input: One False | "0" | "1" | "6" | "false" | -| Sample Input: Many False | "0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0" | "1, 3, 5, 2, 4" | "7" | "false" | - -### Depth First Search Invalid Tests - -| Description | Tree Input | Vertex Values | Target Integer Input | -| ----------- | ---------- | ------------- | -------------------- | -| No Input | | | | -| Missing Input: Tree | "" | "1, 3, 5, 2, 4" | "4" | -| Missing Input: Vertex Values | "0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0" | "" | "1" | -| Missing Input: Target | "0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0" | "1, 3, 5, 2, 4" | "" | - -All of these tests should output the following: - -``` -Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4") -``` - - -## Articles - -There are 28 articles: - -- [Depth First Search in ALGOL 60](/projects/depth-first-search/algol60) -- [Depth First Search in ALGOL 68](/projects/depth-first-search/algol68) -- [Depth First Search in AWK](/projects/depth-first-search/awk) -- [Depth First Search in Ada](/projects/depth-first-search/ada) -- [Depth First Search in Beef](/projects/depth-first-search/beef) -- [Depth First Search in C](/projects/depth-first-search/c) -- [Depth First Search in C#](/projects/depth-first-search/c-sharp) -- [Depth First Search in C++](/projects/depth-first-search/c-plus-plus) -- [Depth First Search in COBOL](/projects/depth-first-search/cobol) -- [Depth First Search in Commodore BASIC](/projects/depth-first-search/commodore-basic) -- [Depth First Search in Euphoria](/projects/depth-first-search/euphoria) -- [Depth First Search in F#](/projects/depth-first-search/f-sharp) -- [Depth First Search in Go](/projects/depth-first-search/go) -- [Depth First Search in Haskell](/projects/depth-first-search/haskell) -- [Depth First Search in Java](/projects/depth-first-search/java) -- [Depth First Search in JavaScript](/projects/depth-first-search/javascript) -- [Depth First Search in Mathematica](/projects/depth-first-search/mathematica) -- [Depth First Search in PHP](/projects/depth-first-search/php) -- [Depth First Search in Pascal](/projects/depth-first-search/pascal) -- [Depth First Search in PowerShell](/projects/depth-first-search/powershell) -- [Depth First Search in Python](/projects/depth-first-search/python) -- [Depth First Search in Ruby](/projects/depth-first-search/ruby) -- [Depth First Search in Rust](/projects/depth-first-search/rust) -- [Depth First Search in Swift](/projects/depth-first-search/swift) -- [Depth First Search in Tcl](/projects/depth-first-search/tcl) -- [Depth First Search in TypeScript](/projects/depth-first-search/typescript) -- [Depth First Search in Visual Basic](/projects/depth-first-search/visual-basic) -- [Depth First Search in m4](/projects/depth-first-search/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/depth-first-search/java/index.md b/docs/projects/depth-first-search/java/index.md deleted file mode 100644 index bb053363f0..0000000000 --- a/docs/projects/depth-first-search/java/index.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -authors: -- koishi-dream -date: 2024-09-30 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2024-09-30 -layout: default -tags: -- depth-first-search -- java -title: Depth First Search in Java -title1: Depth First -title2: Search in Java ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; - -public class DepthFirstSearch { - - public static void main(String[] args) { - if (args.length != 3 || args[0].isEmpty() || args[1].isEmpty() || args[2].isEmpty()) { - handleError(); - return; - } - int matrixSize = args[0].split(",").length; - if (matrixSize != Math.pow(args[1].split(",").length, 2)){ - handleError(); - return; - } - List vertices = Stream.of(args[1].split(",")) - .map(String::trim) - .map(Integer::parseInt) - .toList(); - int[][] matrix = new int[matrixSize][matrixSize]; - int count = 0; - for (int i = 0; i < vertices.size(); i++) { - for (int j = 0; j < vertices.size(); j++) { - matrix[i][j] = Integer.parseInt(args[0].split(",")[count].trim()); - count++; - } - } - DFSGraph dfsGraph = new DFSGraph(matrix, vertices); - int search = Integer.parseInt(args[2]); - System.out.println(dfsGraph.depthFirstSearch(0, 0, search)); - - } - - private static void handleError() { - System.out.println("Usage: please provide a tree in an adjacency matrix form " + - "(\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, " + - "0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") " + - "and the integer to find (\"4\")"); - } - - public static class DFSGraph { - - int[][] matrix; - List vertices; - List visited; - - public DFSGraph(int[][] matrix, List vertices) { - this.matrix = matrix; - this.vertices = vertices; - this.visited = new ArrayList<>(vertices.size()); - } - - public int getNextNodeIndex(int row, int current_column) { - for (int i = current_column; i < vertices.size(); i++) { - if (!visited.contains(vertices.get(i)) && matrix[row][i] == 1) { - return i; - } - } - return -1; - } - - public boolean depthFirstSearch(int row, int column, int search) { - // if the current node is the search node, return true - boolean found = this.vertices.get(row) == search; - if (found) { - return true; - } - // if the current node is the first search node, that is not a valid connection, - // get the next node of the current row - if (matrix[row][column] == 0) { - int nextNodeIndex = getNextNodeIndex(row, column); - if (nextNodeIndex == -1) { - return false; - } else { - column = nextNodeIndex; - } - } - // mark the current node as visited - visited.add(vertices.get(row)); - while (getNextNodeIndex(row, column) != -1) { - boolean f = depthFirstSearch(getNextNodeIndex(row, column), row, search); - if (f) { - return true; - } - column++; - } - return false; - } - - } -} - -``` - -{% endraw %} - -Depth First Search in [Java](/languages/java) was written by: - -- koishi-dream - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/javascript/index.md b/docs/projects/depth-first-search/javascript/index.md deleted file mode 100644 index 0a0e922183..0000000000 --- a/docs/projects/depth-first-search/javascript/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- depth-first-search -- javascript -title: Depth First Search in JavaScript -title1: Depth First Search -title2: in JavaScript ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -"use strict"; - -const USAGE = - 'Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")'; - -/** - * Parses a comma-separated string into an array of numbers. - */ -const parseNumbers = (str) => - str - .split(",") - .filter((val) => val.trim() !== "") - .map(Number); - -/** - * Transforms a flat array into a 2D adjacency matrix. - */ -const buildMatrix = (flatArray) => { - const size = Math.sqrt(flatArray.length); - - if (!Number.isInteger(size)) { - throw new Error("Invalid matrix: must be a perfect square."); - } - - return Array.from({ length: size }, (_, i) => - flatArray.slice(i * size, (i + 1) * size), - ); -}; - -const dfs = (matrix, vertexValues, target) => { - const visited = new Set(); - - const search = (currentIndex) => { - if (visited.has(currentIndex)) return false; - visited.add(currentIndex); - - if (vertexValues[currentIndex] === target) return true; - - for (const [neighborIndex, isConnected] of matrix[currentIndex].entries()) { - if (isConnected === 1 && search(neighborIndex)) { - return true; - } - } - - return false; - }; - - return matrix.length > 0 ? search(0) : false; -}; - -const run = () => { - const [, , rawMatrix, rawValues, rawTarget] = process.argv; - - if (!rawMatrix || !rawValues || !rawTarget) { - console.error(USAGE); - process.exit(1); - } - - try { - const flatMatrix = parseNumbers(rawMatrix); - const vertexValues = parseNumbers(rawValues); - const target = Number(rawTarget); - - const matrix = buildMatrix(flatMatrix); - - if (vertexValues.length !== matrix.length) { - throw new Error("Vertex value count does not match matrix dimensions."); - } - - const result = dfs(matrix, vertexValues, target); - console.log(result); - } catch (_) { - console.error(USAGE); - process.exit(1); - } -}; - -run(); - -``` - -{% endraw %} - -Depth First Search in [JavaScript](/languages/javascript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/m4/index.md b/docs/projects/depth-first-search/m4/index.md deleted file mode 100644 index f13271e224..0000000000 --- a/docs/projects/depth-first-search/m4/index.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-19 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2025-11-09 -layout: default -tags: -- depth-first-search -- m4 -title: Depth First Search in m4 -title1: Depth First -title2: Search in m4 ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a tree in an adjacency matrix form 'dnl -`("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") 'dnl -`together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4") -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(varname, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(varname, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl 2D versions of "array_get" and "array_set" -dnl array2_get(varname, idx1, idx2) -define(`array2_get', `defn(format(``%s[%s][%s]'', `$1', `$2', `$3'))') - -dnl array2_set(varname, idx1, idx2, value) -define(`array2_set', `define(format(``%s[%s][%s]'', `$1', `$2', `$3'), `$4')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname["length"] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname["length"]] = arg -dnl varname["length"] = varname["length"] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl create_graph(conn_mtx_varname, vert_varname, graph_varname): -dnl // Create nodes -dnl graph_varname["length"] = vert_varname["length"] -dnl for i = 0 to conn_vert["length"] - 1: -dnl graph_varname[i]["value"] = vert_varname[i] -dnl graph_varname[i]["length"] = 0 -dnl -dnl // Connect children to nodes -dnl idx = 0 -dnl for i = 0 to vert_varname["length"] - 1: -dnl for j = 0 to vert_varname["length"] - 1: -dnl if conn_mtx_varname[idx] > 0: -dnl graph_varname[i][graph_varname[i]["length"]] = j -dnl graph_varname[i]["length"] = graph_varname[i]["length"] + 1 -dnl -dnl idx = idx + 1 -define(`create_graph', -`array_set(`$3', `length', array_get(`$2', `length'))dnl -_create_nodes(`$2', `$3', 0)dnl -_connect_children(`$1', `$2', `$3', 0, 0)dnl -'dnl -) - -dnl vert_varname=$1, graph_varname=$2, i=$3 -define(`_create_nodes', -`ifelse(eval($3 < array_get(`$1', `length')), 1, -`array2_set(`$2', `$3', `value', array_get(`$1', `$3'))dnl -array2_set(`$2', `$3', `length', 0)dnl -_create_nodes(`$1', `$2', incr($3))'dnl -)'dnl -) - -dnl conn_mtx_varname=$1, vert_varname=$2, graph_varname=$3, i=$4, idx=$5 -define(`_connect_children', -`ifelse(eval($4 < array_get(`$2', `length')), 1, -`_connect_children_inner(`$1', `$2', `$3', `$4', `$5', 0)dnl -_connect_children(`$1', `$2', `$3', incr($4), eval($5 + array_get(`$2', `length')))'dnl -)'dnl -) - -dnl conn_mtx_varname=$1, vert_varname=$2, graph_varname=$3, i=$4, idx=$5, j=$6 -define(`_connect_children_inner', -`ifelse(eval($6 < array_get(`$2', `length')), 1, -`ifelse(eval(array_get(`$1', $5) + 0 > 0), 1, -`array2_set(`$3', `$4', array2_get(`$3', `$4', `length'), `$6')dnl -array2_set(`$3', `$4', `length', incr(array2_get(`$3', `$4', `length')))'dnl -)dnl -_connect_children_inner(`$1', `$2', `$3', `$4', incr($5), incr($6))'dnl -)'dnl -) - -dnl depth_first_search(graph_varname, target): -dnl // Indicate nothing visited -dnl visited = "" -dnl -dnl // Indicate node not found -dnl found_node = -1 -dnl -dnl // Start depth first search at root (node 0) -dnl depth_first_search_rec(graph_varname, target, 0) -dnl -dnl return found_node -define(`depth_first_search', -`pushdef(`visited', `')dnl -pushdef(`found_node', `-1')dnl -depth_first_search_rec(`$1', `$2', 0)dnl -popdef(`visited')dnl -found_node`'dnl -popdef(`found_node')'dnl -) - -dnl depth_first_search_rec(graph_varname, target, node): -dnl // Note: visited is a string that looks like this: "||||..." -dnl // Since M4 does not have anything like a set, this is the easiest way to -dnl // represent it, and the "index" function can be used to see if a node has -dnl // been visited (negative if not visited) -dnl -dnl // If target value found, indicate node found -dnl if graph_varname[node]["value"] == target: -dnl found_node = node -dnl else: -dnl // Indicate node is visited -dnl visited = visited + "|" + node + "|" -dnl -dnl // For each child node -dnl for i = 0 to graph_varname[node]["length"] - 1 -dnl // If child node not visited -dnl if "|" + graph_varname[node][i] + "|" not in visited: -dnl // Recursively check this child node -dnl depth_first_search_rec(graph_varname, target, graph_varname[node][i]) -dnl -dnl // Exit loop if node found -dnl if found_node >= 0: -dnl break -define(`depth_first_search_rec', -`ifelse(eval(array2_get(`$1', `$3', `value') == $2), 1, -`define(`found_node', `$3')', -`define(`visited', visited`|$3|')dnl -_depth_first_search_rec(`$1', `$2', `$3', 0)'dnl -)'dnl -) - -dnl graph_varname=$1, target=$2, node=$3, i=$4 -define(`_depth_first_search_rec', -`ifelse(eval(found_node < 0 && $4 < array2_get(`$1', `$3', `length')), 1, -`ifelse(eval(index(visited, `|'array2_get(`$1', `$3', `$4')`|') < 0), 1, -`depth_first_search_rec(`$1', `$2', array2_get(`$1', `$3', `$4'))'dnl -)dnl -_depth_first_search_rec(`$1', `$2', `$3', incr($4))'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 3 || - !parse_int_list(`conn_mtx', ARGV1) || - !parse_int_list(`vert', ARGV2) || - !is_valid(ARGV3) -), 1, `show_usage()')dnl -create_graph(`conn_mtx', `vert', `graph')dnl -define(`node', depth_first_search(`graph', ARGV3))dnl -ifelse(eval(node >= 0), 1, `true', `false') - -``` - -{% endraw %} - -Depth First Search in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/mathematica/index.md b/docs/projects/depth-first-search/mathematica/index.md deleted file mode 100644 index d8b46e0eb4..0000000000 --- a/docs/projects/depth-first-search/mathematica/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- depth-first-search -- mathematica -title: Depth First Search in Mathematica -title1: Depth First Search -title2: in Mathematica ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Depth-first search option depthFirstSearch1 is based on the built-in DepthFirstScan: *) - -depthFirstSearch1 = Function[{ag, p, v}, - Module[{found = False}, - DepthFirstScan[ - AdjacencyGraph[p, ag], - "PrevisitVertex" -> Function[{u}, If[u == v, found = True]] - ]; - found]]; - -(* If that is considered cheating, then option depthFirstSearch2 implements it directly: *) - -depthFirstSearch2 = Function[{ag, p, v}, - Module[{f}, - f = Function[i, - p[[i]] == v \[Or] AnyTrue[ - Select[Range[i, Length[ag]], Positive[ag][[i, #]] &], - f]]; - f[1] (* start search at first node *) ]]; - -(* The outer function does the string parsing: *) - -depthFirstSearchMain = Function[{am, vs, v}, - Module[{e = "Usage: please provide a tree in an adjacency matrix form (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, \ -0\") together with a list of vertex values (\"1, 3, 5, 2, 4\") and the integer to find (\"4\")"}, - Catch[ - depthFirstSearch2 @@ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments to depth-first search *) { - If[Length[#] > 0, Partition[#, Sqrt[Length[#]]], Throw[e]] &[StringSplit[am, ", "]], - If[Length[#] > 0, #, Throw[e]] &[StringSplit[vs, ", "]], - If[StringLength[v] > 0, v, Throw[e]]}, - {-1} (* at each leaf *)]]]]; - - -(* Valid Tests *) - -Print /@ Apply[depthFirstSearchMain] /@ { - {"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0", "1, 3, 5, 2, 4", "1"}, - {"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0", "1, 3, 5, 2, 4", "4"}, - {"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0", "1, 3, 5, 2, 4", "5"}, - {"0", "1", "1"}, - {"0", "1", "6"}, - {"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0", "1, 3, 5, 2, 4", "7"} - }; - - -(* Invalid Tests *) - -depthFirstSearchMain["", "1, 3, 5, 2, 4", "4"] -depthFirstSearchMain["0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0", "", "1"] -depthFirstSearchMain["0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0", "1, 3, 5, 2, 4", ""] - -``` - -{% endraw %} - -Depth First Search in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/pascal/index.md b/docs/projects/depth-first-search/pascal/index.md deleted file mode 100644 index bdc9114554..0000000000 --- a/docs/projects/depth-first-search/pascal/index.md +++ /dev/null @@ -1,293 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- depth-first-search -- pascal -title: Depth First Search in Pascal -title1: Depth First -title2: Search in Pascal ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program DepthFirstSearch; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - Sysutils; - -type - TIntegerList = specialize TList; - TIntegerSet = specialize THashSet; - TIntegerStack = specialize TStack; - - TNode = class - private - FChildSet: TIntegerSet; - public - Id: integer; - Children: TIntegerList; - constructor Create(AId: integer); - destructor Destroy; override; - procedure AddChild(ChildId: integer); - end; - - TNodeDictionary = specialize TDictionary; - - { TTree } - - TTree = class - private - function ContainsNode(NodeId: integer): boolean; - public - RootId: integer; - Nodes: TNodeDictionary; - constructor Create(ARootId: integer); - destructor Destroy; override; - procedure AddNode(Node: TNode); - function GetNode(NodeId: integer): TNode; - end; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")'); - Halt(1); -end; - -{ TNode } - -constructor TNode.Create(AId: integer); -begin - Id := AId; - Children := TIntegerList.Create; - FChildSet := TIntegerSet.Create; -end; - -destructor TNode.Destroy; -begin - Children.Free; - FChildSet.Free; - inherited; -end; - -procedure TNode.AddChild(ChildId: integer); inline; -begin - if FChildSet.Add(ChildId) then - Children.Add(ChildId); -end; - -{ TTree } - -constructor TTree.Create(ARootId: integer); -begin - RootId := ARootId; - Nodes := TNodeDictionary.Create; -end; - -destructor TTree.Destroy; -var - Node: TNode; -begin - for Node in Nodes.Values do - Node.Free; - Nodes.Free; - inherited; -end; - -procedure TTree.AddNode(Node: TNode); inline; -begin - Nodes.AddOrSetValue(Node.Id, Node); -end; - -// Retrieves a node by ID, or returns nil if not found -function TTree.GetNode(NodeId: integer): TNode; inline; -begin - if not Nodes.TryGetValue(NodeId, Result) then - Result := nil; -end; - -function TTree.ContainsNode(NodeId: integer): boolean; inline; -begin - Result := Nodes.ContainsKey(NodeId); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Parts: TStringArray; - Part: string; - Value: integer; -begin - if S.Trim.IsEmpty then - ShowUsage; - - Parts := S.Split([',']); - Result := TIntegerList.Create; - try - for Part in Parts do - begin - if not TryStrToInt(Trim(Part), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; - - if Result.Count = 0 then - begin - Result.Free; - ShowUsage; - end; - except - on E: Exception do - begin - Result.Free; - ShowUsage; - end; - end; -end; - -// Build tree from adjacency matrix and vertices -function CreateTree(const AdjMatrix, Vertices: TIntegerList): TTree; -var - N, Row, Col, MatrixIndex: integer; - Node: TNode; - Vertex, AdjacentVertex: integer; -begin - N := Vertices.Count; - if (N = 0) or (AdjMatrix.Count <> N * N) then - ShowUsage; - - // Create all nodes and add to tree - Result := TTree.Create(Vertices.First); - for Row in Vertices do - Result.AddNode(TNode.Create(Row)); - - // Populate children based on adjacency matrix - MatrixIndex := 0; - for Row := 0 to N - 1 do - begin - Node := Result.GetNode(Vertices[Row]); - for Col := 0 to N - 1 do - begin - if AdjMatrix[MatrixIndex] <> 0 then - begin - AdjacentVertex := Vertices[Col]; - if not Result.ContainsNode(AdjacentVertex) then - begin - Result.Free; - ShowUsage; - end; - Node.AddChild(AdjacentVertex); - end; - Inc(MatrixIndex); - end; - end; -end; - -// Performs depth-first search for the target value. -// This uses the iterative version with a TStack for performance. -function DepthFirstSearch(Tree: TTree; Target: integer): boolean; -var - Stack: TIntegerStack; - Visited: TIntegerSet; - CurrentId: integer; - CurrentNode: TNode; - ChildId: integer; -begin - Result := False; - if Tree = nil then Exit; - - Stack := TIntegerStack.Create; - Visited := TIntegerSet.Create; - try - Stack.Capacity := Tree.Nodes.Count; - Visited.Capacity := Tree.Nodes.Count; - - Stack.Push(Tree.RootId); - - while Stack.Count > 0 do - begin - CurrentId := Stack.Pop; - - if not Visited.Add(CurrentId) then - Continue; - - if CurrentId = Target then - Exit(True); - - CurrentNode := Tree.GetNode(CurrentId); - if CurrentNode <> nil then - for ChildId in CurrentNode.Children do - Stack.Push(ChildId); - end; - finally - Stack.Free; - Visited.Free; - end; -end; - -var - AdjMatrix, Vertices: TIntegerList; - Target: integer; - Tree: TTree; -begin - if ParamCount <> 3 then - ShowUsage; - - AdjMatrix := ParseIntegerList(ParamStr(1)); - Vertices := ParseIntegerList(ParamStr(2)); - if not TryStrToInt(ParamStr(3), Target) then - ShowUsage; - - Tree := CreateTree(AdjMatrix, Vertices); - try - Writeln(BoolToStr(DepthFirstSearch(Tree, Target), 'true', 'false')); - finally - AdjMatrix.Free; - Vertices.Free; - Tree.Free; - end; -end. - -``` - -{% endraw %} - -Depth First Search in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/php/index.md b/docs/projects/depth-first-search/php/index.md deleted file mode 100644 index ad2e6ce2e6..0000000000 --- a/docs/projects/depth-first-search/php/index.md +++ /dev/null @@ -1,228 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-21 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2023-03-27 -layout: default -tags: -- depth-first-search -- php -title: Depth First Search in PHP -title1: Depth First -title2: Search in PHP ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -class Node -{ - public $id; - public $children; - - public function __construct($id) - { - $this->id = $id; - $this->children = array(); - } - - public function add_child(&$node) - { - array_push($this->children, $node); - } -} - -function create_tree($adjacency_matrix, $vertices) -{ - // Create nodes - $nodes = array_map( - function ($vertex) { return new Node($vertex); }, - $vertices - ); - - // Add child nodes to each node based on non-zero values of adjacency matrix - $index = 0; - $num_vertices = count($vertices); - $num_adjacencies = count($adjacency_matrix); - for ($row = 0; $row < $num_vertices && $index < $num_adjacencies; $row++) - { - for ($col = 0; $col < $num_vertices && $index < $num_adjacencies; $col++, $index++) - { - if ($adjacency_matrix[$index]) - { - $nodes[$row]->add_child($nodes[$col]); - } - } - } - - return $nodes; -} - -function depth_first_search($tree, $target) -{ - // Indicate no nodes visited - $visited = array(); - - // Perform depth first recursively starting at root of tree - return depth_first_search_rec($tree[0], $target, $visited); -} - -function &depth_first_search_rec(&$node, $target, &$visited) -{ - $found = NULL; - - // If node is invalid or value of this node matches target, return this node - if (is_null($node) || $node->id == $target) - { - return $node; - } - - // Indicate this node is visited - $visited[$node->id] = TRUE; - - // Perform depth first search on each unvisited child of this node (if any). - // Stop when match is found - foreach ($node->children as $child) - { - if (!array_key_exists($child->id, $visited)) - { - $found = depth_first_search_rec($child, $target, $visited); - $visited[$child->id] = TRUE; - if (!is_null($found)) - { - break; - } - } - } - - return $found; -} - -// Exit if too few arguments -if (count($argv) < 4) -{ - usage(); -} - -// Parse 1st command line argument. Exit if invalid or too few items -$adjacency_matrix = parse_int_array($argv[1]); -if ($adjacency_matrix === FALSE || count($adjacency_matrix) < 1) -{ - usage(); -} - -// Parse 2nd command line argument. Exit if invalid or too few items -$vertices = parse_int_array($argv[2]); -if ($vertices === FALSE || count($vertices) < 1) -{ - usage(); -} - -// Parse 3rd command line argument. Exit if invalid -$target = parse_int($argv[3]); -if ($target === FALSE) -{ - usage(); -} - -// Create tree -$tree = create_tree($adjacency_matrix, $vertices); - -// Run depth first search and indicate if value is found -$node = depth_first_search($tree, $target); -printf("%s\n", (!is_null($node) ? "true" : "false")); - -``` - -{% endraw %} - -Depth First Search in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/powershell/index.md b/docs/projects/depth-first-search/powershell/index.md deleted file mode 100644 index 583a6cc518..0000000000 --- a/docs/projects/depth-first-search/powershell/index.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-11 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2025-07-11 -layout: default -tags: -- depth-first-search -- powershell -title: Depth First Search in PowerShell -title1: Depth First Search -title2: in PowerShell ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a tree in an adjacency matrix form' ` - '("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0")' ` - 'together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -class Node { - [int]$Value - [Node[]]$Children - - Node([int]$value) { - $this.Value = $value - $this.Children = @() - } - - [void] Add([Node]$node) { - $this.Children += $node - } -} - -class Graph { - [Node[]]$Nodes - - Graph() { - $this.Nodes = @() - } - - [void] Add([Node]$node) { - $this.Nodes += $node - } - - [Node] DepthFirstSearch([int]$target) { - $visited = [Collections.Generic.HashSet[int]]::new() - return $this.DepthFirstSearch($this.Nodes[0], $target, $visited) - } - - hidden [Node] DepthFirstSearch([Node]$node, [int]$target, [Collections.Generic.HashSet[int]]$visited) { - # If invalid node or target value found, return this node - if (-not $node -or $node.Value -eq $target) { - return $node - } - - # Indicate this node is visited - [void]$visited.Add($node.Value) - - foreach ($child in $node.Children) { - # If this child not visited, - if ($child.Value -notin $visited) { - # Recursively search this child. If target value found, return the found node - $foundNode = $this.DepthFirstSearch($child, $target, $visited) - if ($foundNode) { - return $foundNode - } - } - } - - return $null - } -} - -function Create-Graph([int[]]$connectionMatrix, [int[]]$vertices) { - # Populate vertices - $graph = [Graph]::new() - foreach ($vertex in $vertices) { - $graph.Add([Node]::new($vertex)) - } - - # Populate children for each vertex based on connection matrix - $idx = 0 - $numVertices = $vertices.Length - for ($row = 0; $row -lt $numVertices; $row++) { - for ($col = 0; $col -lt $numVertices; $col++) { - if ($connectionMatrix[$idx++] -gt 0) { - $graph.Nodes[$row].Add($graph.Nodes[$col]) - } - } - } - - $graph -} - -if ($args.Length -lt 3 -or -not $args[0] -or -not $args[1]) { - Show-Usage -} - -try { - $connectionMatrix = Parse-IntList $args[0] - $vertices = Parse-IntList $args[1] - $target = [int]::Parse($args[2]) -} catch { - Show-Usage -} - -$graph = Create-Graph $connectionMatrix $vertices -$node = $graph.DepthFirstSearch($target) -Write-Output (($node) ? "true" : "false") - -``` - -{% endraw %} - -Depth First Search in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/python/index.md b/docs/projects/depth-first-search/python/index.md deleted file mode 100644 index d87ed13b2c..0000000000 --- a/docs/projects/depth-first-search/python/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Nazar Stepan -date: 2021-11-12 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2021-11-12 -layout: default -tags: -- depth-first-search -- python -title: Depth First Search in Python -title1: Depth First -title2: Search in Python ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def get_input(argv): - error_message = 'Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")' - - # check input - if len(argv) != 3: - print(error_message) - sys.exit(1) - tree, vertex_values, target = argv - if not tree or not vertex_values or not target: - print(error_message) - sys.exit(1) - - # convert strings to lists - tree = list(map(int, tree.split(', '))) - vertex_values = list(map(int, vertex_values.split(', '))) - tree = [tree[i: i + len(vertex_values)] for i in range(0, len(tree), len(vertex_values))] - target = int(target) - - return tree, vertex_values, target - -class TreeNode: - def __init__(self, val): - self.val = val - self.connected = [] - -def create_tree(tree, vertex_values): - nodes = {value: TreeNode(value) for value in vertex_values} - for i, row in enumerate(tree): - node = nodes[vertex_values[i]] - for j, is_connected in enumerate(row): - if j <= i: - continue - if is_connected: - node.connected.append(nodes[vertex_values[j]]) - head = nodes[vertex_values[0]] - return head - -def depth_first_search(node, target): - if node.val == target: - return True - for connected_node in node.connected: - if depth_first_search(connected_node, target): - return True - return False - -def main(): - tree, vertex_values, target = get_input(sys.argv[1:]) - tree_head = create_tree(tree, vertex_values) - if depth_first_search(tree_head, target): - print('true') - else: - print('false') - -if __name__ == '__main__': - main() - -``` - -{% endraw %} - -Depth First Search in [Python](/languages/python) was written by: - -- Nazar Stepan - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/ruby/index.md b/docs/projects/depth-first-search/ruby/index.md deleted file mode 100644 index 058b13d3a5..0000000000 --- a/docs/projects/depth-first-search/ruby/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- depth-first-search -- ruby -title: Depth First Search in Ruby -title1: Depth First -title2: Search in Ruby ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = 'Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")' - -def usage! - warn USAGE - exit 1 -end - -def parse_list(str) - str.split(",").map { Integer(it.strip) } -rescue ArgumentError, NoMethodError - usage! -end - -def matrix(flat) - n = Integer(Math.sqrt(flat.size)) - usage! unless n * n == flat.size - flat.each_slice(n).to_a -end - -def dfs(mat, vals, i, target, seen) - return true if vals[i] == target - return false if seen[i] - - seen[i] = true - - mat[i].each_with_index do |edge, j| - next unless edge == 1 - return true if dfs(mat, vals, j, target, seen) - end - - false -end - -tree_s, vals_s, target_s = ARGV -usage! if tree_s.nil? || vals_s.nil? || target_s.nil? - -tree = parse_list(tree_s) -vals = parse_list(vals_s) -target = begin - Integer(target_s) -rescue - usage! -end - -usage! unless vals.size * vals.size == tree.size - -mat = matrix(tree) - -puts dfs(mat, vals, 0, target, {}) - -``` - -{% endraw %} - -Depth First Search in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/rust/index.md b/docs/projects/depth-first-search/rust/index.md deleted file mode 100644 index 7ad28bbcbc..0000000000 --- a/docs/projects/depth-first-search/rust/index.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-11 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- depth-first-search -- rust -title: Depth First Search in Rust -title1: Depth First -title2: Search in Rust ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::collections::{HashMap, HashSet}; - -fn usage() -> ! { - println!( - "Usage: please provide a tree in an adjacency matrix form \ - (\"0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0\") \ - together with a list of vertex values (\"1, 3, 5, 2, 4\") \ - and the integer to find (\"4\")" - ); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -#[derive(Debug, Clone)] -struct Node { - id: i32, - children: HashSet, -} - -impl Node { - fn new(id: i32) -> Self { - Self {id: id, children: HashSet::::new()} - } - - fn add_child(&mut self, id: i32) { - self.children.insert(id); - } -} - -#[derive(Debug, Clone)] -struct Tree { - root_id: i32, - tree: HashMap, -} - -impl Tree { - fn new(root_id: i32) -> Self { - Self {root_id: root_id, tree: HashMap::::new()} - } - - fn add_node(&mut self, from_id: i32, node: &Node) { - self.tree.insert(from_id, node.clone()); - } - - fn get_node(&self, node_id: Option) -> Option { - match node_id { - None=> None, - Some(id) => self.tree.get(&id).cloned(), - } - } -} - -fn create_tree(adjacency_matrix: &Vec, vertices: &Vec) -> Tree { - // Create tree and add nodes - let mut tree: Tree = Tree::new(vertices[0]); - let mut nodes: Vec = vertices.iter() - .map(|id| Node::new(*id)) - .collect(); - - // Add child nodes to each node based on non-zero values of adjacency matrix - let mut adjacency_iter = adjacency_matrix.iter(); - let num_vertices = vertices.len(); - for row in 0..num_vertices { - for col in 0..num_vertices { - if *adjacency_iter.next().unwrap_or_else(|| &0) != 0 { - nodes[row].add_child(vertices[col]); - } - } - - tree.add_node(vertices[row], &nodes[row]); - } - - tree -} - -fn depth_first_search(tree: &Tree, target: i32) -> Option { - // Indicate no nodes visited - let mut visited: HashSet = HashSet::::new(); - - // Perform depth first recursively starting at root of tree - depth_first_search_rec( - tree, tree.get_node(Some(tree.root_id)), target, &mut visited - ) -} - -fn depth_first_search_rec( - tree: &Tree, node: Option, target: i32, visited: &mut HashSet -) -> Option { - // If invalid node, return it - if node.is_none() { - return node; - } - - // If target found, return it - let unwrapped_node: Node = node.clone().unwrap(); - if unwrapped_node.id == target { - return node; - } - - // Indicate this node is visited - visited.insert(unwrapped_node.id); - - // Perform depth first search on each unvisited child of this node (if any). - // Stop when match is found - let mut found: Option = None; - for child_id in unwrapped_node.children { - if !visited.contains(&child_id) { - visited.insert(child_id); - found = depth_first_search_rec( - tree, tree.get_node(Some(child_id)), target, visited - ); - if !found.is_none() { - break; - } - } - } - - found -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let adjacency_matrix: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 2nd command-line argument to list of integers - let vertices: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - - // Convert 3rd command-line argument to integer - let target: i32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Create tree - let tree = create_tree(&adjacency_matrix, &vertices); - - // Run depth first search and indicate if value is found - match depth_first_search(&tree, target) { - Some(_) => println!("true"), - None => println!("false"), - } -} - -``` - -{% endraw %} - -Depth First Search in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/swift/index.md b/docs/projects/depth-first-search/swift/index.md deleted file mode 100644 index 11f955e142..0000000000 --- a/docs/projects/depth-first-search/swift/index.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- depth-first-search -- swift -title: Depth First Search in Swift -title1: Depth First -title2: Search in Swift ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4") - """ - -extension Collection { - func chunked(into size: Int) -> [[Element]] { - stride(from: 0, to: count, by: size).map { offset in - let start = index(startIndex, offsetBy: offset) - let end = index(start, offsetBy: size, limitedBy: endIndex) ?? endIndex - return Array(self[start.. [Int]? { - let parts = input.split(separator: ",").map { $0.trimmed } - let values = parts.compactMap(Int.init) - - guard values.count == parts.count, !values.isEmpty else { - return nil - } - - return values -} - -func parseArguments(_ args: [String]) -> (adj: [[Int]], labels: [Int], target: Int)? { - guard args.count == 4, - let flat = parseList(args[1]), - let labels = parseList(args[2]), - let target = Int(args[3].trimmed), - flat.count == labels.count * labels.count - else { - return nil - } - - let adj = flat.chunked(into: labels.count) - return (adj, labels, target) -} - -func depthFirstSearch(adj: [[Int]], labels: [Int], target: Int) -> Bool { - guard !labels.isEmpty else { return false } - - var visited = Set() - - func dfs(_ node: Int) -> Bool { - guard !visited.contains(node) else { return false } - - if labels[node] == target { return true } - visited.insert(node) - - for (neighbor, edge) in adj[node].enumerated() where edge == 1 { - if dfs(neighbor) { return true } - } - - return false - } - - return dfs(0) -} - -guard let (adj, labels, target) = parseArguments(CommandLine.arguments) else { - print(usage) - exit(1) -} - -print(depthFirstSearch(adj: adj, labels: labels, target: target)) - -``` - -{% endraw %} - -Depth First Search in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/tcl/index.md b/docs/projects/depth-first-search/tcl/index.md deleted file mode 100644 index 79ca97c1ec..0000000000 --- a/docs/projects/depth-first-search/tcl/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2025-10-08 -layout: default -tags: -- depth-first-search -- tcl -title: Depth First Search in Tcl -title1: Depth First -title2: Search in Tcl ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 -package require struct ;# for struct::graph - -proc usage {} { - puts stderr {Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")} - exit 1 -} - -proc isInteger {x} { return [string is integer -strict $x] } - -proc parseList {s} { - set s [string trim $s] - if {$s eq ""} { usage } - - lmap t [split $s ","] { - set t [string trim $t] - if {![isInteger $t]} { usage } - set t - } -} - -proc createGraph {matrix vertices} { - set n [llength $vertices] - if {[llength $matrix] != [expr {$n * $n}]} { usage } - - set g [struct::graph] - foreach v $vertices { $g node insert $v } - - for {set i 0} {$i < $n} {incr i} { - for {set j 0} {$j < $n} {incr j} { - if {[lindex $matrix [expr {$i*$n + $j}]] != 0} { - set a [lindex $vertices $i] - set b [lindex $vertices $j] - $g arc insert $a $b - } - } - } - return $g -} - -proc dfsCommand {target visitedRef foundRef args} { - upvar $visitedRef visited - upvar $foundRef found - - set event [lindex $args 0] - set graph [lindex $args 1] - set node [lindex $args 2] - - # We're only interested in what happens once we enter a node, not when - # we leave it. - if {$event ne "enter"} { return } - - if {[lsearch -exact $visited $node] >= 0} { return } - - lappend visited $node - if {$node eq $target} { set found 1 } -} - -proc dfs {graph start target} { - set found 0 - set visited {} - - # Tcllib has DFS directly in struct::graph. However, to use it for this - # I need a callback to tell me whether the target was found. It is quite - # flexible, in typical Tcl fashion, but I don't need it to do very much. - $graph walk $start -type dfs -dir forward \ - -command [list dfsCommand $target visited found] - - return $found -} - -if {$argc != 3} { usage } - -set adjMatrix [parseList [lindex $argv 0]] -set vertices [parseList [lindex $argv 1]] -set target [lindex $argv 2] - -if {![isInteger $target]} { usage } - -set graph [createGraph $adjMatrix $vertices] -set root [lindex $vertices 0] - -puts [expr {[dfs $graph $root $target] ? "true" : "false"}] - - -``` - -{% endraw %} - -Depth First Search in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/typescript/index.md b/docs/projects/depth-first-search/typescript/index.md deleted file mode 100644 index e4b0142f9e..0000000000 --- a/docs/projects/depth-first-search/typescript/index.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- depth-first-search -- typescript -title: Depth First Search in TypeScript -title1: Depth First Search -title2: in TypeScript ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function printUsage(): void { - console.log( - 'Usage: please provide a tree in an adjacency matrix form ("0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0") together with a list of vertex values ("1, 3, 5, 2, 4") and the integer to find ("4")', - ); -} - -function parseList(input: string): number[] { - return input - .split(",") - .map((x) => x.trim()) - .filter(Boolean) - .map(Number); -} - -function buildMatrix(flat: number[]): number[][] { - const n = Math.sqrt(flat.length); - - if (!Number.isInteger(n)) { - throw new Error("Invalid matrix: must be square"); - } - - const matrix: number[][] = []; - - for (let i = 0; i < n; i++) { - matrix.push(flat.slice(i * n, i * n + n)); - } - - return matrix; -} - -function buildAdjList(matrix: number[][]): number[][] { - const n = matrix.length; - const adj: number[][] = Array.from({ length: n }, () => []); - - for (let i = 0; i < n; i++) { - for (let j = 0; j < n; j++) { - if (matrix[i][j] === 1) { - adj[i].push(j); - } - } - } - - return adj; -} - -class Graph { - constructor( - private adj: number[][], - private values: number[], - ) {} - - dfs(start: number, target: number): boolean { - const visited = new Array(this.adj.length).fill(false); - - const visit = (node: number): boolean => { - if (visited[node]) return false; - - visited[node] = true; - - if (this.values[node] === target) return true; - - for (const next of this.adj[node]) { - if (visit(next)) return true; - } - - return false; - }; - - return visit(start); - } -} - -function main(): void { - const [, , treeInput, valuesInput, targetInput] = process.argv; - - if (!treeInput || !valuesInput || !targetInput) { - printUsage(); - return; - } - - try { - const flatMatrix = parseList(treeInput); - const values = parseList(valuesInput); - const target = Number(targetInput); - - const matrix = buildMatrix(flatMatrix); - const adj = buildAdjList(matrix); - - if (values.length !== matrix.length) { - throw new Error("Vertex values length does not match matrix size"); - } - - const graph = new Graph(adj, values); - const found = graph.dfs(0, target); - - console.log(found ? "true" : "false"); - } catch { - printUsage(); - } -} - -main(); - -``` - -{% endraw %} - -Depth First Search in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/depth-first-search/visual-basic/index.md b/docs/projects/depth-first-search/visual-basic/index.md deleted file mode 100644 index e5b6c13a90..0000000000 --- a/docs/projects/depth-first-search/visual-basic/index.md +++ /dev/null @@ -1,245 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: depth-first-search-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- depth-first-search -- visual-basic -title: Depth First Search in Visual Basic -title1: Depth First Search -title2: in Visual Basic ---- - - - -Welcome to the [Depth First Search](/projects/depth-first-search) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Class Node - - Public ReadOnly Property Id As Integer - - Private ReadOnly _childrenSet As New HashSet(Of Integer) - Private ReadOnly _children As New List(Of Integer) - - Public ReadOnly Property Children As IReadOnlyList(Of Integer) - Get - Return _children - End Get - End Property - - Public Sub New(id As Integer) - Me.Id = id - End Sub - - Public Sub AddChild(childId As Integer) - If _childrenSet.Add(childId) Then - _children.Add(childId) - End If - End Sub - -End Class - -Public Class Tree - - Private ReadOnly _nodes As New Dictionary(Of Integer, Node) - - Public ReadOnly Property RootId As Integer - - Public Sub New(rootId As Integer) - Me.RootId = rootId - End Sub - - Public Sub AddNode(node As Node) - _nodes(node.Id) = node - End Sub - - Public Function TryGetNode(id As Integer, ByRef node As Node) As Boolean - Return _nodes.TryGetValue(id, node) - End Function - - Public ReadOnly Property Nodes As IReadOnlyCollection(Of Node) - Get - Return _nodes.Values - End Get - End Property - -End Class - -Public Module DepthFirstSearch - - Private Sub ShowUsage() - Console.Error.WriteLine( - "Usage: please provide a tree in an adjacency matrix form " & - "(""0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0"") " & - "together with a list of vertex values (""1, 3, 5, 2, 4"") and the integer to find (""4"")" - ) - End Sub - - - Public Function ParseIntegerList(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - Throw New ArgumentException("Input string is null or whitespace") - End If - - Dim parts = input.Split(","c, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) - Dim list As New List(Of Integer)(parts.Length) - - For Each part In parts - - Dim value As Integer - If Not Integer.TryParse(part, value) Then - Throw New ArgumentException($"Invalid integer value: '{part}'") - End If - - list.Add(value) - - Next - - If list.Count < 1 Then - Throw New ArgumentException("List must contain at least one integer") - End If - - Return list - - End Function - - - Public Function CreateTree(matrix As List(Of Integer), - vertices As List(Of Integer)) As Tree - - Dim n = vertices.Count - - If matrix.Count <> n * n Then - Throw New ArgumentException("Adjacency matrix size does not match vertex count squared") - End If - - Dim tree As New Tree(vertices(0)) - - For Each v In vertices - tree.AddNode(New Node(v)) - Next - - For row = 0 To n - 1 - - Dim node As Node = Nothing - If Not tree.TryGetNode(vertices(row), node) Then - Throw New ArgumentException("Missing node") - End If - - Dim baseIndex = row * n - - For col = 0 To n - 1 - - If matrix(baseIndex + col) <> 0 Then - node.AddChild(vertices(col)) - End If - - Next - - Next - - Return tree - - End Function - - - Public Function DFS(tree As Tree, target As Integer) As Boolean - - Dim visited As New HashSet(Of Integer) - Dim stack As New Stack(Of Integer) - - stack.Push(tree.RootId) - - While stack.Count > 0 - - Dim current = stack.Pop() - - If Not visited.Add(current) Then - Continue While - End If - - If current = target Then - Return True - End If - - Dim node As Node = Nothing - If tree.TryGetNode(current, node) Then - For Each child In node.Children - stack.Push(child) - Next - End If - - End While - - Return False - - End Function - - - Public Function Main(args As String()) As Integer - - If args.Length <> 3 Then - ShowUsage() - Return 1 - End If - - Try - - Dim matrix = ParseIntegerList(args(0)) - Dim vertices = ParseIntegerList(args(1)) - - Dim target As Integer - If Not Integer.TryParse(args(2), target) Then - ShowUsage() - Return 1 - End If - - Dim tree = CreateTree(matrix, vertices) - Dim found = DFS(tree, target) - - Console.WriteLine(found.ToString().ToLowerInvariant()) - Return 0 - - Catch - ShowUsage() - Return 1 - End Try - - End Function - -End Module -``` - -{% endraw %} - -Depth First Search in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/ada/index.md b/docs/projects/dijkstra/ada/index.md deleted file mode 100644 index 0a36c18df3..0000000000 --- a/docs/projects/dijkstra/ada/index.md +++ /dev/null @@ -1,211 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-09 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-09 -layout: default -tags: -- ada -- dijkstra -title: Dijkstra in Ada -title1: Dijkstra -title2: in Ada ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Containers; use Ada.Containers; -with Ada.Containers.Vectors; - -procedure Dijkstra is - Data_Format_Error : exception; - - package Integer_Vectors is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - subtype Int_List is Integer_Vectors.Vector; - - INF : constant Integer := Integer'Last / 2; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide three inputs: a serialized matrix, a source node and a destination node"); - end Print_Usage; - - function To_Int_List (Raw : String) return Int_List is - Result : Int_List; - - Start : Positive := Raw'First; - Sep : Natural; - begin - if Raw'Length = 0 then - raise Data_Format_Error; - end if; - - loop - Sep := Index (Raw (Start .. Raw'Last), ","); - - declare - Last : constant Positive := - (if Sep = 0 then Raw'Last else Sep - 1); - - Item : constant String := - Trim (Raw (Start .. Last), Ada.Strings.Both); - begin - Result.Append (Integer'Value (Item)); - end; - - exit when Sep = 0; - Start := Sep + 1; - end loop; - - return Result; - end To_Int_List; - - function Dijkstra (Adj : Int_List; N, Src, Dst : Natural) return Integer is - Dist : array (Natural range 0 .. N - 1) of Integer := (others => INF); - Vis : array (Natural range 0 .. N - 1) of Boolean := (others => False); - - function Min_Node return Natural is - Best_Dist : Integer := INF; - Best_Node : Natural := 0; - begin - for I in 0 .. N - 1 loop - if not Vis (I) and then Dist (I) < Best_Dist then - Best_Dist := Dist (I); - Best_Node := I; - end if; - end loop; - - return Best_Node; - end Min_Node; - - U, V : Natural; - W : Integer; - begin - Dist (Src) := 0; - - for Step in 0 .. N - 1 loop - U := Min_Node; - Vis (U) := True; - - for V_Index in 0 .. N - 1 loop - W := Adj (U * N + V_Index); - - if W > 0 and then not Vis (V_Index) then - if Dist (U) + W < Dist (V_Index) then - Dist (V_Index) := Dist (U) + W; - end if; - end if; - end loop; - end loop; - - return Dist (Dst); - end Dijkstra; - -begin - - if Argument_Count /= 3 then - Print_Usage; - return; - end if; - - declare - Adj_Str : constant String := Argument (1); - Src_Str : constant String := Argument (2); - Dst_Str : constant String := Argument (3); - - Adj : Int_List; - N : Natural; - Src, Dst : Natural; - Result : Integer; - begin - - if Adj_Str'Length = 0 - or else Src_Str'Length = 0 - or else Dst_Str'Length = 0 - then - Print_Usage; - return; - end if; - - begin - Adj := To_Int_List (Adj_Str); - Src := Natural'Value (Src_Str); - Dst := Natural'Value (Dst_Str); - exception - when others => - Print_Usage; - return; - end; - - N := Natural (Sqrt (Float (Adj.Length))); - - if N = 0 or else N * N /= Natural (Adj.Length) then - Print_Usage; - return; - end if; - - if Src >= N or else Dst >= N then - Print_Usage; - return; - end if; - - for X of Adj loop - if X < 0 then - Print_Usage; - return; - end if; - end loop; - - Result := Dijkstra (Adj, N, Src, Dst); - - if Result >= INF then - Print_Usage; - else - Put_Line (Integer'Image (Result)); - end if; - - end; - -end Dijkstra; - -``` - -{% endraw %} - -Dijkstra in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/algol60/index.md b/docs/projects/dijkstra/algol60/index.md deleted file mode 100644 index 77b1a2d858..0000000000 --- a/docs/projects/dijkstra/algol60/index.md +++ /dev/null @@ -1,368 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-19 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-04-19 -layout: default -tags: -- algol60 -- dijkstra -title: Dijkstra in ALGOL 60 -title1: Dijkstra in -title2: ALGOL 60 ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide three inputs: a serialized matrix, " - "a source node and a destination node\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - boolean procedure validateInputs(weights, numWeights, src, dest, numVertices); - value numWeights, src, dest, numVertices; - integer array weights; - integer numWeights, src, dest, numVertices; - begin - boolean valid, anyNonZero; - integer i; - - valid := true; - - comment Validate number of weights and source and destination node; - if (numWeights != numVertices * numVertices | - src < 0 | src >= numVertices | dest < 0 | dest >= numVertices) - then valid := false; - - comment Verify weights greater than equal to zero and any non-zero - weights; - anyNonZero := false; - i := 0; - weightLoop: - i := i + 1; - if valid & i <= numWeights then - begin - if weights[i] > 0 then anyNonZero := true - else if weights[i] < 0 then valid := false; - goto weightLoop - end; - - if !anyNonZero then valid := false; - - validateInputs := valid - end validateInputs; - - comment Create graph from weights. - The graph is in this form: - - column 1: Number of edges for each node - - column 2, 4, ..., 2*n: Index of each child node - - column 3, 5, ..., 2*n+1: Weight of each child node - - where n = number of vertices; - procedure createGraph(graph, weights, numVertices); - value numVertices; - integer array graph, weights; - integer numVertices; - begin - integer u, v, idx, numEdges; - - idx := 0; - for u := 1 step 1 until numVertices do - begin - comment Initialize number of edges for this node; - numEdges := 0; - - for v := 1 step 1 until numVertices do - begin - idx := idx + 1; - if weights[idx] > 0 then - begin - comment Update number of edges, store child index and - weight; - numEdges := numEdges + 1; - graph[u, 2 * numEdges] := v; - graph[u, 2 * numEdges + 1] := weights[idx] - end - end; - - comment Store number of edges for this node; - graph[u, 1] := numEdges - end - end createGraph; - - comment Dijkstra's algorithm - Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode. - - Returns distances from source node to each node; - procedure dijkstra(graph, numVertices, dists); - value numVertices; - integer array graph, dists; - integer numVertices; - begin - integer procedure minDistance(q); - boolean array q; - begin - integer minDist, minIndex, v; - - minDist := maxint; - minIndex := 0; - for v := 1 step 1 until numVertices do - begin - if dists[v] < minDist & q[v] then - begin - minDist := dists[v]; - minIndex := v - end - end; - - minDistance := minIndex - end minDistance; - - integer idx, u, v, w, alt, numUnvisited; - boolean array q[1:numVertices]; - - comment Initialize distances to infinite and indicate all node are - unvisited; - numUnvisited := numVertices; - for v := 1 step 1 until numVertices do - begin - dists[v] := maxint; - q[v] := true - end; - - comment Set distance to source node to 0; - dists[src + 1] := 0; - - comment While any unvisited nodes,; - qloop: - if numUnvisited > 0 then - begin - comment Pick a vertex u in Q with minimum distance; - u := minDistance(q); - - comment Remove vertex u from Q; - if q[u] then numUnvisited := numUnvisited - 1; - q[u] := false; - - comment For each neighbor v of vertex u in still in Q; - for idx := 1 step 1 until graph[u, 1] do - begin - v := graph[u, idx * 2]; - if q[v] then - begin - comment Get trial distance; - w := graph[u, idx * 2 + 1]; - alt := dists[u] + w; - - comment If trial distance is smaller than distance v, - update distance to v; - if alt < dists[v] then dists[v] := alt - end - end; - - goto qloop - end - end dijkstra; - - integer argc, ch, src, dest, numWeights, numVertices, result; - integer array weights[1:1024]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 3 then usage; - - comment Get weights from 1st argument. Exit if invalid; - numWeights := inIntegerArray(weights, 1024); - if numWeights < 1 then usage; - - comment Get source node from 2nd argument. Exit if invalid; - if !inValidInteger(src, ch, false) then usage; - - comment Get destination node from 3rd argument. Exit if invalid; - if !inValidInteger(dest, ch, false) then usage; - - comment Validate inputs. Exit if invalid; - numVertices := sqrt(numWeights); - if !validateInputs(weights, numWeights, src, dest, numVertices) then usage; - - begin - comment Create graph based on weights; - integer array graph[1:numVertices, 1:2 * numVertices + 1]; - integer array dists[1:numVertices]; - createGraph(graph, weights, numVertices); - - comment Run Dijkstra's algorithm on graph and show distance to - destination; - dijkstra(graph, numVertices, dists); - outinteger(1, dists[dest + 1]) - end -end - -``` - -{% endraw %} - -Dijkstra in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/algol68/index.md b/docs/projects/dijkstra/algol68/index.md deleted file mode 100644 index 073464ba72..0000000000 --- a/docs/projects/dijkstra/algol68/index.md +++ /dev/null @@ -1,351 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-09 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2023-02-09 -layout: default -tags: -- algol68 -- dijkstra -title: Dijkstra in ALGOL 68 -title1: Dijkstra in -title2: ALGOL 68 ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: -( - printf(($gl$, "Usage: please provide three inputs: a serialized matrix, a source node and a destination node")) -); - -PROC validate inputs = (REF []INT weights, INT num vertices, INT src, INT dest) BOOL: -( - BOOL valid := TRUE; - - # Verify number of weights is a square # - INT num weigths := UPB weights; - IF num weights /= num vertices * num vertices - THEN - valid := FALSE - FI; - - # Verify weights greater than equal to zero and at any non-zero weights # - BOOL any non zero := FALSE; - FOR k TO num weights - WHILE valid - DO - IF weights[k] > 0 - THEN - any non zero := TRUE - FI; - - IF weights[k] < 0 - THEN - valid := FALSE - FI - OD; - - IF NOT any non zero - THEN - valid := FALSE - FI; - - # Verify source and destination are in range # - IF src < 0 OR src >= num vertices OR dest < 0 OR dest >= num vertices - THEN - valid := FALSE - FI; - - valid -); - -# Create graph based on weights # -MODE NODE = STRUCT(INT vertex, INT weight); -MODE NODES = REF []NODE; -MODE GRAPH = STRUCT(INT num vertices, REF []NODES edges); -PROC create graph = (INT num vertices, REF []INT weights) GRAPH: -( - HEAP [num vertices]NODES edges; - INT index := 0; - FOR u TO num vertices - DO - INT num edges := 0; - FOR v TO num vertices - DO - IF weights[index + v] > 0 - THEN - num edges +:= 1 - FI - OD; - - edges[u] := HEAP [num edges]NODE; - num edges := 0; - FOR v TO num vertices - DO - index +:= 1; - IF weights[index] > 0 - THEN - num edges +:= 1; - edges[u][num edges] := NODE(v, weights[index]) - FI - OD - OD; - - GRAPH(num vertices, edges) -); - -COMMENT -Dijkstra's algorithm -Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode -COMMENT -MODE DIJKSTRA_RESULT = STRUCT(REF []INT dists, REF []INT prevs); -PROC dijkstra = (GRAPH graph, INT src) DIJKSTRA_RESULT: -( - # Initialize distances to infinite and previous vertices to undefined # - # Set first vertex distange to 0 # - # Initialize unvisited nodes # - INT num vertices := num vertices OF graph; - HEAP [num vertices]INT dists; - HEAP [num vertices]INT prevs; - HEAP [num vertices]INT q; - INT num unvisited := num vertices; - FOR v TO num vertices - DO - dists[v] := max int; - prevs[v] := 0; - q[v] := v - OD; - - dists[src + 1] := 0; - - # While any unvisited nodes # - INT u; - INT v; - INT alt; - WHILE num unvisited > 0 - DO - # Pick a vertex u in Q with minimum distance # - u := min distance(dists, q); - - # Remove vertex u from Q # - IF q[u] > 0 - THEN - num unvisited -:= 1 - FI; - q[u] := 0; - - # For each neighbor v of vertex u in still in Q # - REF []NODE edges := (edges OF graph)[u]; - FOR index TO UPB edges - DO - v := vertex OF edges[index]; - IF q[v] > 0 - THEN - # Get trial distance # - alt := dists[u] + weight OF edges[index]; - - # If trial distance is smaller than distance v, update distance to v and # - # previous vertex of v # - IF alt < dists[v] - THEN - dists[v] := alt; - prevs[v] := u - FI - FI - OD - OD; - - DIJKSTRA_RESULT(dists, prevs) -); - -PROC min distance = (REF []INT dists, REF []INT q) INT: -( - INT min dist := max int; - INT min index; - FOR v TO UPB dists - DO - IF q[v] > 0 AND dists[v] < min dist - THEN - min dist := dists[v]; - min index := v - FI - OD; - - min index -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT weights := values OF list result; -INT num weights := UPB weights; -IF NOT valid OF list result -THEN - usage; - stop -FI; - -# Parse 2nd command-line argument # -s := argv(5); -PARSEINT_RESULT result := parse int(s); -INT src := value OF result; -IF NOT valid OF result -THEN - usage; - stop -FI; - -# Parse 3rd command-line argument # -s := argv(6); -result := parse int(s); -INT dest := value OF result; -IF NOT valid OF result -THEN - usage; - stop -FI; - -# Validate inputs # -INT num vertices := ENTIER(sqrt(num weights) + 0.5); -IF NOT validate inputs(weights, num vertices, src, dest) -THEN - usage; - stop -FI; - -# Create graph from weights # -GRAPH graph := create graph(num vertices, weights); - -# Run Dijkstra's algorithm on graph and show distance to destination # -DIJKSTRA_RESULT dijkstra result = dijkstra(graph, src); -INT dist := (dists OF dijkstra result)[dest + 1]; -printf(($gl$, whole(dist, 0))) - -``` - -{% endraw %} - -Dijkstra in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/awk/index.md b/docs/projects/dijkstra/awk/index.md deleted file mode 100644 index b048a66021..0000000000 --- a/docs/projects/dijkstra/awk/index.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-27 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2025-04-27 -layout: default -tags: -- awk -- dijkstra -title: Dijkstra in AWK -title1: Dijkstra -title2: in AWK ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide three inputs: a serialized matrix, a source node and a destination node" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -function validate_inputs(weights, num_weights, num_vertices, src, dest, i, any_non_zero) { - # Verify number of weights is a square, source and destination are valid - if (num_weights != num_vertices * num_vertices || \ - src < 0 || src >= num_vertices || \ - dest < 0 || dest >= num_vertices) { - return 0 - } - - # Verify weights greater than equal to zero and any non-zero weights - any_non_zero = 0 - for (i = 1; i <= num_weights; i++) { - if (weights[i] < 0) { - return 0 - } - - if (weights[i] > 0) { - any_non_zero = 1 - } - } - - return any_non_zero -} - -function create_graph(weights, num_vertices, graph, u, v, idx) { - idx = 0 - for (u = 0; u < num_vertices; u++) { - for (v = 0; v < num_vertices; v++) { - idx++ - if (weights[idx] > 0) { - graph[u][v] = weights[idx] - } - } - } -} - -# Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode -function dijkstra(graph, src, dists, prevs, u, v, q, alt) { - # Initialize distances to infinite and previous vertices to undefined - # Initialize unvisited nodes - for (v in graph) { - dists[v] = 1e999 # Awk doesn't have infinity, so use large integer - prevs[v] = 0 - q[v] = 1 - } - - # Set first vertex distance to 0 - dists[src] = 0 - - # While any unvisited nodes - while (length(q) > 0) { - # Pick a vertex u in Q with minimum distance - u = find_min_distance(dists, q) - - # Remove vertex u from Q - delete q[u] - - # For each neighbor v of vertex u still in Q - for (v in graph[u]) { - if (v in q) { - # Get trial distance - alt = dists[u] + graph[u][v] - - # If trial distance is smaller than distance v, update distance to v and - # previous vertex of v - if (alt < dists[v]) { - dists[v] = alt - prevs[v] = u - } - } - } - } -} - -function find_min_distance(dists, q, min_dist, min_index, v) { - min_dist = 1e999 - min_index = -1 - for (v in q) { - if (dists[v] < min_dist) { - min_dist = dists[v] - min_index = v - } - } - - return min_index -} - -BEGIN { - if (ARGC < 4) { - usage() - } - - str_to_array(ARGV[1], weights) - num_weights = length(weights) - src = str_to_number(ARGV[2]) - dest = str_to_number(ARGV[3]) - if (!num_weights || weights[1] == "ERROR" || src == "ERROR" || dest == "ERROR") { - usage() - } - - num_vertices = int(sqrt(num_weights) + 0.5) - if (!validate_inputs(weights, num_weights, num_vertices, src, dest)) { - usage() - } - - create_graph(weights, num_vertices, graph) - dijkstra(graph, src, dists, prevs) - print dists[dest] -} - -``` - -{% endraw %} - -Dijkstra in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/beef/index.md b/docs/projects/dijkstra/beef/index.md deleted file mode 100644 index d5447929a2..0000000000 --- a/docs/projects/dijkstra/beef/index.md +++ /dev/null @@ -1,311 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-26 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2024-02-26 -layout: default -tags: -- beef -- dijkstra -title: Dijkstra in Beef -title1: Dijkstra -title2: in Beef ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace System.Collections -{ - extension List - where T : IMinMaxValue - where int : operator T <=> T - { - public T Max() - { - T max = T.MinValue; - for (T val in this) - { - if (val > max) - { - max = val; - } - } - - return max; - } - } -} - -namespace Dijkstra; - -struct NodeItem -{ - public int mIndex; - public T mWeight; - - public this(int index, T weight) - { - mIndex = index; - mWeight = weight; - } -} - -class Node -{ - public int mIndex; - public List> mChildren = new .() ~ delete _; - - public this(int index) - { - mIndex = index; - } - - public void AddChild(int index, T weight) - { - mChildren.Add(.(index, weight)); - } -} - -class Tree -where int : operator T <=> T -{ - public List> mVertices = new .() ~ DeleteContainerAndItems!(_); - - public this(List weights, int numVertices) - { - // Create nodes - for (int index < numVertices) - { - mVertices.Add(new .(index)); - } - - int index = 0; - for (int row < numVertices) - { - for (int col < numVertices) - { - if (weights[index] > default(T)) - { - mVertices[row].AddChild(col, weights[index]); - } - - index++; - } - } - } -} - -struct DijkstraResult -{ - public int mPrev; - public T mDist; - - public this(int prev, T dist) - { - mPrev = prev; - mDist = dist; - } -} - -class Program -{ - public static void Usage() - { - Console.WriteLine( - "Usage: please provide three inputs: a serialized matrix, a source node and a destination node" - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - public static bool ValidateInputs(List weights, int numVertices, int src, int dest) - where T : IMinMaxValue - where int : operator T <=> T - { - // Verify the following: - // - Number of weights is a square - // - Any non-zero weights - // - Source and destination are in range - int numWeights = weights.Count; - return numWeights == numVertices * numVertices && - weights.Max() > default(T) && - src >= 0 && src < numWeights && - dest >= 0 && dest < numWeights; - } - - // Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode - public static void Dijkstra(Tree tree, int src, List> results) - where T : IMinMaxValue, operator T + T - where int : operator T <=> T - { - // Initialize distances to infinite and previous vertices to undefined - // Set source vertex distance to 0 - // Indicate all nodes unvisited - int numVertices = tree.mVertices.Count; - results.Clear(); - for (int index < numVertices) - { - results.Add(.(0, T.MaxValue)); - } - - results[src].mDist = default(T); - HashSet visited = scope . (); - - // While any unvisited nodes - while (visited.Count < numVertices) - { - // Pick a vertex u with minimum distance from unvisited nodes - int u = -1; - T minDist = T.MaxValue; - for (int index < numVertices) - { - T dist = results[index].mDist; - if (!visited.Contains(index) && dist < minDist) - { - u = index; - minDist = dist; - } - } - - // Indicate vertex u visited - visited.Add(u); - - // For each unvisited neighbor v of vertex u - for (NodeItem item in tree.mVertices[u].mChildren) - { - int v = item.mIndex; - T w = item.mWeight; - if (!visited.Contains(v)) - { - // Get trial distance - T alt = results[u].mDist + w; - - // If trial distance is smaller than distance v, update distance to v - // and update previous vertex - if (alt < results[v].mDist) - { - results[v] = .(u, alt); - } - } - } - } - } - - public static int Main(String[] args) - { - if (args.Count < 3) - { - Usage(); - } - - List weights = scope .(); - int numVertices = ?; - switch (ParseIntList(args[0], weights)) - { - case .Ok: - numVertices = (int)Math.Round(Math.Sqrt(weights.Count)); - - case .Err: - Usage(); - } - - int src = ?; - switch (ParseInt(args[1])) - { - case .Ok(out src): - case .Err: - Usage(); - } - - int dest = ?; - switch (ParseInt(args[2])) - { - case .Ok(out dest): - case .Err: - Usage(); - } - - if (!ValidateInputs(weights, numVertices, src, dest)) - { - Usage(); - } - - Tree tree = scope .(weights, numVertices); - List> results = scope .(); - Dijkstra(tree, src, results); - Console.WriteLine(results[dest].mDist); - - return 0; - } -} - -``` - -{% endraw %} - -Dijkstra in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/c-plus-plus/index.md b/docs/projects/dijkstra/c-plus-plus/index.md deleted file mode 100644 index c3bdf6b874..0000000000 --- a/docs/projects/dijkstra/c-plus-plus/index.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -authors: -- Ajay Maheshwari -- Ștefan-Iulian Alecu -date: 2022-10-06 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- dijkstra -title: Dijkstra in C++ -title1: Dijkstra -title2: in C++ ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -using Node = std::uint32_t; -using Weight = std::int64_t; -using Matrix = std::vector; - -constexpr Weight INF = std::numeric_limits::max() / 2; - -struct State { - Weight dist; - Node u; - - auto operator<=>(const State& other) const noexcept { - return dist <=> other.dist; - } -}; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide three inputs: a serialized matrix, a source node and a destination node)" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -template -std::optional to_num(std::string_view s) { - T value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional parse_weights(std::string_view s) { - if (s.empty()) return std::nullopt; - - Matrix m; - m.reserve(ranges::count(s, ',') + 1); - - auto weight_view = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | - views::transform(to_num); - - for (auto&& opt : weight_view) { - if (!opt) return std::nullopt; - m.push_back(*opt); - } - return m; -} - -Weight dijkstra(const Matrix& matrix, std::size_t n, Node src, Node dest) { - std::vector dist(n, INF); - dist[src] = 0; - - std::priority_queue, std::greater<>> pq; - pq.push({0, src}); - - while (!pq.empty()) { - auto [d, u] = pq.top(); - pq.pop(); - - if (u == dest) return d; - if (d > dist[u]) continue; - - auto row = matrix | views::drop(u * n) | views::take(n); - - for (std::size_t v = 0; v < n; ++v) { - const Weight w = row[v]; - if (w <= 0) continue; - - if (Weight new_dist = d + w; new_dist < dist[v]) { - dist[v] = new_dist; - pq.push({new_dist, static_cast(v)}); - } - } - } - - return dist[dest]; -} - -int main(int argc, char* argv[]) { - if (argc < 4) usage(); - - auto matrix_opt = parse_weights(argv[1]); - if (!matrix_opt) usage(); - - const auto matrix = std::move(*matrix_opt); - const std::size_t n = std::sqrt(matrix.size()); - - if (n == 0 || n * n != matrix.size()) usage(); - if (ranges::any_of(matrix, [](Weight w) { return w < 0; })) usage(); - - const auto source = to_num(argv[2]); - const auto destination = to_num(argv[3]); - - if (!source || *source >= n) usage(); - if (!destination || *destination >= n) usage(); - - const Weight result = dijkstra(matrix, n, *source, *destination); - - if (result >= INF) usage(); - std::cout << result << '\n'; -} -``` - -{% endraw %} - -Dijkstra in [C++](/languages/c-plus-plus) was written by: - -- Ajay Maheshwari -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/c-sharp/index.md b/docs/projects/dijkstra/c-sharp/index.md deleted file mode 100644 index 17a7fb0557..0000000000 --- a/docs/projects/dijkstra/c-sharp/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-29 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- dijkstra -title: Dijkstra in C# -title1: Dijkstra -title2: in C# ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if ( - args is not [var matrixRaw, var sourceRaw, var destRaw] - || !int.TryParse(sourceRaw, out int source) - || !int.TryParse(destRaw, out int dest) - || !TryParseList(matrixRaw.AsSpan(), out var matrix) -) - return Usage(); - -int n = (int)Math.Sqrt(matrix.Count); -if (n * n != matrix.Count || (uint)source >= n || (uint)dest >= n) - return Usage(); - -var graph = new List<(int, uint)>[n]; -for (int i = 0; i < n; i++) - graph[i] = []; - -for (int u = 0, k = 0; u < n; u++) - for (int v = 0; v < n; v++, k++) - if (matrix[k] != 0) - graph[u].Add((v, (uint)matrix[k])); - -uint result = Dijkstra(graph, source, dest); -if (result == uint.MaxValue) - return Usage(); - -Console.WriteLine(result); -return 0; - -static uint Dijkstra(List<(int to, uint w)>[] graph, int source, int destination) -{ - var dist = new uint[graph.Length]; - Array.Fill(dist, uint.MaxValue); - - var pq = new PriorityQueue(); - pq.Enqueue(source, dist[source] = 0); - - while (pq.TryDequeue(out int u, out uint d)) - { - if (d != dist[u]) - continue; - if (u == destination) - return d; - - foreach (var (v, w) in graph[u]) - { - uint newDist = d + w; - if (newDist < dist[v]) - pq.Enqueue(v, dist[v] = newDist); - } - } - - return uint.MaxValue; -} - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n) || n < 0) - return false; - - numbers.Add(n); - } - - return true; -} - -static int Usage() -{ - Console.Error.WriteLine( - "Usage: please provide three inputs: a serialized matrix, a source node and a destination node" - ); - return 1; -} - -``` - -{% endraw %} - -Dijkstra in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/c/index.md b/docs/projects/dijkstra/c/index.md deleted file mode 100644 index 6527a30854..0000000000 --- a/docs/projects/dijkstra/c/index.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-19 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- dijkstra -title: Dijkstra in C -title1: Dijkstra -title2: in C ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include -#include -#include - -#define MAX_NODES 100 - -int dijkstra(int graph[MAX_NODES][MAX_NODES], int src, int dest, int n) -{ - int dist[MAX_NODES]; - bool sptSet[MAX_NODES]; - - for (int i = 0; i < n; i++) - { - dist[i] = INT_MAX; - sptSet[i] = false; - } - - dist[src] = 0; - - for (int count = 0; count < n - 1; count++) - { - int min = INT_MAX, min_index; - - for (int v = 0; v < n; v++) - if (sptSet[v] == false && dist[v] <= min) - min = dist[v], min_index = v; - - int u = min_index; - sptSet[u] = true; - - for (int v = 0; v < n; v++) - if (!sptSet[v] - && graph[u][v] - && dist[u] != INT_MAX - && dist[u] + graph[u][v] < dist[v]) - dist[v] = dist[u] + graph[u][v]; - } - - return dist[dest] == INT_MAX ? -1 : dist[dest]; -} - -int main(int argc, char *argv[]) -{ - if (argc != 4) - { - printf("Usage: please provide three inputs: a serialized matrix, a " - "source node and a destination node\n"); - return 1; - } - - char *matrix = argv[1]; - char *src_str = argv[2]; - char *dest_str = argv[3]; - - // Check for empty inputs - if (strlen(matrix) == 0 || strlen(src_str) == 0 || strlen(dest_str) == 0) - { - printf("Usage: please provide three inputs: a serialized matrix, a " - "source node and a destination node\n"); - return 1; - } - - int src = atoi(src_str); - int dest = atoi(dest_str); - - long long n = 0; - for (size_t i = 0; matrix[i]; i++) - if (matrix[i] == ',') - n++; - n = (long long)sqrt((double)n + 1); - - if (src < 0 || dest < 0 || src >= n || dest >= n) - { - printf("Usage: please provide three inputs: a serialized matrix, a " - "source node and a destination node\n"); - return 1; - } - - int graph[MAX_NODES][MAX_NODES] = {0}; - char *token = strtok(matrix, ", "); - for (int i = 0; i < n && token; i++) - { - for (int j = 0; j < n && token; j++) - { - int weight = atoi(token); - if (weight < 0) - { - printf("Usage: please provide three inputs: a serialized " - "matrix, a source node and a destination node\n"); - return 1; - } - graph[i][j] = weight; - token = strtok(NULL, ", "); - } - } - - int result = dijkstra(graph, src, dest, (int)n); - if (result == -1) - { - printf("Usage: please provide three inputs: a serialized matrix, a " - "source node and a destination node\n"); - } - else - { - printf("%d\n", result); - } - - return 0; -} - -``` - -{% endraw %} - -Dijkstra in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/cobol/index.md b/docs/projects/dijkstra/cobol/index.md deleted file mode 100644 index ae495db78e..0000000000 --- a/docs/projects/dijkstra/cobol/index.md +++ /dev/null @@ -1,218 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-01 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-01 -layout: default -tags: -- cobol -- dijkstra -title: Dijkstra in COBOL -title1: Dijkstra -title2: in COBOL ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. dijkstra. - -data division. -working-storage section. - -01 matrix-input pic x(5000). -01 source-input pic x(16). -01 dest-input pic x(16). - -01 usage-msg pic x(200) - value 'Usage: please provide three inputs: a serialized matrix, a source node and a destination node'. - -01 n pic 9(4) comp. -01 i pic 9(4) comp. -01 j pic 9(4) comp. - -01 src pic 9(4) comp. -01 dst pic 9(4) comp. - -01 cnt pic 9(4) comp. -01 ptr pic 9(4) comp. -01 token pic x(32). - -01 min-dist pic 9(9) comp. -01 min-index pic 9(4) comp. - -01 cell-values pic 9(9) comp occurs 10000 times. - -01 visited. - 05 vis pic 9 comp occurs 100 times. - -01 dist. - 05 d pic 9(9) comp occurs 100 times. - -01 matrix. - 05 matrix-cell pic 9(9) comp occurs 10000 times. - -01 out-num pic z(9)9. - -procedure division. - -main. - accept matrix-input from argument-value - accept source-input from argument-value - accept dest-input from argument-value - - if matrix-input = spaces - or source-input = spaces - or dest-input = spaces - perform show-usage - end-if - - if source-input(1:1) = "-" and function length(function trim(source-input)) > 1 - perform show-usage - end-if - - if dest-input(1:1) = "-" and function length(function trim(dest-input)) > 1 - perform show-usage - end-if - - move function numval(source-input) to src - move function numval(dest-input) to dst - - if src < 0 or dst < 0 - perform show-usage - end-if - - perform parse-matrix - - if n = 0 - perform show-usage - end-if - - if src >= n or dst >= n - perform show-usage - end-if - - perform dijkstra - - if d(dst) = 999999999 - perform show-usage - end-if - - move d(dst) to out-num - display function trim(out-num) - goback. - - -parse-matrix. - move 0 to cnt - move 1 to ptr - - perform until ptr > function length(function trim(matrix-input)) - - move spaces to token - - unstring matrix-input - delimited by "," - into token - with pointer ptr - end-unstring - - if token not = spaces - - if function numval(token) < 0 - perform show-usage - end-if - - add 1 to cnt - move function numval(token) to matrix-cell(cnt) - end-if - - end-perform - - compute n = function integer(function sqrt(cnt)) - - if n * n not = cnt - perform show-usage - end-if. - - -dijkstra. - perform varying i from 0 by 1 until i > n - 1 - move 999999999 to d(i) - move 0 to vis(i) - end-perform - - move 0 to d(src) - - perform varying i from 0 by 1 until i > n - 1 - - move 999999999 to min-dist - move -1 to min-index - - perform varying j from 0 by 1 until j > n - 1 - if vis(j) = 0 and d(j) < min-dist - move d(j) to min-dist - move j to min-index - end-if - end-perform - - if min-index = -1 - exit perform - end-if - - move 1 to vis(min-index) - - perform varying j from 0 by 1 until j > n - 1 - - if vis(j) = 0 - and matrix-cell((min-index * n) + j + 1) > 0 - and d(min-index) not = 999999999 - - if d(min-index) + matrix-cell((min-index * n) + j + 1) < d(j) - compute d(j) = - d(min-index) + matrix-cell((min-index * n) + j + 1) - end-if - end-if - - end-perform - - end-perform. - - -show-usage. - display usage-msg - stop run. -``` - -{% endraw %} - -Dijkstra in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/commodore-basic/index.md b/docs/projects/dijkstra/commodore-basic/index.md deleted file mode 100644 index 8434cbd41f..0000000000 --- a/docs/projects/dijkstra/commodore-basic/index.md +++ /dev/null @@ -1,239 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-23 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2023-10-23 -layout: default -tags: -- commodore-basic -- dijkstra -title: Dijkstra in Commodore BASIC -title1: Dijkstra in -title2: Commodore BASIC ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -15 REM Graph: -16 REM - G%(i, j, 0) contains vertex index for child node j, vertex i or -17 REM negative to indicate no more child nodes -18 REM - G%(i, j, 1) contains weight between vertex i and child node j -20 DIM G%(9, 10, 1) -25 REM Dijkstra result -26 REM - DR(i, 0) contains vertex index of previous node of node i -27 REM - DR(i, 1) contains distance between previous node of node i and node i -28 REM - DR(i, 2) contains 1 if node i visited, 0 otherwise -30 DIM DR(9, 2) -35 REM Get weights -40 GOSUB 2000 -50 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -55 REM Get source node -60 GOSUB 1000 -70 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -80 NS = NR -85 REM Get destination node -90 GOSUB 1000 -100 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -110 ND = NR -115 REM Validate inputs -120 GOSUB 3000 -130 IF V = 0 THEN GOTO 200: REM invalid inputs -135 REM Form graph -140 GOSUB 2500 -145 REM Perform Dijkstra's algorithm and show result -150 GOSUB 3500 -160 S$ = MID$(STR$(DR(ND, 1)), 2) -170 PRINT S$ -180 END -200 PRINT "Usage: please provide three inputs: a serialized matrix, "; -210 PRINT "a source node and a destination node" -220 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -2500 REM Form graph -2501 REM Inputs: -2502 REM - A contains weights -2504 REM - NV contains number of vertices -2505 REM Output: G% contains graph -2510 K = -1 -2520 FOR I = 0 TO NV - 1 -2530 N = -1 -2540 FOR J = 0 TO NV - 1 -2550 K = K + 1 -2560 IF A(K) <= 0 THEN GOTO 2600 -2570 N = N + 1 -2580 G%(I, N, 0) = J -2590 G%(I, N, 1) = A(K) -2600 NEXT J -2610 G%(I, N + 1, 0) = -1: REM End of child nodes -2620 G%(I, N + 1, 1) = 0 -2630 NEXT I -2640 RETURN -3000 REM Validate inputs -3001 REM Inputs: -3002 REM - A contains weights -3003 REM - NA contains number of weights -3004 REM - ND contains destination node -3005 REM - NS contains source node -3005 REM Outputs: -3006 REM - V is 1 if valid, 0 otherwise -3007 REM - NV contains the number of vertices -3010 V = 0: REM assume invalid -3020 REM Verify number of weights is a square -3030 NV = INT(SQR(NA) + 0.5) -3040 IF NA <> (NV * NV) THEN GOTO 3160 -3055 REM Verify weights greater than zero, and at least one non-zero weight -3060 NZ = 0 -3070 I = -1 -3080 I = I + 1 -3090 IF I >= NV THEN GOTO 3130 -3100 IF A(I) < 0 THEN GOTO 3160 -3110 IF A(I) <> 0 THEN NZ = 1: REM Non-zero weight found -3120 GOTO 3080 -3130 IF NZ = 0 THEN GOTO 3160 -3135 REM Verify source and destination node -3140 IF NS < 0 OR NS >= NV OR ND < 0 OR ND >= NV THEN GOTO 3160 -3150 V = 1 -3160 RETURN -3500 REM Dijkstra's algorithm -3501 REM Source: -3502 REM https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode -3503 REM Inputs: -3504 REM - G% contains graph -3505 REM - NV contains number of vertices -3506 REM - NS contains source node -3507 REM Output: DR contains Dijkstra result -3510 REM Initialize distances to infinite and previous vertices to undefined -3511 REM Set source vertex distance to 0 -3512 REM Indicate all nodes unvisited -3520 FOR I = 0 TO NV - 1 -3530 DR(I, 0) = -1 -3540 DR(I, 1) = 1.70141183E38: REM Infinity -3550 DR(I, 2) = 0 -3560 NEXT I -3570 DR(NS, 1) = 0 -3575 REM While any unvisited nodes -3580 FOR I = 0 TO NV - 1 -3585 REM Pick a vertex u with minimum distance from unvisited nodes -3590 MD = 1.70141183E38: REM Infinity -3600 U = -1 -3610 FOR J = 0 TO NV - 1 -3620 IF DR(J, 2) <> 0 OR DR(J, 1) >= MD THEN GOTO 3650 -3630 MD = DR(J, 1) -3640 U = J -3650 NEXT J -3655 REM Indicate vertex u visited -3660 DR(U, 2) = 1 -3665 REM For each unvisited neighbor v of vertex u -3670 J = -1 -3680 J = J + 1 -3690 V = G%(U, J, 0) -3700 W = G%(U, J, 1) -3710 IF V < 0 THEN GOTO 3780 -3720 IF DR(V, 2) <> 0 THEN GOTO 3680 -3725 REM Get trial distance -3730 TD = DR(U, 1) + W -3735 REM If trial distance is smaller than distance v, update distance to -3736 REM v and previous vertex of v -3740 IF TD >= DR(V, 1) THEN GOTO 3680 -3750 DR(V, 0) = U -3760 DR(V, 1) = TD -3770 GOTO 3680 -3780 NEXT I -3790 RETURN - -``` - -{% endraw %} - -Dijkstra in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/euphoria/index.md b/docs/projects/dijkstra/euphoria/index.md deleted file mode 100644 index 1856c090a4..0000000000 --- a/docs/projects/dijkstra/euphoria/index.md +++ /dev/null @@ -1,299 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-28 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2023-02-28 -layout: default -tags: -- dijkstra -- euphoria -title: Dijkstra in Euphoria -title1: Dijkstra in -title2: Euphoria ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/utils.e -include std/math.e -include std/mathcons.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n" - ) - abort(0) -end procedure - -function validate_inputs(sequence weights, integer num_vertices, integer src, integer dest) - -- Verify number of weights is a square - integer num_weights = length(weights) - if num_weights != num_vertices * num_vertices - then - return FALSE - end if - - -- Verify weights greater than equal to zero and any non-zero weights - if min(weights) < 0 or max(weights) <= 0 - then - return FALSE - end if - - -- Verify source and destination are in range - if src < 0 or src >= num_vertices or dest < 0 or dest >= num_vertices - then - return FALSE - end if - - return TRUE -end function - --- Indices for node values -enum NODE_INDEX, NODE_WEIGHT - --- Create graph from weights. --- The graph consists of a sequence of nodes. --- Each node consists of a weight and sequence of neighbor indices -function create_graph(sequence weights, integer num_vertices) - -- Initialize nodes - sequence nodes = repeat({}, num_vertices) - - -- Get neighbors for this node based on weights - integer num_weights = length(weights) - integer index = 0 - for row = 1 to num_vertices - do - -- Add neighbor node indices and weights to this node - for col = 1 to num_vertices - do - index += 1 - if weights[index] > 0 - then - nodes[row] &= {{col, weights[index]}} - end if - end for - end for - - return nodes -end function - --- Indices for return values from dijkstra() -enum DIJKSTRA_DISTS, DIIJKSTRA_PREVS - --- Dijkstra's algorithm --- Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode -function dijkstra(sequence graph, integer src) - -- Initialize distances to infinite and previous vertices to undefined - -- Set first vertex distance to 0 - integer num_vertices = length(graph) - sequence dists = repeat(PINF, num_vertices) - sequence prevs = repeat(0, num_vertices) - sequence q = repeat(0, num_vertices) - for v = 1 to num_vertices - do - q[v] = v - end for - - dists[src + 1] = 0 - - -- Initialize unvisited nodes - integer num_unvisited = num_vertices - - -- While any unvisited nodes - integer u - integer v - integer alt - while num_unvisited > 0 - do - -- Pick a vertex u in Q with minimum distance - u = min_distance(dists, q) - - -- Remove vertex u from Q - if q[u] > 0 - then - num_unvisited -= 1 - end if - q[u] = 0 - - -- For each neighbor v of vertex u in still in Q - for index = 1 to length(graph[u]) - do - v = graph[u][index][NODE_INDEX] - if q[v] > 0 - then - -- Get trial distance - alt = dists[u] + graph[u][index][NODE_WEIGHT] - - -- If trial distance is smaller than distance v, update distance to v and - -- previous vertex of v - if alt < dists[v] - then - dists[v] = alt - prevs[v] = u - end if - end if - end for - end while - - return {dists, prevs} -end function - -function min_distance(sequence dists, sequence q) - atom min_dist = PINF - integer min_index - for v = 1 to length(dists) - do - if q[v] > 0 and dists[v] < min_dist - then - min_dist = dists[v] - min_index = v - end if - end for - - return min_index -end function - --- Check command-line arguments -sequence argv = command_line() -if ( - length(argv) < 4 - or length(argv[4]) = 0 - or length(argv[5]) = 0 - or length(argv[6]) = 0 -) -then - usage() -end if - --- Parse 1st command-line argument -sequence list_result = parse_int_list(argv[4]) -sequence weights = list_result[PARSE_INT_LIST_VALUES] -if not list_result[PARSE_INT_LIST_VALID] -then - usage() -end if - --- Parse 2nd command-line argument -sequence result = parse_int(argv[5]) -integer src = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] -then - usage() -end if - --- Parse 3rd command-line argument -result = parse_int(argv[6]) -integer dest = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] -then - usage() -end if - --- Validate inputs -integer num_weights = length(weights) -integer num_vertices = round(sqrt(num_weights)) -if not validate_inputs(weights, num_vertices, src, dest) -then - usage() -end if - --- Create graph from weights -sequence graph = create_graph(weights, num_vertices) - --- Run Dijkstra's algorithm on graph and show distance to destination -sequence dijkstra_result = dijkstra(graph, src) -integer dist = dijkstra_result[DIJKSTRA_DISTS][dest + 1] -printf(STDOUT, "%d\n", dist) - -``` - -{% endraw %} - -Dijkstra in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/f-sharp/index.md b/docs/projects/dijkstra/f-sharp/index.md deleted file mode 100644 index 054f854b03..0000000000 --- a/docs/projects/dijkstra/f-sharp/index.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- dijkstra -- f-sharp -title: Dijkstra in F# -title1: Dijkstra -title2: in F# ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System -open System.Collections.Generic - -let usage = - "Usage: please provide three inputs: a serialized matrix, a source node and a destination node" - -module Dijkstra = - - let private search (adj: (int * int) list[]) (src: int) (dst: int) = - let n = adj.Length - let dists = Array.create n Int32.MaxValue - let visited = Array.create n false - dists.[src] <- 0 - - let pq = PriorityQueue() - pq.Enqueue(src, 0) - - while pq.Count > 0 do - let u = pq.Dequeue() - - if not visited.[u] then - visited.[u] <- true - - if u <> dst then - for v, w in adj.[u] do - if not visited.[v] then - let alt = dists.[u] + w - - if alt < dists.[v] then - dists.[v] <- alt - pq.Enqueue(v, alt) - - match dists.[dst] with - | Int32.MaxValue -> Error usage - | x -> Ok(string x) - - let run (adj, src, dst) = search adj src dst - -module Helpers = - let private (|Int|_|) (s: string) = - match Int32.TryParse(s.Trim()) with - | true, n -> Some n - | _ -> None - - let private (|IntList|_|) (s: string) = - if String.IsNullOrWhiteSpace s then - None - else - let parts = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) |> Array.map (fun x -> x.Trim()) - - let rec parse idx acc = - if idx = parts.Length then - Some(Array.ofList (List.rev acc)) - else - match parts.[idx] with - | Int x -> parse (idx + 1) (x :: acc) - | _ -> None - - parse 0 [] - - let private withinBounds x n = x >= 0 && x < n - - let private isValid n (flat: int array) src dst = - n > 0 - && flat.Length = n * n - && withinBounds src n - && withinBounds dst n - && not (Array.exists ((>) 0) flat) // 0 > x - - let private (|MatrixInput|_|) (args: string array) = - match args with - | [| IntList flat; Int src; Int dst |] -> - let n = int (sqrt (float flat.Length)) - - if isValid n flat src dst then - let adj = - Array.init n (fun r -> - [ - for c in 0 .. n - 1 do - let w = flat.[r * n + c] - - if w > 0 then - yield (c, w) - ]) - - Some(adj, src, dst) - else - None - | _ -> None - - let parseArgs argv = - match argv with - | MatrixInput data -> Ok data - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.bind Dijkstra.run |> Helpers.handleResult - -``` - -{% endraw %} - -Dijkstra in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/go/index.md b/docs/projects/dijkstra/go/index.md deleted file mode 100644 index fb4423c3f7..0000000000 --- a/docs/projects/dijkstra/go/index.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- dijkstra -- go -title: Dijkstra in Go -title1: Dijkstra -title2: in Go ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "math" - "os" - "strconv" - "strings" -) - -const usage = `Usage: please provide three inputs: a serialized matrix, a source node and a destination node` - -func main() { - if len(os.Args) != 4 { - printUsage() - } - - matrix, errM := parseList(os.Args[1]) - source, errS := strconv.Atoi(os.Args[2]) - dest, errD := strconv.Atoi(os.Args[3]) - - if errM != nil || errS != nil || errD != nil { - printUsage() - } - - nFloat := math.Sqrt(float64(len(matrix))) - n := int(nFloat) - if nFloat != float64(n) || n == 0 { - printUsage() - } - - if source < 0 || source >= n || dest < 0 || dest >= n { - printUsage() - } - - for _, w := range matrix { - if w < 0 { - printUsage() - } - } - - cost, reachable := dijkstra(matrix, n, source, dest) - if !reachable { - printUsage() - } - - fmt.Println(cost) -} - -func dijkstra(matrix []int, n, start, end int) (int, bool) { - dist := make([]int, n) - visited := make([]bool, n) - - for i := range dist { - dist[i] = math.MaxInt32 - } - dist[start] = 0 - - for i := 0; i < n; i++ { - u := -1 - minDist := math.MaxInt32 - - for v := 0; v < n; v++ { - if !visited[v] && dist[v] < minDist { - u = v - minDist = dist[v] - } - } - - if u == -1 { - break - } - - visited[u] = true - if u == end { - return dist[u], true - } - - for v := 0; v < n; v++ { - weight := matrix[u*n+v] - if weight > 0 && !visited[v] { - newDist := dist[u] + weight - if newDist < dist[v] { - dist[v] = newDist - } - } - } - } - - if dist[end] == math.MaxInt32 { - return 0, false - } - return dist[end], true -} - -func parseList(input string) ([]int, error) { - if strings.TrimSpace(input) == "" { - return nil, fmt.Errorf("empty input") - } - - parts := strings.Split(input, ",") - nums := make([]int, 0, len(parts)) - for _, p := range parts { - val, err := strconv.Atoi(strings.TrimSpace(p)) - if err != nil { - return nil, err - } - nums = append(nums, val) - } - return nums, nil -} - -func printUsage() { - fmt.Println(usage) - os.Exit(1) -} -``` - -{% endraw %} - -Dijkstra in [Go](/languages/go) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/index.md b/docs/projects/dijkstra/index.md deleted file mode 100644 index fa6ccbed02..0000000000 --- a/docs/projects/dijkstra/index.md +++ /dev/null @@ -1,181 +0,0 @@ ---- -date: 2021-10-25 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- dijkstra -title: Dijkstra -title1: Dijkstra -title2: '' ---- - - - -Welcome to the Dijkstra page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Dijkstra's algorithm (or Dijkstra's Shortest Path First algorithm, SPF algorithm) -is an algorithm for finding the shortest paths between nodes in a graph, which -may represent, for example, road networks. It was conceived by computer scientist -Edsger W. Dijkstra in 1956 and published three years later. - -Dijkstra's algorithm doesn't work for graphs with negative weight edges. - -### Algorithm - -Below are the detailed steps used in Dijkstra's algorithm to find the shortest path -from a single source vertex to all other vertices in the given graph. - -1. Create a set sptSet (shortest path tree set) that keeps track - of vertices included in shortest path tree, i.e., whose minimum - distance from source is calculated and finalized. Initially, - this set is empty. -2. Assign a distance value to all vertices in the input graph. - Initialize all distance values as INFINITE. Assign distance - value as 0 for the source vertex so that it is picked first. -3. While sptSet doesn't include all vertices - 1. Pick a vertex u which is not there in sptSet and has minimum distance value. - 2. Include u to sptSet. - 3. Update distance value of all adjacent vertices of u. To update the distance - values, iterate through all adjacent vertices. For every adjacent vertex v, if - sum of distance value of u (from source) and weight of edge u-v, is less than - the distance value of v, then update the distance value of v. - -### Example - -Dijkstra's algorithm to find the shortest path between a and b. It picks -the unvisited vertex with the low distance, calculates the distance through -it to each unvisited neighbor, and updates the neighbor's distance if smaller. -Mark visited (set to red) when done with neighbors. - -![Dijkstra_Animation](https://user-images.githubusercontent.com/35429211/67672949-a2dcfd80-f981-11e9-862a-96bd0ec9ba83.gif) - - -## Requirements - -```console -./dijkstra.lang "0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0" "0" "1" -``` - -Here we've chosen to represent the matrix as a serialized list of integers. Since -the input string represents a square matrix, we should be able to take the -square root of the length to determine where the rows are in the string. In this -case, we have 25 values, so we must have 5 nodes. -If we reformat the input string as a matrix, we'll notice that the values in the -matrix represent the edge weight between each node. For example, we -could reformat our example to look something like the following: - -| Mapping | 0 | 1 | 2 | 3 | 4 | -| ------- | --- | --- | --- | --- | --- | -| 0 | 0 | 2 | 0 | 6 | 0 | -| 1 | 2 | 0 | 3 | 8 | 5 | -| 2 | 0 | 3 | 0 | 0 | 7 | -| 3 | 6 | 8 | 0 | 0 | 9 | -| 4 | 0 | 5 | 7 | 9 | 0 | - -Then we take the Source and the Destination. - -The Output will be the Cost of the Shortest Path from Source to Destination. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Dijkstra. -In order to keep things simple, we split up the testing as follows: - -- Dijkstra Valid Tests -- Dijkstra Invalid Tests - -### Dijkstra Valid Tests - -| Description | Matrix | Source | Destination | Output | -| ----------- | ------ | ------ | ----------- | ------ | -| Sample Input: Routine | "0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0" | "0" | "1" | "2" | - -### Dijkstra Invalid Tests - -| Description | Matrix | Source | Destination | -| ----------- | ------ | ------ | ----------- | -| No Input | | | | -| Empty Input | "" | "" | "" | -| Non-Square Input | "1, 0, 3, 0, 5, 1" | "1" | "2" | -| No Destination | "0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0" | "0" | "" | -| No Source Or Destination | "0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0" | "" | "" | -| Source Or Destination < 0 | "0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0" | "-1" | "2" | -| Weight < 0 | "0, 2, 0, -6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, -6, 8, 0, 0, 9, 0, 5, 7, 9, 0" | "1" | "2" | -| Source Or Destination > Number Of Vertices | "0, 2, 0, -6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, -6, 8, 0, 0, 9, 0, 5, 7, 9, 0" | "1" | "10" | -| No Way | "0, 0, 0, 0" | "0" | "1" | - -All of these tests should output the following: - -``` -Usage: please provide three inputs: a serialized matrix, a source node and a destination node -``` - - -## Articles - -There are 28 articles: - -- [Dijkstra in ALGOL 60](/projects/dijkstra/algol60) -- [Dijkstra in ALGOL 68](/projects/dijkstra/algol68) -- [Dijkstra in AWK](/projects/dijkstra/awk) -- [Dijkstra in Ada](/projects/dijkstra/ada) -- [Dijkstra in Beef](/projects/dijkstra/beef) -- [Dijkstra in C](/projects/dijkstra/c) -- [Dijkstra in C#](/projects/dijkstra/c-sharp) -- [Dijkstra in C++](/projects/dijkstra/c-plus-plus) -- [Dijkstra in COBOL](/projects/dijkstra/cobol) -- [Dijkstra in Commodore BASIC](/projects/dijkstra/commodore-basic) -- [Dijkstra in Euphoria](/projects/dijkstra/euphoria) -- [Dijkstra in F#](/projects/dijkstra/f-sharp) -- [Dijkstra in Go](/projects/dijkstra/go) -- [Dijkstra in Java](/projects/dijkstra/java) -- [Dijkstra in JavaScript](/projects/dijkstra/javascript) -- [Dijkstra in Mathematica](/projects/dijkstra/mathematica) -- [Dijkstra in PHP](/projects/dijkstra/php) -- [Dijkstra in Pascal](/projects/dijkstra/pascal) -- [Dijkstra in PowerShell](/projects/dijkstra/powershell) -- [Dijkstra in Python](/projects/dijkstra/python) -- [Dijkstra in Ruby](/projects/dijkstra/ruby) -- [Dijkstra in Rust](/projects/dijkstra/rust) -- [Dijkstra in Swift](/projects/dijkstra/swift) -- [Dijkstra in Tcl](/projects/dijkstra/tcl) -- [Dijkstra in TypeScript](/projects/dijkstra/typescript) -- [Dijkstra in Visual Basic](/projects/dijkstra/visual-basic) -- [Dijkstra in m4](/projects/dijkstra/m4) -- [Dijkstra in x86-64](/projects/dijkstra/x86-64) - -*** - - \ No newline at end of file diff --git a/docs/projects/dijkstra/java/index.md b/docs/projects/dijkstra/java/index.md deleted file mode 100644 index 4af828e204..0000000000 --- a/docs/projects/dijkstra/java/index.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- dijkstra -- java -title: Dijkstra in Java -title1: Dijkstra -title2: in Java ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -public class Dijkstra { - private static final int INF = Integer.MAX_VALUE; - - public static void main(String[] args) { - try { - if (args.length != 3 || Stream.of(args).anyMatch(String::isBlank)) { - throw new IllegalArgumentException(); - } - - final int[] weights = parseWeights(args[0]); - final int size = (int) Math.round(Math.sqrt(weights.length)); - - if (size * size != weights.length || size == 0) { - throw new IllegalArgumentException(); - } - - final int sourceNode = Integer.parseInt(args[1].trim()); - final int targetNode = Integer.parseInt(args[2].trim()); - - if (sourceNode < 0 || sourceNode >= size || - targetNode < 0 || targetNode >= size) { - throw new IllegalArgumentException(); - } - - int result = findShortestPath(weights, size, sourceNode, targetNode); - System.out.println(result); - - } catch (Exception e) { - System.err.println( - "Usage: please provide three inputs: a serialized matrix, a source node and a destination node" - ); - } - } - - private static int[] parseWeights(String input) { - return Pattern.compile(",") - .splitAsStream(input) - .map(String::trim) - .mapToInt(s -> { - int w = Integer.parseInt(s); - if (w < 0) throw new IllegalArgumentException(); - return w; - }) - .toArray(); - } - - record Node(int id, int cost) implements Comparable { - public int compareTo(Node o) { - return Integer.compare(this.cost, o.cost); - } - } - - private static int findShortestPath(int[] matrix, int n, int start, int target) { - if (start == target) return 0; - - int[] dist = new int[n]; - Arrays.fill(dist, INF); - dist[start] = 0; - - PriorityQueue pq = new PriorityQueue<>(); - pq.add(new Node(start, 0)); - - while (!pq.isEmpty()) { - Node cur = pq.poll(); - int u = cur.id(); - - if (cur.cost() > dist[u]) continue; - if (u == target) return dist[u]; - - for (int v = 0; v < n; v++) { - int w = matrix[u * n + v]; - if (w <= 0) continue; - - int nd = dist[u] + w; - - if (nd >= dist[v]) continue; - - dist[v] = nd; - pq.add(new Node(v, nd)); - } - } - - throw new NoSuchElementException(); - } -} -``` - -{% endraw %} - -Dijkstra in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/javascript/index.md b/docs/projects/dijkstra/javascript/index.md deleted file mode 100644 index 515febf7e1..0000000000 --- a/docs/projects/dijkstra/javascript/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Matteo Planchet -- rzuckerm -date: 2021-10-25 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- dijkstra -- javascript -title: Dijkstra in JavaScript -title1: Dijkstra in -title2: JavaScript ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -function main() { - - const mat = process.argv[2]; - const src = parseInt(process.argv[3]); - const des = parseInt(process.argv[4]); - - usage = "Usage: please provide three inputs: a serialized matrix, a source node and a destination node" - - if (isNaN(des) || isNaN(src) || !mat) { - return console.log(usage); - } - - const matList = mat.split(", "); - const len = matList.length; - const n = Math.sqrt(len); - - // Non-Square Input - if (n * n != len) { - return console.log(usage); - } - - // The Source or The Destination < 0 - if (src < 0 || des < 0) { - return console.log(usage); - } - - // Weight < 0 - if (matList.some(weight => weight < 0)) { - return console.log(usage); - } - - // Not any weight > 0 - if (!matList.some(weight => weight > 0)) { - return console.log(usage); - } - - // The Source or The Destination > SquareRootOfMatrix - 1 - if (src > n - 1 || des > n - 1) { - return console.log(usage); - } - - const mapping = []; - while (matList.length) { - mapping.push(matList.splice(0, n).map((i) => parseInt(i))); - } - - const dijkstra = (src, des, n) => { - // Create a priority queue to store nodes that - // are being preprocessed. - const q = []; - - // Create an array for distances and initialize all - // distances as infinite (Infinity) - const dist = new Array(n).fill(Infinity); - - // Insert source itself in priority queue and initialize - // its distance as 0. - // A node is a tuple with [id, cost] - q.push([src, 0]); - dist[src] = 0; - - while (q.length) { - let cur = q[0]; - q.shift(); - let u = cur[0]; - let cost = cur[1]; - - // Get all adjacent of u. - for (let i = 0; i < n; i++) { - let v = mapping[u][i]; - if (v == 0) continue; - - // If there is shorter path to v through u. - if (cost + v < dist[i]) { - // Updating distance of v - dist[i] = cost + v; - q.push([i, dist[i]]); - } - } - } - return dist[des]; - }; - - console.log(dijkstra(src, des, n)); -} - -main(); - -``` - -{% endraw %} - -Dijkstra in [JavaScript](/languages/javascript) was written by: - -- Jeremy Grifski -- Matteo Planchet -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/m4/index.md b/docs/projects/dijkstra/m4/index.md deleted file mode 100644 index 8f97430a61..0000000000 --- a/docs/projects/dijkstra/m4/index.md +++ /dev/null @@ -1,342 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-11-14 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2025-11-14 -layout: default -tags: -- dijkstra -- m4 -title: Dijkstra in m4 -title1: Dijkstra -title2: in m4 ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide three inputs: a serialized matrix, a source node and a destination node -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(varname, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(varname, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl 2D versions of "array_get" and "array_set" -dnl array2_get(varname, idx1, idx2) -define(`array2_get', `defn(format(``%s[%s][%s]'', `$1', `$2', `$3'))') - -dnl array2_set(varname, idx1, idx2, value) -define(`array2_set', `define(format(``%s[%s][%s]'', `$1', `$2', `$3'), `$4')') - -dnl 3D versions of "array_get" and "array_set" -dnl array3_get(varname, idx1, idx2, idx3) -define(`array3_get', `defn(format(``%s[%s][%s][%s]'', `$1', `$2', `$3', `$4'))') - -dnl array3_set(varname, idx1, idx2, idx3, value) -define(`array3_set', `define(format(``%s[%s][%s][%s]'', `$1', `$2', `$3', `$4'), `$5')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname["length"] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname["length"]] = arg -dnl varname["length"] = varname["length"] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl Reference: https://en.wikipedia.org/wiki/Integer_square_root#Algorithm_using_Newton's_method -dnl isqrt(n): -dnl if n < 2: -dnl return n -dnl prev2 = -1 -dnl prev1 = 1 -dnl while 1: -dnl x1 = (prev1 + n // prev1) // 2 -dnl -dnl // Case 1: converged (steady value) -dnl if x1 == prev1: -dnl return x1 -dnl -dnl // Case 2: oscillation (2-cycle) -dnl if x1 == prev2 and x1 != prev1: -dnl return min(prev1, x1) -dnl -dnl // Set up next values -dnl prev2, prev1 = prev1, x1 -define(`isqrt', `ifelse(eval($1 < 2), 1, $1, -`pushdef(`x1', 0)dnl -_isqrt($1, -1, 1)dnl -popdef(`x1')dnl -'dnl -)'dnl -) - -dnl n=$1, prev2=$2, prev1=$3 -define(`_isqrt', -`define(`x1', eval(($3 + $1 / $3) >> 1))dnl -ifelse(eval(x1 == $3), 1, x1, -`ifelse(eval(x1 == $2 && x1 != $3), 1, `min(`$3', x1)', `_isqrt(`$1', `$3', x1)')'dnl -)'dnl -) - -dnl min(a, b) -define(`min', `ifelse(eval($1 < $2), 1, $1, $2)') - -dnl validate_inputs(weights_varname, num_vertices, src, dest): -dnl // Verify number of weights is a square, source and destination are valid -dnl if (weights_varname["length"] != num_vertices * num_vertices or -dnl src < 0 or src >= num_vertices or dest < 0 or dest >= num_vertices): -dnl return 0 -dnl -dnl // Verify weights greater than equal to zero and any non-zero weights -dnl any_non_zero = 0 -dnl for i = 0 to weights_varname["length"] - 1 -dnl if weights_varname[i] < 0: -dnl return 0 -dnl -dnl if weights_varname[i] > 0: -dnl any_non_zero = 1 -dnl -dnl return any_non_zero -define(`validate_inputs', -`ifelse(eval(array_get(`$1', `length') != $2 * $2 || -$3 < 0 || $3 >= $2 || $4 < 0 || $4 >= $2), 1, 0, `validate_weights(`$1', 0, 0)'dnl -)'dnl -) - -dnl weights_varname=$1, i=$2, any_non_zero=$3 -define(`validate_weights', -`ifelse(eval($2 >= array_get(`$1', `length')), 1, `$3', -`ifelse(eval(array_get(`$1', `$2') < 0), 1, 0, -eval(array_get(`$1', `$2') > 0), 1, -`validate_weights(`$1', incr($2), 1)', `validate_weights(`$1', incr($2), `$3')'dnl -)'dnl -)'dnl -) - -dnl create_graph(weights_varname, num_vertices, graph_varname): -dnl // Create nodes -dnl graph_varname["length"] = num_vertices -dnl for i = 0 to num_vertices - 1: -dnl graph_varname[i]["length"] = 0 -dnl -dnl // Connect children to nodes -dnl idx = 0 -dnl for i = 0 to num_vertices - 1: -dnl for j = 0 to num_vertices - 1: -dnl if weight_mtx_varname[idx] > 0: -dnl graph_varname[i]["edge"][graph_varname[i]["length"]] = j -dnl graph_varname[i]["weight"][graph_varname[i]["length"]] = weights_varname[idx] -dnl graph_varname[i]["length"] = graph_varname[i]["length"] + 1 -dnl -dnl idx = idx + 1 -define(`create_graph', -`array_set(`$3', `length', `$2')dnl -_create_nodes(`$3', `$2', 0)dnl -_connect_children(`$1', `$2', `$3', 0, 0)dnl -'dnl -) - -dnl graph_varname=$1, num_vertices=$2, i=$3 -define(`_create_nodes', -`ifelse(eval($3 < $2), 1, -`array2_set(`$1', `$3', `length', 0)dnl -_create_nodes(`$1', `$2', incr($3))'dnl -)'dnl -) - -dnl weights_varname=$1, num_vertices=$2, graph_varname=$3, i=$4, idx=$5 -define(`_connect_children', -`ifelse(eval($4 < $2), 1, -`_connect_children_inner(`$1', `$2', `$3', `$4', `$5', 0)dnl -_connect_children(`$1', `$2', `$3', incr($4), eval($5 + $2))'dnl -)'dnl -) - -dnl weights_varname=$1, num_vertices=$2, graph_varname=$3, i=$4, idx=$5, j=$6 -define(`_connect_children_inner', -`ifelse(eval($6 < $2), 1, -`ifelse(eval(array_get(`$1', `$5') > 0), 1, -`array3_set(`$3', `$4', `edge', array2_get(`$3', `$4', `length'), `$6')dnl -array3_set(`$3', `$4', `weight', array2_get(`$3', `$4', `length'), array_get(`$1', $5))dnl -array2_set(`$3', `$4', `length', incr(array2_get(`$3', `$4', `length')))'dnl -)dnl -_connect_children_inner(`$1', `$2', `$3', `$4', incr($5), incr($6))'dnl -)'dnl -) - -dnl M4 does not have infinity so choose largest integer value as infinity -define(`INF', 2147483647) - -dnl Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode -dnl dijkstra(graph_varname, src, dists_varname): -dnl // Note: unvisited (q) is a string that looks like this: "||||..." -dnl // Since M4 does not have anything like a set, this is the easiest way to -dnl // represent it, and the "index" function can be used to see if a node is -dnl // unvisited (non-negative if unvisited) -dnl -dnl // Initialize distances to infinite and initialize unvisited nodes -dnl q = "" -dnl dists_varname["length"] = graph_varname["length"] -dnl for i = 0 to dists_varname["length"] - 1: -dnl dists_varname[i] = INF -dnl q = q + "|" + i + "|" -dnl -dnl // Set first vertex distance to 0 -dnl dists_varname[src] = 0 -dnl -dnl // While any unvisited nodes -dnl while q != "": -dnl // Pick a vertex u in q with minimum distance -dnl u = find_min_distance(dists_varname) -dnl -dnl // Remove vertex u from q -dnl q = replace(q, "|" + u + "|", "") -dnl -dnl // For each neighbor v of vertex u still in q -dnl for i = 0 to graph[u]["length"] - 1: -dnl v = graph_varname[u]["edge"][i] -dnl if ("|" + v + "|) in q: -dnl // Get trial distance. If it is smaller than distance v, update distance to v -dnl alt = add(dists_varname[u], graph_varname[u]["weight"][i]) -dnl if alt < dists_varname[v]: -dnl dists_varname[v] = alt -define(`dijkstra', -`pushdef(`q', `')dnl -pushdef(`u', `')dnl -pushdef(`v', `')dnl -pushdef(`alt', `')dnl -array_set(`$3', `length', array_get(`$1', `length'))dnl -_init_dijkstra_result(`$3', 0)dnl -array_set(`$3', `$2', 0)dnl -_dijkstra_outer(`$1', `$3')dnl -popdef(`alt')dnl -popdef(`v')dnl -popdef(`u')dnl -popdef(`q')dnl -') - -dnl dists_varname=$1, i=$2 -define(`_init_dijkstra_result', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`array_set(`$1', `$2', INF)dnl -define(`q', q`|$2|')dnl -_init_dijkstra_result(`$1', incr($2))'dnl -)'dnl -) - -dnl graph_varname=$1, dists_varname=$2 -define(`_dijkstra_outer', -`ifelse(q, `',, -`define(`u', find_min_distance(`$2'))dnl -define(`q', patsubst(q, `|'u`|'))dnl -_dijkstra_inner(`$1', `$2', 0)dnl -_dijkstra_outer(`$1', `$2')dnl -'dnl -)'dnl -) - -dnl graph_varname=$1, dists_varname=$2, i=$3 -define(`_dijkstra_inner', -`ifelse(eval($3 < array2_get(`$1', u, `length')), 1, -`define(`v', array3_get(`$1', u, `edge', `$3'))dnl -ifelse(eval(index(q, `|'v`|') >= 0), 1, -`define(`alt', add(array_get(`$2', u), array3_get(`$1', u, `weight', `$3')))dnl -ifelse(eval(alt < array_get(`$2', v)), 1, `array_set(`$2', v, alt)')dnl -')dnl -_dijkstra_inner(`$1', `$2', incr($3))dnl -'dnl -)'dnl -) - -dnl find_min_distance(dists_varname): -dnl min_dist = INF -dnl min_index = -1 -dnl for i = 0 to dists_varname["length"] - 1: -dnl if ("|" + i + "|") in q and dists_varname[i] < min_dist: -dnl min_dist = dists_varname[i] -dnl min_index = i -dnl return min_index -define(`find_min_distance', `_find_min_distance(`$1', INF, -1, 0)') - -dnl dists_varname=$1, min_dist=$2, min_index=$3, i=$4 -define(`_find_min_distance', -`ifelse(eval($4 >= array_get(`$1', `length')), 1, `$3', -`ifelse(eval(index(q, `|$4|') >= 0 && array_get(`$1', `$4') < $2), 1, -`_find_min_distance(`$1', array_get(`$1', `$4'), `$4', incr($4))', -`_find_min_distance(`$1', `$2', `$3', incr($4))'dnl -)'dnl -)'dnl -) - -dnl add(a, b): -dnl if a == INF or b == INF: -dnl return INF -dnl return a + b -define(`add', `ifelse(eval($1 == INF || $2 == INF), 1, INF, `eval($1 + $2)')') - -divert(0)dnl -ifelse(eval(ARGC < 3 || - !parse_int_list(`weights', ARGV1) || - !is_valid(ARGV2) || - !is_valid(ARGV3) -), 1, `show_usage()')dnl -define(`num_vertices', isqrt(array_get(`weights', `length')))dnl -ifelse(validate_inputs(weights, num_vertices, ARGV2, ARGV3), 0, `show_usage()')dnl -create_graph(`weights', num_vertices, `graph')dnl -dijkstra(`graph', ARGV2, `dists')dnl -array_get(`dists', ARGV3) - -``` - -{% endraw %} - -Dijkstra in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/mathematica/index.md b/docs/projects/dijkstra/mathematica/index.md deleted file mode 100644 index 2b50039c15..0000000000 --- a/docs/projects/dijkstra/mathematica/index.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- dijkstra -- mathematica -title: Dijkstra in Mathematica -title1: Dijkstra in -title2: Mathematica ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* This is easy to do using Mathematica graph operations: *) - -dijkstra = Function[{am, from, to}, - (* sum the edge weights *) - Total @ Module[ - {g = WeightedAdjacencyGraph[am /. 0 -> \[Infinity] (* needed to indicate no edge *)]}, - PropertyValue[{ (* find the edge weights *) - g, - (* convert the list of path vertices into a list of edges *) - Apply[UndirectedEdge] /@ Partition[ - (* find shortest path (cheating!) *) - FindShortestPath[g, from, to, Method -> "Dijkstra"], - 2, 1]}, - EdgeWeight]]]; - -(* The outer function provides the 'user interface': *) - -dijkstraMain = Function[{values, from, to}, - Module[{e = "Usage: please provide three inputs: a serialized matrix, a source node and a destination node"}, - Catch[ - Apply[ - Function[{v, f, t}, - Module[{l = Sqrt[Length[v]], w}, - w = dijkstra[ - Partition[v,(* convert to square matrix *) - (* compute square dimension *) - If[IntegerQ[l], l, Throw[e]]], - If[f < l, 1 + f, Throw[e]],(* Mathematica indices are 1-based *) - If[t < l, 1 + t, Throw[e]]]; - (* Specifically detect the case where no path was found; - note that FindShortestPath just returns zero in this case, - which it would also do if the source and destination vertices are the same. *) - If[w == 0 \[And] f != t, Throw[e], w]]]]@ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments: list of weights, source node, destination node *) - { - StringSplit[If[StringLength[values] > 0, values, Throw[e]], ", "], - from, to - }, - {-1} (* at each leaf *)]]]]; - -(* Valid Tests *) - -Print /@ Apply[dijkstraMain] /@ { - {"0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0", "0", "1"} - }; - - -(* Invalid Tests *) - -dijkstraMain["1, 0, 3, 0, 5, 1", "1", "2"] -dijkstraMain["0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0", "0", ""] -dijkstraMain["0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0", "", ""] -dijkstraMain["0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0", "-1", "2"] -dijkstraMain["0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0", "1", "-2"] -dijkstraMain["0, 2, 0, -6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, -6, 8, 0, 0, 9, 0, 5, 7, 9, 0", "1", "2"] -dijkstraMain["0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0", "1", "10"] -dijkstraMain["0, 0, 0, 0", "0", "1"] - -``` - -{% endraw %} - -Dijkstra in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/pascal/index.md b/docs/projects/dijkstra/pascal/index.md deleted file mode 100644 index a099b13805..0000000000 --- a/docs/projects/dijkstra/pascal/index.md +++ /dev/null @@ -1,220 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- dijkstra -- pascal -title: Dijkstra in Pascal -title1: Dijkstra -title2: in Pascal ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program Dijkstra; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - Math, - SysUtils; - -type - TIntegerList = specialize TList; - TBooleanList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide three inputs: a serialized matrix, a source node and a destination node'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Part: string; - Value: integer; -begin - if S.Trim.IsEmpty then ShowUsage; - Result := TIntegerList.Create; - for Part in S.Split([',']) do - begin - if not TryStrToInt(Trim(Part), Value) or (Value < 0) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; - if Result.Count = 0 then - begin - Result.Free; - ShowUsage; - end; -end; - -// Checks if the matrix is square, returns dimension or -1 if invalid -function MatrixDimension(const Matrix: TIntegerList): integer; inline; -var - Len: integer; - D: integer; -begin - Len := Matrix.Count; - D := Floor(Sqrt(Len)); - if (D * D = Len) and (D > 0) then - Result := D - else - Result := -1; -end; - -// Returns distance from src to dst or -1 if unreachable -function Dijkstra(const Matrix: TIntegerList; - Dimension, Source, Destination: integer): integer; -const - INF = $3F3F3F3F; -var - Dist: TIntegerList; - Visited: TBooleanList; - I, J, MinDist, MinIndex, Weight, CurrentDist: integer; -begin - Dist := TIntegerList.Create; - Visited := TBooleanList.Create; - try - Dist.Capacity := Dimension; - Visited.Capacity := Dimension; - - for I := 0 to Dimension - 1 do - begin - Dist.Add(INF); - Visited.Add(False); - end; - - Dist[Source] := 0; - - for I := 0 to Dimension - 1 do - begin - MinDist := INF; - MinIndex := -1; - - // Find closest unvisited node - for J := 0 to Dimension - 1 do - if (not Visited[J]) and (Dist[J] < MinDist) then - begin - MinDist := Dist[J]; - MinIndex := J; - end; - - if MinIndex = -1 then - Break; - - Visited[MinIndex] := True; - CurrentDist := Dist[MinIndex]; - - if MinIndex = Destination then - begin - Result := CurrentDist; - Exit; - end; - - for J := 0 to Dimension - 1 do - begin - Weight := Matrix[MinIndex * Dimension + J]; - if (not Visited[J]) and (Weight > 0) and - (CurrentDist + Weight < Dist[J]) then - Dist[J] := CurrentDist + Weight; - end; - end; - - if Dist[Destination] = INF then - Result := -1 - else - Result := Dist[Destination]; - - finally - Dist.Free; - Visited.Free; - end; -end; - - -var - MatrixStr, SourceStr, DestinationStr: string; - Matrix: TIntegerList; - Dimension, Source, Destination, ShortestDistance: integer; -begin - if ParamCount <> 3 then - ShowUsage; - - MatrixStr := Trim(ParamStr(1)); - SourceStr := Trim(ParamStr(2)); - DestinationStr := Trim(ParamStr(3)); - - if (MatrixStr = '') or (SourceStr = '') or (DestinationStr = '') then - ShowUsage; - - Matrix := nil; - try - Matrix := ParseIntegerList(MatrixStr); - - Dimension := MatrixDimension(Matrix); - - // Check if: - // - the matrix represents a valid square adjacency matrix (dimension <> 1) - // - the source and destination nodes are valid integers - // - the nodes are within valid index range [0, Dimension - 1] - if (Dimension = -1) or (not TryStrToInt(SourceStr, Source)) or - (not TryStrToInt(DestinationStr, Destination)) or (Source < 0) or - (Source >= Dimension) or (Destination < 0) or (Destination >= Dimension) then - - ShowUsage; - - ShortestDistance := Dijkstra(Matrix, Dimension, Source, Destination); - - if ShortestDistance = -1 then - ShowUsage - else - Writeln(ShortestDistance); - - finally - Matrix.Free; - end; -end. - -``` - -{% endraw %} - -Dijkstra in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/php/index.md b/docs/projects/dijkstra/php/index.md deleted file mode 100644 index 26872d6297..0000000000 --- a/docs/projects/dijkstra/php/index.md +++ /dev/null @@ -1,299 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2023-03-27 -layout: default -tags: -- dijkstra -- php -title: Dijkstra in PHP -title1: Dijkstra -title2: in PHP ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -function validate_inputs($weights, $num_vertices, $src, $dest) -{ - // Verify number of weights is a square - if (count($weights) != $num_vertices * $num_vertices) - { - return FALSE; - } - - // Verify weights greater than equal to zero - if (min($weights) < 0) - { - return FALSE; - } - - # Verify any non-zero weights - if ( - count( - array_filter($weights, function ($weight) { return $weight != 0; }) - ) == 0 - ) - { - return FALSE; - } - - # Verify source and destination are in range - if ($src < 0 or $src >= $num_vertices or $dest < 0 or $dest >= $num_vertices) - { - return FALSE; - } - - return TRUE; -} - -function create_graph($weights, $num_vertices) -{ - // Initialize nodes - $nodes = array_map( - function ($id) { return new Node($id); }, - range(0, $num_vertices - 1) - ); - - // Get neighbors for this node based on weights - $index = 0; - for ($row = 0; $row < $num_vertices; $row++) - { - for ($col = 0; $col < $num_vertices; $col++, $index++) - { - if ($weights[$index] > 0) - { - $nodes[$row]->add_child($col, $weights[$index]); - } - } - } - - return $nodes; -} - -class Node -{ - public $index; - public $children; - - public function __construct($index) - { - $this->index = $index; - $this->children = array(); - } - - public function add_child($index, $weight) - { - array_push($this->children, new NodeItem($index, $weight)); - } -} - -class NodeItem -{ - public $index; - public $weight; - - public function __construct($index, $weight) - { - $this->index = $index; - $this->weight = $weight; - } -} - -// Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode -function dijkstra($graph, $src) -{ - // Initialize distances to infinite and previous vertices to undefined - // Set source vertex distance to 0 - // Indicate all nodes unvisited - $num_vertices = count($graph); - $results = array_map( - function ($_) { return new DisktraItem(); }, - range(0, $num_vertices - 1) - ); - $results[$src]->dist = 0; - - // While any unvisited nodes - for ($i = 0; $i < $num_vertices; $i++) - { - // Pick a vertex u with minimum distance from unvisited nodes - $u = find_min_dist_index($results); - - // Indicate vertex u visited - $results[$u]->visited = TRUE; - - // For each unvisited neighbor v of vertex u - foreach ($graph[$u]->children as $node) - { - $v = $node->index; - if (!$results[$v]->visited) - { - // Get trial distance - $alt = $results[$u]->dist + $node->weight; - - // If trial distance is smaller than distance v, update distance to v and - // previous vertex of v - if ($alt < $results[$v]->dist) - { - $results[$v]->dist = $alt; - $results[$v]->prev = $u; - } - } - } - } - - return $results; -} - -function find_min_dist_index($results) -{ - $min_dist = PHP_INT_MAX; - $min_index = -1; - foreach ($results as $v => $result) - { - if (!$result->visited && $result->dist < $min_dist) - { - $min_dist = $result->dist; - $min_index = $v; - } - } - - return $min_index; -} - -class DisktraItem -{ - public $prev; - public $dist; - public $visited; - - public function __construct() - { - $this->prev = -1; - $this->dist = PHP_INT_MAX; - $this->visited = FALSE; - } -} - -// Exit if too few arguments -if (count($argv) < 4) -{ - usage(); -} - -// Parse arguments. Exit if invalid -$weights = parse_int_array($argv[1]); -$src = parse_int($argv[2]); -$dest = parse_int($argv[3]); -if ($weights === FALSE || $src === FALSE || $dest === FALSE) -{ - usage(); -} - -// Validate inputs -$num_vertices = round(sqrt(count($weights))); -if (!validate_inputs($weights, $num_vertices, $src, $dest)) -{ - usage(); -} - -// Create graph from weights -$graph = create_graph($weights, $num_vertices); - -// Run Dijkstra's algorithm on graph and show distance to destination -$results = dijkstra($graph, $src); -printf("%d\n", $results[$dest]->dist); - -``` - -{% endraw %} - -Dijkstra in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/powershell/index.md b/docs/projects/dijkstra/powershell/index.md deleted file mode 100644 index a48f641151..0000000000 --- a/docs/projects/dijkstra/powershell/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-22 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- dijkstra -- powershell -title: Dijkstra in PowerShell -title1: Dijkstra in -title2: PowerShell ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide three inputs: a serialized matrix, a source node and a destination node" - Exit(1) -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -function Test-Inputs([array]$Weights, [int]$NumVertices, [int]$Src, [int]$Dest) { - # Verify number of weights is a square, weights are non-negative, any non-zero weight, and source - # destination are valid - $WeightMeasurements = $Weights | Measure-Object -Minimum -Maximum - ($Weights.Length -eq ($NumVertices * $NumVertices) -and - $WeightMeasurements.Minimum -ge 0 -and - $WeightMeasurements.Maximum -gt 0 -and - $Src -ge 0 -and $Src -lt $NumVertices -and - $Dest -ge 0 -and $Dest -lt $NumVertices) -} - -class NodeItem { - [int]$Index - [int]$Weight - - NodeItem([int]$index, [int]$weight) { - $this.Index = $index - $this.Weight = $weight - } -} - -class Node { - [int]$Index - [NodeItem[]]$Children - - Node([int]$index) { - $this.Index = $index - $this.Children = @() - } - - [void] AddChild([int]$index, [int]$weight) { - $this.Children += [NodeItem]::new($index, $weight) - } -} - -function Create-Graph([array]$Weights, [int]$NumVertices) { - # Initialize nodes - $nodes = 0..($NumVertices - 1) | ForEach-Object { [Node]::new($_) } - - # Get neighbors for this node based on weights - $index = 0 - for ($row = 0; $row -lt $NumVertices; $row++) { - for ($col = 0; $col -lt $NumVertices; ($col++), ($index++)) { - if ($Weights[$index] -gt 0) { - $nodes[$row].AddChild($col, $Weights[$index]) - } - } - } - - $nodes -} - -class DijkstraItem { - [int]$Prev = -1 - [int]$Dist = [int]::MaxValue -} - -# Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode -function Invoke-Dijkstra([Node[]]$Graph, [int]$Src) { - # Initialize distances to infinite and previous vertices to undefined - $numVertices = $Graph.Length - $results = 0..($numVertices - 1) | ForEach-Object { [DijkstraItem]::new() } - - # Indicate all nodes unvisited - $q = [Collections.Generic.HashSet[int]](0..($numVertices - 1)) - - # Set source vertex distance to 0 - $results[$Src].Dist = 0 - - # While there are unvisited nodes - while ($q.Count) { - # Pick a vertex u with minimum distance from unvisited nodes - $u = Find-MinDistIndex $q $results - - # Indicate vertex u visited - [void]$q.Remove($u) - - # For each unvisited neighbor v of vertex u - foreach ($node in $Graph[$u].Children) { - $v = $node.Index - if ($v -in $q) { - # Get trial distance - $alt = $results[$u].Dist + $node.Weight - - # If trial distance is smaller than distance v, update distance to v and - # previous vertex of v - if ($alt -lt $results[$v].Dist) { - $results[$v].Dist = $alt - $results[$v].Prev = $u - } - } - } - } - - $results -} - -function Find-MinDistIndex([Collections.Generic.HashSet[int]]$q, [DijkstraItem[]]$results) { - $minDist = [int]::MaxValue - $minIndex = -1 - for ($v = 0; $v -lt $results.Length; $v++) { - if ($v -in $q -and $results[$v].Dist -lt $minDist) { - $minDist = $results[$v].Dist - $minIndex = $v - } - } - - $minIndex -} - -if ($args.Length -lt 3 -or -not $args[0]) { - Show-Usage -} - -try { - $weights = Parse-IntList $args[0] - $src = [int]::Parse($args[1]) - $dest = [int]::Parse($args[2]) -} catch { - Show-Usage -} - - -$numVertices = [int][Math]::Floor([Math]::Sqrt($weights.Length)) -if (-not (Test-Inputs $weights $numVertices $src $dest)) { - Show-Usage -} - -# Create graph from weights -$graph = Create-Graph $weights $numVertices - -# Run Dijkstra's algorithm on graph and show distance to destination -$results = Invoke-Dijkstra $graph $src -Write-Output $results[$dest].Dist - -``` - -{% endraw %} - -Dijkstra in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/python/index.md b/docs/projects/dijkstra/python/index.md deleted file mode 100644 index 3495348d94..0000000000 --- a/docs/projects/dijkstra/python/index.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-09 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2023-02-09 -layout: default -tags: -- dijkstra -- python -title: Dijkstra in Python -title1: Dijkstra -title2: in Python ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys -import math - -def usage(): - print("Usage: please provide three inputs: a serialized matrix, a source node and a destination node") - sys.exit(0) - -def parse_int_list(s): - return [int(x.strip()) for x in s.split(",")] - -def validate_inputs(weights, num_vertices, src, dest): - # Verify number of weights is a square - if len(weights) != num_vertices * num_vertices: - return False - - # Verify weights greater than equal to zero - if any(weight < 0 for weight in weights): - return False - - # Verify any non-zero weights - if not any(weights): - return False - - # Verify source and destination are in range - if src < 0 or src >= num_vertices or dest < 0 or dest >= num_vertices: - return False - - return True - -class Graph: - def __init__(self, num_vertices): - self.num_vertices = num_vertices - self.edges = [{} for i in range(num_vertices)] - - def add_node(self, u, v, weight): - self.edges[u][v] = weight - -def create_graph(num_vertices, weights): - graph = Graph(num_vertices) - index = 0 - for u in range(num_vertices): - for v in range(num_vertices): - if weights[index]: - graph.add_node(u, v, weights[index]) - - index += 1 - - return graph - -def dijkstra(graph, src): - # Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode - - # Initialize distances to infinite and previous vertices to undefined - # Set source vertex distance to 0 - dists = [sys.maxsize] * graph.num_vertices - prevs = [-1] * (graph.num_vertices) - dists[src] = 0 - - # Initialize unvisited nodes - q = set(range(graph.num_vertices)) - - # While any unvisited nodes - while q: - # Pick a vertex u in Q with minimum distance - _, u = min( - (dist, vertex) for vertex, dist in enumerate(dists) if vertex in q - ) - - # Remove vertex u from Q - q.remove(u) - - # For each neighbor v of vertex u in still in Q - for v, weight in graph.edges[u].items(): - if v in q: - # Get trial distance - alt = dists[u] + weight - - # If trial distance is smaller than distance v, update distance to v and - # previous vertex of v - if alt < dists[v]: - dists[v] = alt - prevs[v] = u - - return dists, prevs - -def main(): - if len(sys.argv) < 4: - usage() - - # Parse inputs - try: - weights = parse_int_list(sys.argv[1]) - src = int(sys.argv[2]) - dest = int(sys.argv[3]) - except ValueError: - usage() - - # Validate inputs - num_vertices = int(math.sqrt(len(weights) + 0.5)) - if not validate_inputs(weights, num_vertices, src, dest): - usage() - - # Create graph from weights - graph = create_graph(num_vertices, weights) - - # Run Dijkstra's algorithm on graph and show distance to destination - dists, _ = dijkstra(graph, src) - print(dists[dest]) - -if __name__ == "__main__": - main() - -``` - -{% endraw %} - -Dijkstra in [Python](/languages/python) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/ruby/index.md b/docs/projects/dijkstra/ruby/index.md deleted file mode 100644 index e42391ab2b..0000000000 --- a/docs/projects/dijkstra/ruby/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- dijkstra -- ruby -title: Dijkstra in Ruby -title1: Dijkstra -title2: in Ruby ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = "Usage: please provide three inputs: a serialized matrix, a source node and a destination node" - -def usage! - warn USAGE - exit 1 -end - -def parse_matrix(str) - str.split(",").map { Integer(it.strip) } -rescue ArgumentError, NoMethodError - usage! -end - -def build_matrix(flat) - n = Integer(Math.sqrt(flat.size)) - usage! unless n * n == flat.size - - matrix = flat.each_slice(n).to_a - - usage! if matrix.any? { |row| row.any?(&:negative?) } - - matrix -end - -def parse_index(str, n) - usage! if str.nil? || str.strip.empty? - - i = Integer(str) - usage! unless i.between?(0, n - 1) - - i -rescue ArgumentError - usage! -end - -def dijkstra(matrix, src, dst) - n = matrix.size - dist = Array.new(n, Float::INFINITY) - visited = Array.new(n, false) - - dist[src] = 0 - - n.times do - u = nil - best = Float::INFINITY - - n.times do |i| - next if visited[i] - next if dist[i] >= best - - best = dist[i] - u = i - end - - break unless u - - visited[u] = true - - row = matrix[u] - base = dist[u] - - row.each_with_index do |w, v| - next if w <= 0 || visited[v] - - alt = base + w - dist[v] = alt if alt < dist[v] - end - end - - dist[dst] -end - -matrix_str, src_str, dst_str = ARGV -usage! if matrix_str.nil? || src_str.nil? || dst_str.nil? -usage! if matrix_str.strip.empty? || src_str.strip.empty? || dst_str.strip.empty? - -matrix = build_matrix(parse_matrix(matrix_str)) -n = matrix.size - -src = parse_index(src_str, n) -dst = parse_index(dst_str, n) - -dist = dijkstra(matrix, src, dst) - -usage! unless dist.finite? - -puts dist.to_i - -``` - -{% endraw %} - -Dijkstra in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/rust/index.md b/docs/projects/dijkstra/rust/index.md deleted file mode 100644 index f2049e38c4..0000000000 --- a/docs/projects/dijkstra/rust/index.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-20 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- dijkstra -- rust -title: Dijkstra in Rust -title1: Dijkstra -title2: in Rust ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::collections::{HashMap, HashSet}; - -fn usage() -> ! { - println!( - "Usage: please provide three inputs: a serialized matrix, \ - a source node and a destination node" - ); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -#[derive(Debug, Clone)] -struct Node { - index: usize, - children: HashMap, -} - -impl Node { - fn new(index: usize) -> Self { - Self {index: index, children: HashMap::::new()} - } - - fn add_child(&mut self, index: usize, weight: u32) { - self.children.insert(index, weight); - } -} - -type Tree = Vec; - -fn create_tree(weights: &Vec, num_vertices: usize) -> Tree { - // Create nodes - let mut nodes: Vec = (0..num_vertices) - .map(|index| Node::new(index)) - .collect(); - - // Add child nodes to each node based on non-zero values of adjacency matrix - let mut index = 0; - for row in 0..num_vertices { - for col in 0..num_vertices { - let weight = weights[index]; - index += 1; - if weight > 0 { - nodes[row].add_child(col, weight); - } - } - } - - nodes -} - -fn validate_inputs( - weights: &Vec, num_vertices: usize, src: usize, dest: usize -) -> bool { - // Verify the following: - // - Number of weights is a square - // - Any non-zero weights - // - Source and destination are in range - weights.len() == num_vertices * num_vertices - && *weights.iter().max().unwrap() > 0 - && src < num_vertices - && dest < num_vertices -} - -#[derive(Debug, Clone)] -struct DijkstraItem { - prev: usize, - dist: u32, -} - -impl DijkstraItem { - fn new(prev: usize, dist: u32) -> DijkstraItem { - DijkstraItem {prev: prev, dist: dist} - } -} - -// Source: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Pseudocode -fn dijkstra(tree: &Tree, src: usize) -> Vec { - // Initialize distances to infinite and previous vertices to undefined - // Set source vertex distance to 0 - // Indicate all nodes unvisited - let num_vertices = tree.len(); - let mut results: Vec = vec![DijkstraItem::new(0, u32::MAX); num_vertices]; - results[src].dist = 0; - let mut visited: HashSet = HashSet::::new(); - - // While any unvisited nodes - while visited.len() < num_vertices { - // Pick a vertex u with minimum distance from unvisited nodes - let u: usize = (0..num_vertices) - .filter(|index| !visited.contains(index)) - .map(|index| (results[index].dist, index)) - .min() - .unwrap() - .1; - - // Indicate vertex u visited - visited.insert(u); - - // For each unvisited neighbor v of vertex u - for (&v, &weight) in tree[u].children.iter() { - if !visited.contains(&v) { - // Get trial distance - let alt = results[u].dist + weight; - - // If trial distance is smaller than distance v, update distance to v and - if alt < results[v].dist { - results[v].dist = alt; - results[v].prev = u; - } - } - } - } - - results -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let weights: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 2nd command-line argument to integer - let src: usize = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 3rd command-line argument to integer - let dest: usize = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if invalid inputs - let num_weights = weights.len(); - let num_vertices = (num_weights as f32).sqrt().round() as usize; - if !validate_inputs(&weights, num_vertices, src, dest) { - usage(); - } - - // Create tree - let tree = create_tree(&weights, num_vertices); - - // Run Dijkstra's algorithm on graph and show distance to destination - let results = dijkstra(&tree, src); - println!("{}", results[dest].dist); -} - -``` - -{% endraw %} - -Dijkstra in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/swift/index.md b/docs/projects/dijkstra/swift/index.md deleted file mode 100644 index 43510bcf8d..0000000000 --- a/docs/projects/dijkstra/swift/index.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- dijkstra -- swift -title: Dijkstra in Swift -title1: Dijkstra -title2: in Swift ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide three inputs: a serialized matrix, a source node and a destination node - """ - -extension Collection { - func chunked(into size: Int) -> [[Element]] { - stride(from: 0, to: count, by: size).map { offset in - let start = index(startIndex, offsetBy: offset) - let end = index(start, offsetBy: size, limitedBy: endIndex) ?? endIndex - return Array(self[start.. [Int]? { - let parts = input.split(separator: ",").map { $0.trimmed } - let values = parts.compactMap(Int.init) - - guard values.count == parts.count, !values.isEmpty else { - return nil - } - - return values -} - -func parseArguments(from args: [String]) -> (matrix: [[Int]], source: Int, destination: Int)? { - guard args.count == 4, - let flat = parseList(args[1]), - let source = Int(args[2].trimmed), - let destination = Int(args[3].trimmed) - else { - return nil - } - - let n = Int(Double(flat.count).squareRoot()) - - guard n * n == flat.count, - (0.. Int? { - let n = matrix.count - var dist = Array(repeating: Int.max, count: n) - var visited = Set() - - dist[source] = 0 - - for _ in 0.. 0 { - let newDist = baseDist + row[v] - if newDist < dist[v] { - dist[v] = newDist - } - } - } - - return dist[destination] == Int.max ? nil : dist[destination] -} - -guard let (matrix, source, destination) = parseArguments(from: CommandLine.arguments) else { - print(usage) - exit(1) -} - -if let result = shortestPath(matrix: matrix, from: source, to: destination) { - print(result) -} else { - print(usage) -} - -``` - -{% endraw %} - -Dijkstra in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/tcl/index.md b/docs/projects/dijkstra/tcl/index.md deleted file mode 100644 index d48014575f..0000000000 --- a/docs/projects/dijkstra/tcl/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2025-10-08 -layout: default -tags: -- dijkstra -- tcl -title: Dijkstra in Tcl -title1: Dijkstra -title2: in Tcl ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 -package require struct -package require struct::graph -package require struct::graph::op - -proc usage {} { - puts stderr {Usage: please provide three inputs: a serialized matrix, a source node and a destination node} - exit 1 -} - -proc isInteger {x} { return [string is integer -strict $x] } - -proc parseList {s} { - set s [string trim $s] - if {$s eq ""} { usage } - - set result {} - foreach t [split $s ,] { - set t [string trim $t] - if {![isInteger $t] || $t < 0} { usage } - lappend result $t - } - return $result -} - -proc createGraph {matrix vertices} { - set n [llength $vertices] - if {[llength $matrix] != [expr {$n * $n}]} { usage } - - set g [struct::graph] - $g node insert {*}$vertices - - set idx 0 - foreach i $vertices { - foreach j $vertices { - set w [lindex $matrix $idx] - incr idx - if {$w > 0} { - set a [$g arc insert $i $j] - $g arc setweight $a $w - } - } - - return $g - } -} - -proc main {argv} { - if {[llength $argv] != 3} { usage } - lassign $argv matrixStr srcStr destStr - - if {![string is integer -strict $srcStr] || ![string is integer -strict $destStr]} { - usage - } - - set matrix [parseList $matrixStr] - set n [expr {int(sqrt([llength $matrix]))}] - if {$n*$n != [llength $matrix]} { usage } - - set src [expr {$srcStr + 0}] - set dest [expr {$destStr + 0}] - if {$src < 0 || $src >= $n || $dest < 0 || $dest >= $n} { usage } - - set vertices [lrange [list {*}[lrepeat $n 0]] 0 end] - for {set i 0} {$i < $n} {incr i} { lset vertices $i $i } - - set g [createGraph $matrix $vertices] - - if {[$g node degree $src] == 0 || [$g node degree $dest] == 0} { - $g destroy - usage - } - - try { - set distances [::struct::graph::op::dijkstra $g $src -outputformat distances] - if {[dict exists $distances $dest]} { - puts [dict get $distances $dest] - } else { - usage - } - } on error {err opts} { - usage - } finally { - $g destroy - } -} - -main $argv - - -``` - -{% endraw %} - -Dijkstra in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/typescript/index.md b/docs/projects/dijkstra/typescript/index.md deleted file mode 100644 index 60ffa05bd7..0000000000 --- a/docs/projects/dijkstra/typescript/index.md +++ /dev/null @@ -1,181 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- dijkstra -- typescript -title: Dijkstra in TypeScript -title1: Dijkstra in -title2: TypeScript ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function printUsage(): void { - console.log( - "Usage: please provide three inputs: a serialized matrix, a source node and a destination node", - ); -} - -function parseList(input: string | undefined): number[] | null { - if (input === undefined) return null; - if (input.trim() === "") return []; - - const parts = input.split(",").map((s) => s.trim()); - const nums: number[] = []; - - for (const p of parts) { - if (!/^-?\d+$/.test(p)) return null; - nums.push(Number(p)); - } - - return nums; -} - -function buildMatrix(flat: number[]): number[][] | null { - const n = Math.sqrt(flat.length); - if ((n | 0) !== n) return null; - - const size = n | 0; - const matrix: number[][] = new Array(size); - - for (let i = 0; i < size; i++) { - const row: number[] = new Array(size); - for (let j = 0; j < size; j++) { - row[j] = flat[i * size + j]; - } - matrix[i] = row; - } - - return matrix; -} - -function dijkstra(matrix: number[][], src: number, dst: number): number { - const n = matrix.length; - const dist = new Array(n).fill(Infinity); - const visited = new Array(n).fill(false); - - dist[src] = 0; - - for (let i = 0; i < n; i++) { - let u = -1; - - for (let j = 0; j < n; j++) { - if (!visited[j] && (u === -1 || dist[j] < dist[u])) { - u = j; - } - } - - if (u === -1 || dist[u] === Infinity) break; - visited[u] = true; - - const row = matrix[u]; - const du = dist[u]; - - for (let v = 0; v < n; v++) { - const w = row[v]; - if (w > 0 && !visited[v]) { - const alt = du + w; - if (alt < dist[v]) dist[v] = alt; - } - } - } - - return dist[dst] === Infinity ? -1 : dist[dst]; -} - -function main(): void { - const [, , matrixStr, srcStr, dstStr] = process.argv; - const flat = parseList(matrixStr); - const srcArr = parseList(srcStr); - const dstArr = parseList(dstStr); - - if ( - flat === null || - srcArr === null || - dstArr === null || - srcArr.length !== 1 || - dstArr.length !== 1 - ) { - printUsage(); - return; - } - - if (flat.length === 0) { - printUsage(); - return; - } - - const src = srcArr[0]; - const dst = dstArr[0]; - - const matrix = buildMatrix(flat); - if (!matrix) { - printUsage(); - return; - } - - const n = matrix.length; - - if (src < 0 || dst < 0 || src >= n || dst >= n) { - printUsage(); - return; - } - - for (const row of matrix) { - for (const w of row) { - if (w < 0) { - printUsage(); - return; - } - } - } - - const result = dijkstra(matrix, src, dst); - if (result < 0) { - printUsage(); - return; - } - - console.log(result.toString()); -} - -main(); - -``` - -{% endraw %} - -Dijkstra in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/visual-basic/index.md b/docs/projects/dijkstra/visual-basic/index.md deleted file mode 100644 index f23d920852..0000000000 --- a/docs/projects/dijkstra/visual-basic/index.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-08 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-05-08 -layout: default -tags: -- dijkstra -- visual-basic -title: Dijkstra in Visual Basic -title1: Dijkstra in -title2: Visual Basic ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module Program - - Private Const INF As Integer = &H3F3F3F3F - - Private Sub ShowUsage() - Console.Error.WriteLine( - "Usage: please provide three inputs: " & - "a serialized matrix, a source node and a destination node" - ) - Environment.Exit(1) - End Sub - - - Private Function ParseIntegerList(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - ShowUsage() - End If - - Return input.Split(","c, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) _ - .Select(Function(s) - Dim v As Integer - If Not Integer.TryParse(s, v) OrElse v < 0 Then - ShowUsage() - End If - Return v - End Function) _ - .ToList() - - End Function - - - Private Function GetDimension(matrix As List(Of Integer)) As Integer - Dim n = CInt(Math.Sqrt(matrix.Count)) - If n * n <> matrix.Count Then Return -1 - Return n - End Function - - - Private Function Dijkstra(matrix As List(Of Integer), - n As Integer, - source As Integer, - destination As Integer) As Integer - - Dim dist(n - 1) As Integer - Dim visited(n - 1) As Boolean - - For i = 0 To n - 1 - dist(i) = INF - Next - - dist(source) = 0 - - Dim pq As New PriorityQueue(Of Integer, Integer) - pq.Enqueue(source, 0) - - While pq.Count > 0 - - Dim node = pq.Dequeue() - - If visited(node) Then Continue While - visited(node) = True - - If node = destination Then - Return dist(node) - End If - - Dim baseIndex = node * n - - For i = 0 To n - 1 - - Dim weight = matrix(baseIndex + i) - - If weight <= 0 Then Continue For - If visited(i) Then Continue For - - Dim newDist = dist(node) + weight - - If newDist < dist(i) Then - dist(i) = newDist - pq.Enqueue(i, newDist) - End If - - Next - - End While - - Return If(dist(destination) = INF, -1, dist(destination)) - - End Function - - - Public Function Main(args As String()) As Integer - - If args.Length <> 3 Then ShowUsage() - - Dim matrix = ParseIntegerList(args(0)) - Dim n = GetDimension(matrix) - - Dim source As Integer - Dim dest As Integer - - If n = -1 OrElse - Not Integer.TryParse(args(1), source) OrElse - Not Integer.TryParse(args(2), dest) OrElse - source < 0 OrElse source >= n OrElse - dest < 0 OrElse dest >= n Then - ShowUsage() - End If - - Dim result = Dijkstra(matrix, n, source, dest) - - If result = -1 Then ShowUsage() - - Console.WriteLine(result) - Return 0 - - End Function - -End Module -``` - -{% endraw %} - -Dijkstra in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/dijkstra/x86-64/index.md b/docs/projects/dijkstra/x86-64/index.md deleted file mode 100644 index fa7837f6de..0000000000 --- a/docs/projects/dijkstra/x86-64/index.md +++ /dev/null @@ -1,1575 +0,0 @@ ---- -authors: -- Raymond Marx -date: 2026-01-05 -featured-image: dijkstra-in-every-language.jpg -last-modified: 2026-01-05 -layout: default -tags: -- dijkstra -- x86-64 -title: Dijkstra in x86-64 -title1: Dijkstra -title2: in x86-64 ---- - - - -Welcome to the [Dijkstra](/projects/dijkstra) in [x86-64](/languages/x86-64) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```x86-64 -; MACROS - -%MACRO MMAP_PUSH 0 -PUSH RDI -PUSH RSI -PUSH RDX -PUSH RCX -PUSH R10 -PUSH R8 -PUSH R9 -PUSH R11 -%ENDMACRO -%MACRO MMAP_POP 0 -POP R11 -POP R9 -POP R8 -POP R10 -POP RCX -POP RDX -POP RSI -POP RDI -%ENDMACRO - -;Exit codes -%DEFINE EXIT_OK 0 - -%DEFINE INVALID_ARGC 1 -%DEFINE INVALID_SRCDST 2 -%DEFINE INVALID_NUM_NEG 3 -%DEFINE INVALID_CHAR 4 -%DEFINE INVALID_NUM_VERTS 5 -%DEFINE INVALID_NOT_SQUARE 6 -%DEFINE INVALID_STATE 7 -%DEFINE INVALID_EMPTY 8 -%DEFINE INVALID_BAD_STR 9 -%DEFINE INVALID_NO_WAY 10 -%DEFINE VALID_ARGC 4 - -; CONSTANTS -%DEFINE MUL_2 1 -%DEFINE MUL_4 2 -%DEFINE MUL_INT 2 -%DEFINE MUL_LONG 3 -%DEFINE DIV_2 1 -%DEFINE SIZE_INT 4 -%DEFINE SIZE_LONG 8 -%DEFINE EMPTY_INPUT 0 -%DEFINE INT_MAX 0xFFFFFFFF -%DEFINE NULL 0 -%DEFINE FALSE 0 -%DEFINE TRUE 1 -%DEFINE MAX_STR_INT 11 ; 10 (Max Int) + 1 (Null) - -%DEFINE UNSEEN 0 -%DEFINE SEEN 1 - -%DEFINE NO_CONNECTION 0 - -%DEFINE COMMA_SPACE 2 - - - -; Functions/Methods - -%DEFINE atoi.STACK_INIT 8 -%DEFINE atoi.ret 8 - - - -%DEFINE priority_queue@construct.STACK_INIT 8 -%DEFINE priority_queue@construct.PQPtr 8 - -%DEFINE parseSRCDST.STACK_INIT 8 -%DEFINE parseSRCDST.strlen 8 - -%DEFINE parseVertices.STACK_INIT 64 -%DEFINE parseVertices.strlen 8 -%DEFINE parseVertices.SRC 16 -%DEFINE parseVertices.DST 24 -%DEFINE parseVertices.NumPtr 32 -%DEFINE parseVertices.PrevState 40 -%DEFINE parseVertices.NumElems 48 -%DEFINE parseVertices.CurrentArray 56 -%DEFINE parseVertices.NumVertices 64 - - -;SYSCALLS -;STDOUT/OUT -%DEFINE SYS_WRITE 1 -%DEFINE STDOUT 1 -;Memory -%DEFINE SYS_MMAP 9 -%DEFINE NO_ADDR 0 -%DEFINE NO_FD -1 -%DEFINE NO_OFFSET 0 -;PROTS (RDX) -%DEFINE PROT_READ 0x01 -%DEFINE PROT_WRITE 0x02 -;FLAGS (R10) -%DEFINE MAP_SHARED 0x01 -%DEFINE MAP_ANONYMOUS 0x20 - -%DEFINE SYS_MPROTECT 10 - -%DEFINE SYS_MUNMAP 11 - -;Thread -%DEFINE SYS_EXIT 60 - - - -;Start - -%DEFINE _start.argc 8 -%DEFINE _start.argv0 16 -%DEFINE _start.argv1 24 -%DEFINE _start.argv2 32 -%DEFINE _start.argv3 40 -; RBP+ ^ -; RBP- v -%DEFINE _start.STACK_INIT 40 -%DEFINE _start.SRC 8 -%DEFINE _start.DST 16 -%DEFINE _start.NumVerts 24 -%DEFINE _start.graph 32 -%DEFINE _start.RET 40 - -%DEFINE dijkstra.STACK_INIT 72 -%DEFINE dijkstra.PriorityQueue 8 -%DEFINE dijkstra.prev 16 -%DEFINE dijkstra.dist 24 -%DEFINE dijkstra.SRC 32 -%DEFINE dijkstra.graph 40 -%DEFINE dijkstra.x 48 -%DEFINE dijkstra.y 56 -%DEFINE dijkstra.numVerts 64 -%DEFINE dijkstra.currentRow 72 - - - - - -section .rodata - -newline: - .msg db 0xA - .len equ $- .msg - -Error: - .msg db 'Usage: please provide three inputs: a serialized matrix, a source node and a destination node' - .len equ $- .msg - -Err_Table: ; This is absurd but this because of CMOV not allowing immediates. - dq 0 - dq -1 - dq -2 - dq -3 - dq -4 - dq -5 - dq -6 - dq -7 - dq -8 - dq -9 - dq -10 - -BOOLs: - .TRUE dq 1 - .FALSE dq 0 - -section .data - -Error_state: - .CODE db 0 - -struc min_heap - .size resq 1 - .max_len resq 1 - .elems resq 1 -endstruc - -struc NodeTuple - .value resd 1 - .element resd 1 -endstruc - -; I want this priority queue as it acts as a great container for the minheap -; and allows for easy abstraction of minheap methods. -struc priority_queue - .size resq 1 - .max_len resq 1 - .heap resq 1 -endstruc - -section .bss - -section .text - -reverseString: -; ---------------------------------------------------------------------------- -; Function: Reverse string -; Description: -; Reverses string simply. -; Parameters: -; RDI - (char[]*) String ptr. -; RSI - (int) Strlen -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - () None. -; Clobbers - RCX, RDX, R9, R9 -; --------------------------------------------------------------------------- -CMP RSI, 1 -JBE .ext - -MOV RCX, 0 -MOV RDX, RSI -DEC RDX - -.loop: - CMP RCX, RDX - JAE .ext - MOV R8B, [RDI+RCX] - MOV R9B, [RDI+RDX] - MOV [RDI+RCX], R9B - MOV [RDI+RDX], R8B - INC RCX - DEC RDX - JMP .loop -.ext: -RET - -global _start -_start: - -PUSH RBP -MOV RBP, RSP -SUB RSP, _start.STACK_INIT - -CMP QWORD [RBP + _start.argc], VALID_ARGC -CMOVB RDI, [Err_Table + INVALID_ARGC*SIZE_LONG] -JB .error - -MOV RDI, [Err_Table + INVALID_EMPTY*SIZE_LONG] -MOV RAX, [RBP + _start.argv1] -CMP BYTE [RAX], 0 -JE .error -MOV RAX, [RBP + _start.argv2] -CMP BYTE [RAX], 0 -JE .error -MOV RAX, [RBP + _start.argv3] -CMP BYTE [RAX], 0 -JE .error - -MOV RSI, [RBP + _start.argv1] -CMP QWORD [RBP + _start.argc], VALID_ARGC -CMOVNE RDI, [Err_Table + INVALID_ARGC*SIZE_LONG] - -CMOVNE RSI, [RBP + _start.argc] -JNE .error - -MOV RAX, [RBP + _start.argv1] -MOV RCX, 0 -MOV RDX, 0 -MOV RBX, 0 -.count_commas: - CMP BYTE [RAX + RCX], 0 - JE .count_end - CMP BYTE [RAX + RCX], ',' - JNE .skip - INC RBX - .skip: - INC RCX - JMP .count_commas -.count_end: -INC RBX -MOV RDI, RBX -CALL ezsqrt -MOV [RBP - _start.NumVerts], RAX -CMP RAX, -1 -CMOVE RDI, [Err_Table + INVALID_NOT_SQUARE*SIZE_LONG] -JE .error -MOV RDI, [RBP + _start.argv2] -CALL parseSRCDST -MOV [RBP - _start.SRC], RAX -MOV RDI, [RBP + _start.argv3] -CALL parseSRCDST -MOV [RBP - _start.DST], RAX -MOV RAX, [RBP - _start.SRC] -MOV RBX, [RBP - _start.DST] -CMP RAX, RBX -CMOVE RDI, [Err_Table+INVALID_SRCDST*SIZE_LONG] -JE .error - -MOV RAX, SYS_MMAP -MOV RDI, NO_ADDR -MOV RSI, [RBP - _start.NumVerts] -SHL RSI, MUL_LONG -MOV RDX, PROT_READ | PROT_WRITE -MOV R10, MAP_SHARED | MAP_ANONYMOUS -MOV R8, NO_FD -MOV R9, NO_OFFSET -SYSCALL -MOV [RBP - _start.graph], RAX -MOV R12, [RBP - _start.NumVerts] -MOV R13, [RBP - _start.graph] - .GRAPH_LOOP: - PUSH RBP - MOV RBP, RSP - SUB RSP, SIZE_LONG*1 - XOR RCX, RCX - MOV QWORD [RBP - SIZE_LONG*1], 0 - .GRAPH_Inner: - MOV RCX, [RBP - SIZE_LONG*1] - CMP RCX, R12 - JAE .GRAPH_Exit - - PUSH RCX - MOV RAX, SYS_MMAP - MOV RDI, NO_ADDR - MOV RSI, R12 - SHL RSI, MUL_INT - .chk_sze: - MOV RDX, PROT_READ | PROT_WRITE - MOV R10, MAP_SHARED | MAP_ANONYMOUS - MOV R8, NO_FD - MOV R9, NO_OFFSET - SYSCALL - POP RCX - MOV [R13 + RCX*SIZE_LONG], RAX - .graph_regchk: - INC RCX - MOV [RBP - SIZE_LONG*1], RCX - JMP .GRAPH_Inner - .GRAPH_Exit: - ADD RSP, SIZE_LONG*1 - MOV RSP, RBP - POP RBP -MOV RDI, [RBP + _start.argv1] -MOV RSI, [RBP - _start.graph] -MOV RDX, [RBP - _start.NumVerts] -CALL parseVertices -MOV RDI, [RBP - _start.SRC] -MOV RSI, [RBP - _start.graph] -MOV RDX, [RBP - _start.NumVerts] -CALL dijkstra -.dijkstra_complete: -MOV RCX, [RBP - _start.DST] -MOV EBX, [RAX + RCX*SIZE_INT] -MOV [RBP - _start.RET], RBX -CMP EBX, -1 -CMOVE RDI, [Err_Table + INVALID_NO_WAY*SIZE_LONG] -JE .error - -MOV RAX, SYS_MMAP -MOV RDI, NO_ADDR -MOV RSI, MAX_STR_INT -INC RSI -MOV RDX, PROT_READ | PROT_WRITE -MOV R10, MAP_SHARED | MAP_ANONYMOUS -MOV R8, NO_FD -MOV R9, NO_OFFSET -SYSCALL -MOV R15, RAX -MOV RDI, [RBP - _start.RET] -MOV RSI, RAX -CALL itoa - -MOV R12, RAX -MOV RSI, R15 -PUSH RAX -MOV RDI, R15 -MOV RSI, R12 -CALL reverseString -POP RAX -INC RAX -MOV RSI, R15 -MOV BYTE [RSI + RAX], NULL - -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, R15 -MOV RDX, R12 -SYSCALL - -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, newline.msg -MOV RDX, newline.len -SYSCALL - -MOV RAX, SYS_EXIT -MOV RDI, [Err_Table+EXIT_OK*SIZE_LONG] -SYSCALL - - -.error: - PUSH RDI - PUSH RSI - MOV RAX, SYS_WRITE - MOV RDI, STDOUT - MOV RSI, Error.msg - MOV RDX, Error.len - SYSCALL - - MOV RAX, SYS_WRITE - MOV RDI, STDOUT - MOV RSI, newline.msg - MOV RDX, newline.len - SYSCALL - - MOV RAX, SYS_EXIT - POP RSI - POP RDI - - SYSCALL - -itoa: -; ---------------------------------------------------------------------------- -; Function: Int to ASCII -; Description: -; Converts integer to ASCII, returned through char[] ptr. -; Parameters: -; RDI - (int) Int to convert. -; RSI - (char[]*) String ptr. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (int) Strlen. -; Clobbers - RAX, RSI, RCX, RDX, R8 -; --------------------------------------------------------------------------- -CMP RDI, 0 -JE .zero -MOV R8, 10 -MOV RCX, 0 -MOV RAX, RDI -MOV RDX, 0 -JMP .loop -.zero: -MOV BYTE [RSI], '0' -MOV RAX, 1 -JMP .ext -.loop: - CMP RAX, 0 - JE .ext - CMP RCX, MAX_STR_INT ; I don't like accessing global stuff from inside functions, though these definitions are stateless at least. - JA .ext - DIV R8 - ADD RDX, '0' - MOV [RSI + RCX], DL - - MOV RDX, 0 - INC RCX - JMP .loop -.ext: -MOV RAX, RCX -RET - -parseSRCDST: -; ---------------------------------------------------------------------------- -; Function: Parse SRC & DST. -; Description: -; Parses given SRC OR DST. Separated from vertice parser for modularity and organization. -; Parsed through Finite State Machine. -; Parameters: -; RDI - (char[]*) Ptr to SRC/DST char array. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; EAX - (int) SRC/DST -; Clobbers - RAX, RDI, RSI, RCX, RDX -; --------------------------------------------------------------------------- -PUSH RBP -MOV RBP, RSP -SUB RSP, parseSRCDST.STACK_INIT - -MOV RCX, 0 - .validate: - MOV DL, BYTE [RDI+RCX] - JMP [.jmpTable + RDX*SIZE_LONG] - .jmpTable: - dq .zero - times 47 dq .error - times 10 dq .num - times 198 dq .error - .cont: - MOV RSI, RCX - CALL atoi - - MOV EAX, EAX - ADD RSP, parseSRCDST.STACK_INIT - MOV RSP, RBP - POP RBP - RET - .zero: - CMP RCX, 0 - CMOVE RAX, [Err_Table+INVALID_SRCDST*SIZE_LONG] - JE .error - JNE .cont - .num: - INC RCX - JMP .validate - .error: - PUSH RAX - MOV RAX, SYS_WRITE - MOV RDI, STDOUT - MOV RSI, Error.msg - MOV RDX, Error.len - SYSCALL - - MOV RAX, SYS_WRITE - MOV RDI, STDOUT - MOV RSI, newline.msg - MOV RDX, newline.len - SYSCALL - - MOV RAX, SYS_EXIT - POP RDI - - SYSCALL - -parseVertices: -; ---------------------------------------------------------------------------- -; Function: Parse Vertices. -; Description: -; Parses given vertices from array and checks for errors. -; Parsed through Finite State Machine. -; Parameters: -; RDI - (char[]*) Ptr to vertice char array. -; RSI - (int[][]*) Ptr to graph 2d array. -; RDX - (int) Number of vertices. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (int) 0 (OK) -; Clobbers - RAX, RDI, RSI, RCX, RDX. -; --------------------------------------------------------------------------- -;Previous States - %DEFINE Parse.STATE.START 0000b - %DEFINE Parse.STATE.NUM 0001b - %DEFINE Parse.STATE.COMMA 0010b - %DEFINE Parse.STATE.SPACE 0100b - %DEFINE Parse.STATE.ZERO 1000b -PUSH RBP -MOV RBP, RSP -SUB RSP, parseVertices.STACK_INIT -MOV [RBP - parseVertices.SRC], RDI -MOV [RBP - parseVertices.DST], RSI -MOV QWORD [RBP - parseVertices.NumVertices], RDX -MOV QWORD [RBP - parseVertices.NumElems], 0 -MOV QWORD [RBP - parseVertices.strlen], 0 -MOV QWORD [RBP - parseVertices.PrevState], Parse.STATE.START -PUSH RBX -PUSH R12 -MOV RAX, RDI -CMP AL, EMPTY_INPUT -CMOVE RAX, [Err_Table+INVALID_EMPTY*SIZE_LONG] -JE .error - -MOV RCX, 0 -XOR RBX, RBX -MOV [RBP - parseVertices.NumPtr], RDI - .validate: - MOV DL, BYTE [RDI+RCX] - - JMP [.jmpTable + RDX*SIZE_LONG] - .jmpTable: - dq .zero - times 31 dq .error - dq .space - times 11 dq .error - dq .comma - times 3 dq .error - times 10 dq .num - times 197 dq .error - - .num: - CMP QWORD [RBP - parseVertices.PrevState], Parse.STATE.START - JE .errSkip - PUSH RDI - PUSH RAX - MOV RAX, [RBP - parseVertices.NumPtr] - MOV RAX, [RAX] - ADD RDI, RCX - CMP QWORD [RBP - parseVertices.PrevState], Parse.STATE.SPACE - CMOVE RAX, RDI - MOV [RBP - parseVertices.NumPtr], RAX - POP RAX - POP RDI - JE .errSkip - CMOVNE RDI, [Err_Table+INVALID_BAD_STR*SIZE_LONG] - JMP .error - .errSkip: - INC QWORD [RBP - parseVertices.strlen] - INC RCX - MOV QWORD [RBP - parseVertices.PrevState], Parse.STATE.NUM - JMP .validate - - .comma: - CMP QWORD [RBP - parseVertices.PrevState], Parse.STATE.NUM - CMOVNE RDI, [Err_Table+INVALID_BAD_STR*SIZE_LONG] - JNE .error - - .zero_jmp: - PUSH RAX - PUSH RDI - PUSH RSI - PUSH RCX - PUSH RDX - MOV RDI, [RBP - parseVertices.NumPtr] - MOV RSI, [RBP - parseVertices.strlen] - CALL atoi - MOV RCX, [RBP - parseVertices.NumElems] - MOV R12, [RBP - parseVertices.DST] - MOV RDI, [R12 + RBX*SIZE_LONG] - MOV [RDI + RCX*SIZE_INT], EAX - .skip_move: - POP RDX - POP RCX - POP RSI - POP RDI - POP RAX - CMP QWORD [RBP - parseVertices.PrevState], Parse.STATE.ZERO - JE .zero_cont - - MOV QWORD [RBP - parseVertices.PrevState], Parse.STATE.COMMA - MOV QWORD [RBP - parseVertices.strlen], 0 - INC RCX - INC QWORD [RBP - parseVertices.NumElems] - PUSH RCX - MOV RCX, [RBP - parseVertices.NumElems] - CMP RCX, [RBP - parseVertices.NumVertices] - POP RCX - JB .skipReset - MOV QWORD [RBP - parseVertices.NumElems], 0 - INC RBX - - .skipReset: - JMP .validate - .space: - CMP QWORD [RBP - parseVertices.PrevState], Parse.STATE.COMMA - CMOVNE RDI, [Err_Table+INVALID_BAD_STR*SIZE_LONG] - JNE .error - INC RCX - MOV QWORD [RBP - parseVertices.PrevState], Parse.STATE.SPACE - JMP .validate - .zero: - CMP QWORD [RBP - parseVertices.PrevState], Parse.STATE.START - JE .skip_err - CMP QWORD [RBP - parseVertices.PrevState], Parse.STATE.NUM - CMOVNE RDI, [Err_Table+INVALID_BAD_STR*SIZE_LONG] - JNE .error - CMP QWORD [RBP - parseVertices.NumElems], 0 - CMOVE RDI, [Err_Table+INVALID_BAD_STR*SIZE_LONG] - JE .error - .skip_err: - MOV QWORD [RBP - parseVertices.PrevState], Parse.STATE.ZERO - JMP .zero_jmp ; I don't like this backwards GOTO. - .zero_cont: - JMP .cont - - .cont: - MOV RAX, 0 - POP R12 - POP RBX - ADD RSP, parseVertices.STACK_INIT - MOV RSP, RBP - POP RBP - RET - .error: - ;For debugging, I can also add pointers, or other info into other registers before SYSCALLing. - PUSH RDX - MOV RAX, SYS_WRITE - MOV RDI, STDOUT - MOV RSI, Error.msg - MOV RDX, Error.len - SYSCALL - - MOV RAX, SYS_WRITE - MOV RDI, STDOUT - MOV RSI, newline.msg - MOV RDX, newline.len - SYSCALL - - MOV RAX, SYS_EXIT - POP RDX - SYSCALL - - - - - - -dijkstra: -; ---------------------------------------------------------------------------- -; Function: priority queue push. -; Description: -; The algorithm of study itself, Dijkstra. -; Parameters: -; EDI - (int) SRC. -; RSI - (int[][]*) Graph to vertice&edges. -; EDX - (int) # Vertices. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (int[]*) Array of distances. -; Clobbers - RAX, RDI, RSI, RCX, RDX, R8, R9, R10, R11. -; --------------------------------------------------------------------------- -PUSH RBP -MOV RBP, RSP -SUB RSP, dijkstra.STACK_INIT -PUSH RBX -PUSH R12 -PUSH R13 -PUSH R14 -PUSH R15 -MOV [RBP - dijkstra.SRC], RDI -MOV [RBP - dijkstra.graph], RSI -MOV [RBP - dijkstra.numVerts], RDX -MOV DWORD [RBP - dijkstra.x], 0 -MOV DWORD [RBP - dijkstra.y], 0 - -MOV RSI, [RBP - dijkstra.SRC] -MOV RDI, [RBP - dijkstra.graph] -CALL dijkstra~GetRow -MOV [RBP - dijkstra.currentRow], RAX -MOV RSI, [RBP - dijkstra.SRC] -MOV RDI, [RBP - dijkstra.graph] - -MMAP_PUSH -MOV RAX, SYS_MMAP -MOV RDI, NO_ADDR -MOV RSI, [RBP - dijkstra.numVerts] -SHL RSI, SIZE_INT -MOV RDX, PROT_READ | PROT_WRITE -MOV R10, MAP_SHARED | MAP_ANONYMOUS -MOV R8, NO_FD -MOV R9, NO_OFFSET -SYSCALL -MOV [RBP - dijkstra.prev], RAX - -MOV RAX, SYS_MMAP -MOV RDI, NO_ADDR -MOV RSI, [RBP - dijkstra.numVerts] -SHL RSI, SIZE_INT -MOV RDX, PROT_READ | PROT_WRITE -MOV R10, MAP_SHARED | MAP_ANONYMOUS -MOV R8, NO_FD -MOV R9, NO_OFFSET -SYSCALL -MOV [RBP - dijkstra.dist], RAX -MMAP_POP -MOV RCX, 0 -MOV R8, [RBP - dijkstra.prev] -MOV R9, [RBP - dijkstra.dist] - .dists_loop: - CMP RCX, [RBP - dijkstra.numVerts] - JE .dists_ext - MOV DWORD [R8 + RCX*SIZE_INT], 0 - MOV DWORD [R9 + RCX*SIZE_INT], INT_MAX - INC RCX - JMP .dists_loop -.dists_ext: -MOV RCX, [RBP - dijkstra.SRC] -MOV DWORD [R9 + RCX*SIZE_INT], 0 -MOV RDI, [RBP - dijkstra.numVerts] -CALL priority_queue@construct -MOV [RBP - dijkstra.PriorityQueue], RAX - -MOV RCX, 0 -MOV RDX, [RBP - dijkstra.currentRow] -MOV RDI, [RBP - dijkstra.SRC] -MOV ESI, 0 -CALL dijkstra~GenerateTuple -MOV RSI, RAX -MOV RDI, [RBP - dijkstra.PriorityQueue] -CALL priority_queue@add -.PQ_INIT_EXIT: - .PQ_LOOP: - MOV RDI, [RBP - dijkstra.PriorityQueue] - CALL priority_queue@isEmpty - CMP RAX, [BOOLs.TRUE] - JE .PQ_EXIT - MOV RDI, [RBP - dijkstra.PriorityQueue] - PUSH R15 - MOV R15, [RDI + priority_queue.heap] - CALL priority_queue@remove - MOV R15, [RDI + priority_queue.heap] - POP R15 - MOV EBX, [RAX + NodeTuple.element] - MOV [RBP - dijkstra.x], EBX - MOV RCX, [RBP - dijkstra.dist] - MOV ECX, [RCX + RBX*SIZE_INT] - MOV RBX, RAX - CMP ECX, 0 - JE .PQ_PASS - CMP ECX, -1 - JE .PQ_PASS - CMP [RBX + NodeTuple.value], ECX - JA .PQ_LOOP - .PQ_PASS: - MOV RDI, [RBP - dijkstra.graph] - MOV ESI, [RBX + NodeTuple.element] - MOV R14D, ESI - CALL dijkstra~GetRow - MOV [RBP - dijkstra.currentRow], RAX - MOV R11, [RBP - dijkstra.dist] - MOV R15, [RBP - dijkstra.currentRow] - MOV RCX, 0 - .neighbor_loop: - - CMP DWORD [R15 + RCX*SIZE_INT], 0 - JE .neighbor_iterate - MOV R14, [RBP - dijkstra.x] - MOV R12D, [R11 + R14*SIZE_INT] - ADD R12D, [R15 + RCX*SIZE_INT] - MOV R13D, [R11 + RCX*SIZE_INT] - CMP R13D, -1 - JE .update - CMP R12D, R13D - JAE .neighbor_iterate - .update: - MOV [R11 + RCX*SIZE_INT], R12D - MOV RDI, [RBP - dijkstra.PriorityQueue] - MOV ESI, ECX - MOV EDX, R12D - CALL priority_queue@decreaseKey - CMP RAX, 1 - JE .neighbor_iterate - MOV RDI, RCX - MOV ESI, R12D - CALL dijkstra~GenerateTuple - MOV RDI, [RBP - dijkstra.PriorityQueue] - MOV RSI, RAX - CALL priority_queue@add - .neighbor_iterate: - INC RCX - CMP RCX, [RBP - dijkstra.numVerts] - JE .PQ_LOOP - JMP .neighbor_loop - -.PQ_EXIT: -POP R15 -POP R14 -POP R13 -POP R12 -POP RBX -MOV RAX, [RBP - dijkstra.dist] -ADD RSP, dijkstra.STACK_INIT -MOV RSP, RBP -POP RBP -RET - - -dijkstra~GenerateTuple: -; ---------------------------------------------------------------------------- -; Function: Dijkstra Generate Tuple -; Description: -; Helper method for dijkstra to generate tuples. -; Preserving RDX, R10, R8, R9 as I know it will be annoying restoring those for every call if clobbered. -; Can replace ad hoc instances of tuple generation. -; Parameters: -; EDI - (int) Element. -; ESI - (int) Value. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (NodeTuple*) Generated Tuple. -; Clobbers - -; --------------------------------------------------------------------------- -MMAP_PUSH -PUSH RSI -PUSH RDI -MOV RAX, SYS_MMAP -MOV RDI, NO_ADDR -MOV RSI, NodeTuple_size -MOV RDX, PROT_READ | PROT_WRITE -MOV R10, MAP_SHARED | MAP_ANONYMOUS -MOV R8, NO_FD -MOV R9, NO_OFFSET -SYSCALL -POP RDI -POP RSI -MOV DWORD [RAX + NodeTuple.value], ESI -MOV DWORD [RAX + NodeTuple.element], EDI - -MMAP_POP -RET - -dijkstra~GetRow: -; ---------------------------------------------------------------------------- -; Function: Dijkstra Get Row -; Description: -; Helper method for dijkstra to grab the address of the needed row given a graph. -; Parameters: -; RDI - (int[][]*) Graph. -; RSI - (int) Row # -; RDX - () Unused -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (int[]*) Row. -; Clobbers - RAX. -; --------------------------------------------------------------------------- -MOV RAX, [RDI + RSI*SIZE_LONG] -RET - - -priority_queue@add: -; ---------------------------------------------------------------------------- -; Function: priority queue add. -; Description: -; Adds new value into minheap. -; Parameters: -; RDI - (PriorityQueue*)This* priority queue. -; RSI - (NodeTuple*) Tuple that contains distance and element. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - () RAX == 0 (Full), RAX == 1 (Success). -; Clobbers - -; --------------------------------------------------------------------------- -MMAP_PUSH ;Having abstracted the min heap allows me to do this. -PUSH R12 -MOV R12, RSI -MOV RDX, [RDI + priority_queue.size] -MOV RSI, [RDI + priority_queue.size] -CMP RDX, [RDI + priority_queue.max_len] -CMOVE RAX, [BOOLs.FALSE] -JE .ext -MOV R8, [RDI + priority_queue.heap] -MOV R8, [R8 + min_heap.elems] -MOV [R8 + RSI*SIZE_LONG], R12 -INC EDX -INC DWORD [RDI + priority_queue.size] -MOV R8D, [RDI + priority_queue.size] -MOV RDI, [RDI + priority_queue.heap] -MOV [RDI + min_heap.size], R8D - -CALL minheap@siftUp -MOV RAX, [BOOLs.TRUE] -.ext: -POP R12 -MMAP_POP -RET - -priority_queue@remove: -; ---------------------------------------------------------------------------- -; Function: priority queue remove. -; Description: -; Removes the first element in both the value and element array of the minheap and returns NodeTuple containing both. -; Preserves RDI -; Parameters: -; RDI - (PriorityQueue*)This* priority queue. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (NodeTuple*) NodeTuple containing value, elem, or nil (0). -; Clobbers - RDI, RSI, RDX, R10, R8, R9. -; --------------------------------------------------------------------------- -PUSH RDI -PUSH RBX -PUSH R12 -PUSH R13 -MOV RBX, [RDI + priority_queue.heap] -MOV R12, [RBX + min_heap.elems] -CMP DWORD [RDI + priority_queue.size], 0 -CMOVA RAX, [BOOLs.FALSE] -JE .ext -MOV RAX, [R12] -PUSH RAX -MOV QWORD [R12], NULL - -MOV EDX, [RDI + priority_queue.size] -DEC EDX -DEC DWORD [RDI + priority_queue.size] -MOV R13D, [RDI + priority_queue.size] -MOV [RBX + min_heap.size], R13D -PUSH RDI -MOV RDI, RBX -MOV RSI, 0 -CALL minheap@swap -POP RDI -MOV RDI, [RDI + priority_queue.heap] -MOV ESI, 0 -CALL minheap@siftDown -POP RAX -.ext: -POP R13 -POP R12 -POP RBX -POP RDI -RET - -priority_queue@peek: -; ---------------------------------------------------------------------------- -; Function: priority queue peek. -; Description: -; Peeks at the first element in both the value and element array of the minheap and returns NodeTuple containing both. -; Parameters: -; RDI - (PriorityQueue*)This* priority queue. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (NodeTuple*) NodeTuple containing value, elem, or nil (0). -; Clobbers - RAX, RSI, RCX. -; --------------------------------------------------------------------------- -PUSH RBX -PUSH R12 -MOV RBX, priority_queue.heap -MOV R12, min_heap.elems -CMP DWORD [RDI + priority_queue.size], 0 -CMOVA RAX, [BOOLs.FALSE] -JE .ext -MOV RSI, [RDI + RBX] -MOV RCX, [RSI + R12] -MOV RAX, [RCX] -.ext: -POP R12 -POP RBX -RET - - - -priority_queue@isEmpty: -; ---------------------------------------------------------------------------- -; Function: priority queue isEmpty. -; Description: -; Gets status of PQ emptiness in boolean form; CMOVcc to avoid branching. -; Parameters: -; RDI - (PriorityQueue*)This* priority queue. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (bool) RAX == 0 FALSE; RAX == 1 TRUE -; Clobbers - RAX, RDI. -; --------------------------------------------------------------------------- -MOV RAX, 0 -CMP QWORD [RDI + priority_queue.size], 0 -CMOVA RAX, [BOOLs.FALSE] -CMOVE RAX, [BOOLs.TRUE] -RET - -priority_queue@size: -; ---------------------------------------------------------------------------- -; Function: priority queue size. -; Description: -; Self explanatory. -; Parameters: -; RDI - (PriorityQueue*)This* priority queue. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; EAX - (int) Size of PQ/Minheap. -; Clobbers - RAX, RDI. -; --------------------------------------------------------------------------- -MOV RAX, [RDI + priority_queue.size] -RET - -priority_queue@decreaseKey: -; ---------------------------------------------------------------------------- -; Function: priority queue decreaseKey. -; Description: -; Decrease priority of given symbol. Implemented through linear search because implementing a hashmap would take too long for now; possibility for improvement. -; Parameters: -; RDI - (PriorityQueue*)This* priority queue. -; ESI - (int) Symbol. -; EDX - (int) Replacement priority. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; EAX - (int) EAX == 0 : NOT IN QUEUE; EAX == 1 : IN QUEUE. -; Clobbers - RAX. -; --------------------------------------------------------------------------- -MMAP_PUSH -MOV RDX, [RDI + priority_queue.heap] -MOV RDX, [RDX + min_heap.elems] -MOV RCX, 0 - .search: - CMP ECX, [RDI + priority_queue.size] - CMOVE RAX, [BOOLs.FALSE] - JE .ext - MOV R10, [RDX + RCX*SIZE_LONG] - CMP ESI, [R10 + NodeTuple.element] - JE .success - INC ECX - JNE .search -.success: -MOV R10, [RDX + RCX*SIZE_LONG] -MOV [R10 + NodeTuple.value], EDX -MOV ESI, ECX -CALL minheap@siftUp -MOV RAX, [BOOLs.TRUE] -.ext: -MMAP_POP -RET - -priority_queue@construct: -; ---------------------------------------------------------------------------- -; Function: Priority Queue Constructor -; Description: -; Restores min-heap by moving new element upward. -; Parameters: -; RDI - (int) Allowing size to be defined ahead of time so there's no slow and annoying SYS_MREMAP. (SIZE OF MMAP, NOT ACTUAL HEAP SIZE!) -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (PriorityQueue*)Ptr to new PQ. -; Clobbers - RAX, RDI, RSI, RCX, RDX, R8, R9, R10. -; --------------------------------------------------------------------------- -.constrct: -PUSH RBP -MOV RBP, RSP -SUB RSP, priority_queue@construct.STACK_INIT -PUSH R13 -PUSH R12 -MOV R12, RDI - -MOV RAX, SYS_MMAP -MOV RDI, NO_ADDR -MOV RSI, priority_queue_size -MOV RDX, PROT_READ | PROT_WRITE -MOV R10, MAP_SHARED | MAP_ANONYMOUS -MOV R8, NO_FD -MOV R9, NO_OFFSET -SYSCALL -MOV [RBP - priority_queue@construct.PQPtr], RAX -MOV QWORD [RAX + priority_queue.size], 0 -MOV [RAX + priority_queue.max_len], R12 - -MOV RAX, SYS_MMAP -MOV RDI, NO_ADDR -MOV RSI, R12 -SHL RSI, MUL_LONG -MOV RDX, PROT_READ | PROT_WRITE -MOV R10, MAP_SHARED | MAP_ANONYMOUS -MOV R8, NO_FD -MOV R9, NO_OFFSET -SYSCALL - -MOV RDI, RAX -MOV RSI, R12 -CALL minheap@construct -MOV RDI, [RBP - priority_queue@construct.PQPtr] -MOV [RDI + priority_queue.heap], RAX - -POP R12 -POP R13 -MOV RAX, [RBP - priority_queue@construct.PQPtr] -ADD RSP, priority_queue@construct.STACK_INIT -MOV RSP, RBP -POP RBP -RET - -priority_queue@destruct: -; ---------------------------------------------------------------------------- -; Function: Priority Queue Destructor -; Description: -; Destructs Priority Queue -; Parameters: -; RDI - (PriorityQueue*)Ptr to priority queue. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - () -; Clobbers - RDI, RSI, RDX. -; --------------------------------------------------------------------------- -PUSH RDI -MOV RDI, [RDI + priority_queue.heap] -CALL minheap@destruct - -MOV RAX, SYS_MUNMAP -POP RDI -MOV RSI, priority_queue_size -SYSCALL -XOR RDI, RDI ; Killing RDI so stale ptr isn't passed on. -RET - -minheap@siftUp: -; ---------------------------------------------------------------------------- -; Function: minheap sift up -; Description: -; Restores min-heap by moving new element upward. -; Parameters: -; RDI - (Minheap*) This* minheap. -; ESI - (int) Index. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - () None. -; Clobbers - RDI, RSI, RCX, RDX, R10, R8, R9, R11. -; --------------------------------------------------------------------------- - .sift_loop: - CMP ESI, 0 - JE .sift_ext - PUSH RDI - MOV RDI, RSI - CALL minheap@parent - - MOV R11, RDI - POP RDI - MOV RDX, [RDI + min_heap.elems] - - MOV R8, [RDX + RAX*SIZE_LONG] - MOV R9, [RDX + RSI*SIZE_LONG] - MOV ECX, [R8 + NodeTuple.value] - CMP ECX, [R9 + NodeTuple.value] - JBE .sift_ext - MOV EDX, EAX - MOV ESI, R11D - CALL minheap@swap - MOV RSI, RAX - JMP .sift_loop -.sift_ext: -RET -minheap@siftDown: -; ---------------------------------------------------------------------------- -; Function: minheap sift down. -; Description: -; Restores min-heap by moving root downward. -; Parameters: -; RDI - (Minheap*) This* minheap. -; ESI - (int) Index. -; EDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - () None. -; Clobbers - RAX, RDI, RSI, RCX, RDX, R10, R8, R9, R11. -; --------------------------------------------------------------------------- -PUSH RDI - - .sift: - MOV RCX, RDI - MOV R10D, ESI - MOV RDI, RSI - CALL minheap@left - MOV R9, RAX - CALL minheap@right - MOV R8, RAX - MOV EDX, EDI - - MOV R11, [RCX + min_heap.elems] - CMP R9D, [RCX + min_heap.size] - JAE .skpLft - MOV RDX, R9 - .skpLft: - CMP R8D, [RCX + min_heap.size] - JAE .skpRgt - MOV RDX, R8 - .skpRgt: - CMP RDX, R10 - JE .siftEXT - PUSH RCX - PUSH RDX - MOV RDI, RCX - MOV RSI, R10 - CALL minheap@swap - POP RSI - POP RDI - JMP .sift -.siftEXT: -POP RDI -RET - - -minheap@swap: -; ---------------------------------------------------------------------------- -; Function: minheap swap -; Description: -; Swaps elements between given two indices. -; Parameters: -; RDI - (Minheap*) Minheap to operate on. -; ESI - (int) Index one. -; EDX - (int) Index two. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - () None. -; Clobbers - R8, R9, R10. -; --------------------------------------------------------------------------- -MOV R10, [RDI + min_heap.elems] -MOV R8, [R10 + RSI*SIZE_LONG] -MOV R9, [R10 + RDX*SIZE_LONG] -MOV [R10 + RSI*SIZE_LONG], R9 -MOV [R10 + RDX*SIZE_LONG], R8 -RET - - -minheap@parent: -; ---------------------------------------------------------------------------- -; Function: minheap parent -; Description: -; Grabs parent element index relative to given index. -; Parameters: -; EDI - (int) Index. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (long) Parent index. -; Clobbers - RAX -; --------------------------------------------------------------------------- -MOV EAX, EDI -DEC RAX -SHR RAX, DIV_2 -RET -minheap@left: -; ---------------------------------------------------------------------------- -; Function: minheap left -; Description: -; Grabs left element index relative to given index. -; Parameters: -; EDI - (int) Index. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (long) Left element index. -; Clobbers - RAX -; --------------------------------------------------------------------------- -MOV EAX, EDI -SHL RAX, MUL_2 -INC RAX -RET -minheap@right: -; ---------------------------------------------------------------------------- -; Function: minheap right -; Description: -; Grabs right element index relative to given index. -; Parameters: -; EDI - (minheap) Index. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (long) Right element index. -; Clobbers - RAX -; --------------------------------------------------------------------------- -MOV EAX, EDI -SHL RAX, MUL_2 -ADD RAX, 2 -RET -minheap@construct: -; ---------------------------------------------------------------------------- -; Function: Minheap Constructor -; Description: -; Constructs minheap with information generated by priority_queue@construct -; Parameters: -; RDI - (long[]*) Element array. -; ESI - (int) Array size. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (Minheap*) Minheap ptr. -; Clobbers - RAX -; --------------------------------------------------------------------------- -MMAP_PUSH - -MOV RAX, SYS_MMAP -MOV RDI, NO_ADDR -MOV RSI, min_heap_size -MOV RDX, PROT_READ | PROT_WRITE -MOV R10, MAP_SHARED | MAP_ANONYMOUS -MOV R8, NO_FD -MOV R9, NO_OFFSET -SYSCALL - -MMAP_POP - -MOV [RAX + min_heap.elems], RDI -MOV [RAX + min_heap.max_len], RSI -MOV QWORD [RAX + min_heap.size], 0 - -RET - -minheap@destruct: -; ---------------------------------------------------------------------------- -; Function: Minheap Destructor -; Description: -; Destructs Minheap; only to be called by priority_queue@destruct -; Parameters: -; RDI - (Minheap*) Ptr to minheap. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - () -; Clobbers - RDI, RSI, RDX. -; --------------------------------------------------------------------------- -MOV RDX, RDI - -MOV RAX, SYS_MUNMAP -MOV RDI, [RDX + min_heap.elems] -MOV RSI, [RDX + min_heap.max_len] -SYSCALL - -MOV RAX, SYS_MUNMAP -MOV RDI, [RDX] -MOV RSI, min_heap_size -SYSCALL - -XOR RDX, RDX ; I want to kill this register so a stale ptr to minheap isn't passing on after this function's lifetime. -RET -ezsqrt: -; ---------------------------------------------------------------------------- -; Function: Easy Square Root -; Description: -; Checks if number is perfect square; returns square root into RAX. -; Parameters: -; EDI - (long) Input value to sqrt. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (long) RAX == -1 (Input not square); RAX > 0 (Input IS perfect square). -; Clobbers - RAX, RDI, RCX, RDX -; --------------------------------------------------------------------------- - PUSH RBP - MOV RBP, RSP - PUSH RBX - - MOV RBX, -1 - MOV RCX, 1 - .sqrt_loop: - MOV RAX, RCX - MUL RCX - CMP EAX, EDI - JE .ext - INC RCX - CMP EAX, EDI - CMOVA RAX, RBX - JA .short_circuit - JB .sqrt_loop - .ext: - MOV RAX, RCX - .short_circuit: - POP RBX - MOV RSP, RBP - POP RBP - RET - -atoi: -; ---------------------------------------------------------------------------- -; Function: atoi -; Description: -; Converts ascii string to integer. -; Parameters: -; RDI - (char[]*) Pointer to string to convert to integer. -; RSI - (long) Strlen. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; EAX - (int) Integer value of string. -; Clobbers - RAX, RDX, RCX, R10. -; --------------------------------------------------------------------------- - PUSH RBX - .check_atoi: - - MOV RCX, 0 - MOV RBX, 10 - MOV RAX, 0 - .loop: - MOV R10B, [RDI + RCX] - SUB R10B, '0' - MUL RBX - ADD EAX, R10D - INC RCX - JB .loop - .ext: - POP RBX - RET - - - -``` - -{% endraw %} - -Dijkstra in [x86-64](/languages/x86-64) was written by: - -- Raymond Marx - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/ada/index.md b/docs/projects/duplicate-character-counter/ada/index.md deleted file mode 100644 index f0bf59e0e4..0000000000 --- a/docs/projects/duplicate-character-counter/ada/index.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-10 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-10 -layout: default -tags: -- ada -- duplicate-character-counter -title: Duplicate Character Counter in Ada -title1: Duplicate Character -title2: Counter in Ada ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -pragma Ada_2022; - -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Characters.Handling; use Ada.Characters.Handling; - -with Ada.Containers.Hashed_Maps; - -procedure Duplicate_Character_Counter is - - function Hash (C : Character) return Ada.Containers.Hash_Type - is (Ada.Containers.Hash_Type (Character'Pos (C))); - - function Equivalent (L, R : Character) return Boolean - is (L = R); - - package Char_Count_Map is new - Ada.Containers.Hashed_Maps - (Key_Type => Character, - Element_Type => Natural, - Hash => Hash, - Equivalent_Keys => Equivalent); - - use Char_Count_Map; - - function Count (Input : String) return Map is - M : Map; - begin - for C of Input loop - if Is_Alphanumeric (C) then - if M.Contains (C) then - M.Replace (C, M.Element (C) + 1); - else - M.Insert (C, 1); - end if; - end if; - end loop; - - return M; - end Count; - - procedure Print_Duplicates (Input : String; M : Map) is - Seen : array (Character) of Boolean := [others => False]; - Found : Boolean := False; - begin - for C of Input loop - if Is_Alphanumeric (C) - and then M.Contains (C) - and then M.Element (C) > 1 - and then not Seen (C) - then - Put_Line (C & ":" & Natural'Image (M.Element (C))); - Seen (C) := True; - Found := True; - end if; - end loop; - - if not Found then - Put_Line ("No duplicate characters"); - end if; - end Print_Duplicates; - - Input : constant String := - (if Argument_Count = 1 then Argument (1) else ""); - -begin - if Input = "" then - Put_Line ("Usage: please provide a string"); - Set_Exit_Status (Failure); - return; - end if; - - declare - M : constant Map := Count (Input); - begin - Print_Duplicates (Input, M); - end; - -end Duplicate_Character_Counter; - -``` - -{% endraw %} - -Duplicate Character Counter in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/algol60/index.md b/docs/projects/duplicate-character-counter/algol60/index.md deleted file mode 100644 index c124c34d93..0000000000 --- a/docs/projects/duplicate-character-counter/algol60/index.md +++ /dev/null @@ -1,201 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-01 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-04-06 -layout: default -tags: -- algol60 -- duplicate-character-counter -title: Duplicate Character Counter in ALGOL 60 -title1: Duplicate Character -title2: Counter in ALGOL 60 ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please provide a string\n"); - stop - end usage; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - procedure outAsciiChar(ch); - value ch; - integer ch; - begin - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - outchar( - 1, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ) - end outAsciiChar; - - integer procedure duplicateCharacterCounter(s, len, charCounts, foundChars); - value len; - integer array s, charCounts, foundChars; - integer len; - begin - integer i, ch, numFoundChars; - - comment Initialize character counts; - for i := 1 step 1 until 127 do charCounts[i] := 0; - - comment Count number of times each character is found and keep - track of each unique character found; - numFoundChars := 0; - for i := 1 step 1 until len do - begin - ch := s[i]; - charCounts[ch] := charCounts[ch] + 1; - if charCounts[ch] = 1 then - begin - numFoundChars := numFoundChars + 1; - foundChars[numFoundChars] := ch - end - end; - - duplicateCharacterCounter := numFoundChars - end duplicateCharacterCounter; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - procedure outDuplicateCharacterCounts(charCounts, foundChars, numFoundChars); - value numFoundChars; - integer numFoundChars; - integer array charCounts, foundChars; - begin - boolean dupesFound; - integer i, ch; - - dupesFound := false; - for i := 1 step 1 until numFoundChars do - begin - ch := foundChars[i]; - if charCounts[ch] > 1 then - begin - dupesFound := true; - outAsciiChar(ch); - outstring(1, ": "); - outIntegerNoSpace(charCounts[ch]); - outstring(1, "\n") - end - end; - - if !dupesFound then outstring(1, "No duplicate characters\n") - end outDuplicateCharacterCounts; - - integer argc, len, numFoundChars; - integer array s[1:256], charCounts[1:127], foundChars[1:127]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get string as integer array. Exit if empty; - len := inCharArray(s, 256); - if len < 1 then usage; - - comment Get duplicate character counts and show duplicate character counts; - numFoundChars := duplicateCharacterCounter(s, len, charCounts, foundChars); - outDuplicateCharacterCounts(charCounts, foundChars, numFoundChars) -end - -``` - -{% endraw %} - -Duplicate Character Counter in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/algol68/index.md b/docs/projects/duplicate-character-counter/algol68/index.md deleted file mode 100644 index 8f2f74492a..0000000000 --- a/docs/projects/duplicate-character-counter/algol68/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-22 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- duplicate-character-counter -title: Duplicate Character Counter in ALGOL 68 -title1: Duplicate Character -title2: Counter in ALGOL 68 ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC usage = VOID: printf(($gl$, "Usage: please provide a string")); - -PROC duplicate character counter = (STRING s) REF []INT: -( - # Initialize character counter # - HEAP [0..255]INT char counter; - FOR k FROM LWB char counter TO UPB char counter - DO - char counter[k] := 0 - OD; - - # Count number of occurances of each character # - FOR k TO UPB s - DO - char counter[ABS s[k]] +:= 1 - OD; - - char counter -); - -PROC show duplicate character counts = (STRING s, REF []INT char counter) VOID: -( - BOOL has dupes := FALSE; - INT code; - FOR k TO UPB s - DO - code := ABS s[k]; - IF char counter[code] > 1 - THEN - printf(($g": "gl$, s[k], whole(char counter[code], 0))); - char counter[code] := 0; - has dupes := TRUE - FI - OD; - - IF NOT has dupes - THEN - printf(($gl$, "No duplicate characters")) - FI -); - -# Get 1st command-line argument. Exit if empty # -STRING s := argv(4); -IF UPB s = 0 -THEN - usage; - stop -FI; - -# Count duplicate characters # -REF []INT char counter := duplicate character counter(s); - -# Show all duplicate character counts in order in which they occurred in string (if any) # -show duplicate character counts(s, char counter) - -``` - -{% endraw %} - -Duplicate Character Counter in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/awk/index.md b/docs/projects/duplicate-character-counter/awk/index.md deleted file mode 100644 index 6f12250ff9..0000000000 --- a/docs/projects/duplicate-character-counter/awk/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-06 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- duplicate-character-counter -title: Duplicate Character Counter in AWK -title1: Duplicate Character -title2: Counter in AWK ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a string" - exit(1) -} - -function duplicate_character_counter(s, counts, order, i, c) { - for (i = 1; i <= length(s); i++) { - c = substr(s, i, 1) - if (!(c in counts)) { - order[i] = c - } - - counts[c]++ - } -} - -function display_duplicate_character_counts(counts, order, dupes, idx, c) { - dupes = 0 - for (idx in order) { - c = order[idx] - if (counts[c] > 1) { - print c ": " counts[c] - dupes = 1 - } - } - - if (!dupes) { - print "No duplicate characters" - } -} - -BEGIN { - if (ARGC < 2 || !ARGV[1]) { - usage() - } - - s = ARGV[1] - duplicate_character_counter(s, counts, order) - display_duplicate_character_counts(counts, order) -} - -``` - -{% endraw %} - -Duplicate Character Counter in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/beef/index.md b/docs/projects/duplicate-character-counter/beef/index.md deleted file mode 100644 index 4ffa9dac39..0000000000 --- a/docs/projects/duplicate-character-counter/beef/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-18 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2024-01-18 -layout: default -tags: -- beef -- duplicate-character-counter -title: Duplicate Character Counter in Beef -title1: Duplicate Character -title2: Counter in Beef ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace DuplicateCharacterCounter; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a string"); - Environment.Exit(0); - } - - public static void CountDuplicateCharacters(StringView str, uint[] dupeCounter) - { - for (int i < 256) - { - dupeCounter[i] = 0; - } - - for (char8 ch in str) - { - dupeCounter[(int)ch]++; - } - } - - public static void ShowDuplicateCharacterCounts(StringView str, uint[] dupeCounter) - { - bool hasDupes = false; - for (char8 ch in str) - { - uint dupeCount = dupeCounter[(int)ch]; - if (dupeCount > 1) - { - Console.WriteLine($"{ch}: {dupeCount}"); - dupeCounter[(int)ch] = 0; // Indicate character already seen - hasDupes = true; - } - } - - if (!hasDupes) - { - Console.WriteLine("No duplicate characters"); - } - } - - public static int Main(String[] args) - { - if (args.Count < 1 || args[0].Length < 1) - { - Usage(); - } - - uint[] dupeCounter = scope uint[256]; - CountDuplicateCharacters(args[0], dupeCounter); - ShowDuplicateCharacterCounts(args[0], dupeCounter); - return 0; - } -} - -``` - -{% endraw %} - -Duplicate Character Counter in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/c-plus-plus/index.md b/docs/projects/duplicate-character-counter/c-plus-plus/index.md deleted file mode 100644 index dbb491bf72..0000000000 --- a/docs/projects/duplicate-character-counter/c-plus-plus/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Vipin Yadav -- Ștefan-Iulian Alecu -date: 2022-10-03 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- duplicate-character-counter -title: Duplicate Character Counter in C++ -title1: Duplicate Character -title2: Counter in C++ ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cout << "Usage: please provide a string\n"; - std::exit(1); -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - std::string_view input{argv[1]}; - if (input.empty()) usage(); - - std::array counts{}; - - for (const auto c : input) { - counts[c]++; - } - - bool any_duplicates = false; - - for (const auto c : input) { - if (counts[c] > 1) { - std::cout << std::format("{}: {}\n", c, counts[c]); - counts[c] = 0; - any_duplicates = true; - } - } - - if (!any_duplicates) { - std::cout << "No duplicate characters\n"; - } -} -``` - -{% endraw %} - -Duplicate Character Counter in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Vipin Yadav -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/c-sharp/index.md b/docs/projects/duplicate-character-counter/c-sharp/index.md deleted file mode 100644 index 4781f17f9d..0000000000 --- a/docs/projects/duplicate-character-counter/c-sharp/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Huma Homidov -- Ștefan-Iulian Alecu -date: 2024-11-12 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- duplicate-character-counter -title: Duplicate Character Counter in C# -title1: Duplicate Character -title2: Counter in C# ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var input] || string.IsNullOrWhiteSpace(input)) -{ - Console.Error.WriteLine("Usage: please provide a string"); - return; -} - -Span freq = stackalloc int[128]; - -foreach (char c in input) - if (c < 128) - freq[c]++; - -bool found = false; - -foreach (char c in input) -{ - if (c >= 128 || freq[c] < 2) - continue; - - Console.WriteLine($"{c}: {freq[c]}"); - freq[c] = 0; - found = true; -} - -if (!found) - Console.WriteLine("No duplicate characters"); -``` - -{% endraw %} - -Duplicate Character Counter in [C#](/languages/c-sharp) was written by: - -- Huma Homidov -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/c/index.md b/docs/projects/duplicate-character-counter/c/index.md deleted file mode 100644 index e200222e30..0000000000 --- a/docs/projects/duplicate-character-counter/c/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Vipin Yadav -- Ștefan-Iulian Alecu -date: 2022-10-03 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- duplicate-character-counter -title: Duplicate Character Counter in C -title1: Duplicate Character -title2: Counter in C ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -// Function to handle errors -int handle_error() -{ - printf("Usage: please provide a string\n"); - exit(0); -} - -int main(int argc, char *argv[]) -{ - /* - Condition to check for No String as Input - */ - if (argc != 2) - handle_error(); - /* - Condition to check for No String as Input - */ - if (strlen(argv[1]) == 0) - handle_error(); - - int counter[256] = {0}; - int len = strlen(argv[1]); - for (int i = 0; i < len; i++) - counter[argv[1][i] - 1]++; - - int flag = 1; - for (int i = 0; i < len; i++) - { - char c = argv[1][i]; - if (counter[c - 1] > 1) - { - flag = 0; - printf("%c: %d\n", c, counter[c - 1]); - counter[c - 1] = 0; - } - } - - if (flag == 1) - printf("No duplicate characters\n"); - - return 0; -} -``` - -{% endraw %} - -Duplicate Character Counter in [C](/languages/c) was written by: - -- Vipin Yadav -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/cobol/index.md b/docs/projects/duplicate-character-counter/cobol/index.md deleted file mode 100644 index 18e099a9eb..0000000000 --- a/docs/projects/duplicate-character-counter/cobol/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-30 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- cobol -- duplicate-character-counter -title: Duplicate Character Counter in COBOL -title1: Duplicate Character -title2: Counter in COBOL ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. duplicate-character-counter. - -data division. -working-storage section. - -01 input-str pic x(200). -01 usage-msg pic x(50) value 'Usage: please provide a string'. - -01 i pic 9(4). -01 len pic 9(4). - -01 ascii-table. - 05 ascii-map occurs 256 times pic 9(4) value 0. - -01 seen-table. - 05 seen occurs 256 times pic 9 value 0. - -01 current-char pic x. -01 ascii-val pic 9(4). - -01 has-duplicates pic 9 value 0. - -01 out-count pic z(4)9. - -procedure division. - -main. - - accept input-str from argument-value - - if input-str = spaces - display usage-msg - stop run - end-if - - move function length(function trim(input-str)) to len - - if len = 0 - display usage-msg - stop run - end-if - - perform varying i from 1 by 1 until i > len - move input-str(i:1) to current-char - move function ord(current-char) to ascii-val - add 1 to ascii-map(ascii-val) - end-perform - - perform varying i from 1 by 1 until i > len - - move input-str(i:1) to current-char - move function ord(current-char) to ascii-val - - if ascii-map(ascii-val) > 1 and seen(ascii-val) = 0 - - move ascii-map(ascii-val) to out-count - - display current-char ": " function trim(out-count) - - move 1 to seen(ascii-val) - move 1 to has-duplicates - end-if - - end-perform - - if has-duplicates = 0 - display "No duplicate characters" - end-if - - stop run. -``` - -{% endraw %} - -Duplicate Character Counter in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/commodore-basic/index.md b/docs/projects/duplicate-character-counter/commodore-basic/index.md deleted file mode 100644 index add0d6ffc9..0000000000 --- a/docs/projects/duplicate-character-counter/commodore-basic/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2023-10-15 -layout: default -tags: -- commodore-basic -- duplicate-character-counter -title: Duplicate Character Counter in Commodore BASIC -title1: Duplicate Character Counter -title2: in Commodore BASIC ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM CC%(255): REM character counter -15 REM Input string -20 GOSUB 1000 -30 IF S$ = "" THEN GOTO 200 -35 REM Count characters -40 L% = LEN(S$) -50 FOR K = 1 TO L% -60 CN% = ASC(MID$(S$, K, 1)) -70 CC%(CN%) = CC%(CN%) + 1 -80 NEXT K -85 REM Show duplicate character counts -90 DP% = 0 -100 FOR K = 1 TO L% -110 A$ = MID$(S$, K, 1) -120 CN% = ASC(A$) -130 IF CC%(CN%) < 2 THEN GOTO 170 -140 PRINT A$; ": "; MID$(STR$(CC%(CN%)), 2) -150 CC%(CN%) = 0: REM indicate character displayed -160 DP% = 1 -170 NEXT K -180 IF DP% = 0 THEN PRINT "No duplicate characters" -190 END -200 PRINT "Usage: please provide a string" -210 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 13 OR C = 255 THEN RETURN: REM end of value or input -1050 S$ = S$ + A$ -1060 GOTO 1020 - -``` - -{% endraw %} - -Duplicate Character Counter in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/dart/index.md b/docs/projects/duplicate-character-counter/dart/index.md deleted file mode 100644 index 102f2249ef..0000000000 --- a/docs/projects/duplicate-character-counter/dart/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- gangaasoonu -date: 2025-10-04 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-10-04 -layout: default -tags: -- dart -- duplicate-character-counter -title: Duplicate Character Counter in Dart -title1: Duplicate Character -title2: Counter in Dart ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -//Issue 4974 -void main(List args){ - const String error_message = "Usage: please provide a string"; - if (args.isEmpty || args[0].isEmpty){ - print(error_message); - return; - } // end of empty check - - Map frequency = {}; - bool duplicate_not_found = true; - - for (int i = 0; i < args[0].length; i ++){ - String char = args[0][i]; - if (RegExp(r'[a-zA-Z0-9]').hasMatch(char)) { - frequency[char] = (frequency[char] ?? 0) + 1; - } - } // end of checking duplicate characters - - //either print all duplicate letters or set flag duplicate letters not found - frequency.forEach((char, count){ - if (count > 1) { - duplicate_not_found = false; // at least 1 duplicate letter is found - print('$char: $count'); - } - }); - // print if no duplicate characters - if(duplicate_not_found == true){ - print("No duplicate characters"); - } -} - -``` - -{% endraw %} - -Duplicate Character Counter in [Dart](/languages/dart) was written by: - -- gangaasoonu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/euphoria/index.md b/docs/projects/duplicate-character-counter/euphoria/index.md deleted file mode 100644 index fcf3d8fe5a..0000000000 --- a/docs/projects/duplicate-character-counter/euphoria/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- duplicate-character-counter -- euphoria -title: Duplicate Character Counter in Euphoria -title1: Duplicate Character -title2: Counter in Euphoria ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e - -function duplicate_character_counter(sequence s) - -- Initialize character counter - sequence char_counter = repeat(0, 256) - - -- Count number of occurances of each character - for n = 1 to length(s) - do - char_counter[s[n] + 1] += 1 - end for - - return char_counter -end function - -procedure show_duplicate_character_counts(sequence s, sequence char_counter) - boolean has_dupes = FALSE - - for n = 1 to length(s) - do - integer index = s[n] + 1 - if char_counter[index] > 1 - then - printf(STDOUT, "%s: %d\n", {s[n], char_counter[index]}) - char_counter[index] = 0 - has_dupes = TRUE - end if - end for - - if not has_dupes - then - puts(STDOUT, "No duplicate characters\n") - end if -end procedure - -procedure usage() - printf(STDOUT, "Usage: please provide a string") - abort(0) -end procedure - --- Parse 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Count duplicate characters -sequence s = argv[4] -sequence char_counter = duplicate_character_counter(s) - --- Show all duplicate character counts in order in which they occurred in string (if any) -show_duplicate_character_counts(s, char_counter) - -``` - -{% endraw %} - -Duplicate Character Counter in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/f-sharp/index.md b/docs/projects/duplicate-character-counter/f-sharp/index.md deleted file mode 100644 index 39cf923dd5..0000000000 --- a/docs/projects/duplicate-character-counter/f-sharp/index.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- duplicate-character-counter -- f-sharp -title: Duplicate Character Counter in F# -title1: Duplicate Character -title2: Counter in F# ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -let usage = "Usage: please provide a string" - -module DuplicateCharacterCounter = - let private getDuplicateCounts = - Seq.countBy id - >> Seq.filter (fun (_, count) -> count > 1) - >> Seq.map (fun (c, count) -> sprintf "%c: %d" c count) - >> Seq.toList - - let private formatOutput = - function - | [] -> "No duplicate characters" - | items -> String.concat "\n" items - - let run input = - input |> getDuplicateCounts |> formatOutput |> Ok - -module Helpers = - let (|Empty|NonEmpty|) (s: string) = - match s.Trim() with - | "" -> Empty - | trimmed -> NonEmpty trimmed - - let parseArgs argv = - match argv with - | [| Empty |] -> Error usage - | [| NonEmpty input |] -> Ok input - | _ -> Error usage - - let handleResults = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.bind DuplicateCharacterCounter.run - |> Helpers.handleResults - -``` - -{% endraw %} - -Duplicate Character Counter in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/go/index.md b/docs/projects/duplicate-character-counter/go/index.md deleted file mode 100644 index ac5abca774..0000000000 --- a/docs/projects/duplicate-character-counter/go/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2024-10-08 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2024-10-08 -layout: default -tags: -- duplicate-character-counter -- go -title: Duplicate Character Counter in Go -title1: Duplicate Character -title2: Counter in Go ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" -) - -func errorMessage() { - fmt.Println("Usage: please provide a string") -} - -func main() { - if len(os.Args) <= 1 { - errorMessage() - return - } - - inputStr := os.Args[1] - - if len(inputStr) == 0 { - errorMessage() - return - } - charCount := make(map[rune]int) - for _, c := range inputStr { - charCount[c]++ - } - duplicateFound := false - for _, c := range inputStr { - if count, exists := charCount[c]; exists && count > 1 { - if !duplicateFound { - duplicateFound = true - } - fmt.Printf("%c: %d\n", c, count) - charCount[c] = 0 - } - } - - if !duplicateFound { - fmt.Println("No duplicate characters") - } -} - -``` - -{% endraw %} - -Duplicate Character Counter in [Go](/languages/go) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/haskell/index.md b/docs/projects/duplicate-character-counter/haskell/index.md deleted file mode 100644 index 6725b435e5..0000000000 --- a/docs/projects/duplicate-character-counter/haskell/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-23 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-23 -layout: default -tags: -- duplicate-character-counter -- haskell -title: Duplicate Character Counter in Haskell -title1: Duplicate Character -title2: Counter in Haskell ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -{-# LANGUAGE TupleSections #-} - -module Main where - -import Data.Map (Map) -import qualified Data.Map.Strict as Map -import System.Environment (getArgs) - -duplicateCharacters :: String -> Map Char Int -duplicateCharacters = Map.filter (> 1) . Map.fromListWith (+) . map (, 1) - -printDuplicates :: String -> Map Char Int -> IO () -printDuplicates [] _ = return () -printDuplicates (x:xs) m = - case Map.updateLookupWithKey (\_ _ -> Nothing) x m of - (Just count, m') -> putStrLn (x : ": " ++ show count) >> printDuplicates xs m' - _ -> printDuplicates xs m - -main :: IO () -main = do - args <- getArgs - case args of - [xs@(_:_)] -> - let m = duplicateCharacters xs - in if Map.null m - then putStrLn "No duplicate characters" - else printDuplicates xs m - _ -> putStrLn "Usage: please provide a string" - - -``` - -{% endraw %} - -Duplicate Character Counter in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/index.md b/docs/projects/duplicate-character-counter/index.md deleted file mode 100644 index bf1d9ccdd8..0000000000 --- a/docs/projects/duplicate-character-counter/index.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -date: 2022-05-14 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-23 -layout: default -tags: -- duplicate-character-counter -title: Duplicate Character Counter -title1: Duplicate -title2: Character Counter ---- - - - -Welcome to the Duplicate Character Counter page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -## Description - -Although a one line solution for this problem is feasible, just as -huge brute force solutions are, we should avoid both of these -approaches. Instead, our goal should be to find a fine line between -both, where the code is not bogged down but is largely readable and -maintainable. - - -## Requirements - -The code should return the count of all duplicate, case-sensitive, -alphanumeric characters, that occur more than once in the given string. -Characters should also be presented in the order in which they appear -in the string. For instance, 'abba' should output 'a' as the first character -that has a duplicate. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Duplicate Character Counter. -In order to keep things simple, we split up the testing as follows: - -- Duplicate Character Counter Valid Tests -- Duplicate Character Counter Invalid Tests - -### Duplicate Character Counter Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: No Duplicates | "hola" | "No duplicate characters" | -| Sample Input: Routine | "goodbyeblues" | "o: 2"
"b: 2"
"e: 2" | - -### Duplicate Character Counter Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | - -All of these tests should output the following: - -``` -Usage: please provide a string -``` - - -## Articles - -There are 36 articles: - -- [Duplicate Character Counter in ALGOL 60](/projects/duplicate-character-counter/algol60) -- [Duplicate Character Counter in ALGOL 68](/projects/duplicate-character-counter/algol68) -- [Duplicate Character Counter in AWK](/projects/duplicate-character-counter/awk) -- [Duplicate Character Counter in Ada](/projects/duplicate-character-counter/ada) -- [Duplicate Character Counter in Beef](/projects/duplicate-character-counter/beef) -- [Duplicate Character Counter in C](/projects/duplicate-character-counter/c) -- [Duplicate Character Counter in C#](/projects/duplicate-character-counter/c-sharp) -- [Duplicate Character Counter in C++](/projects/duplicate-character-counter/c-plus-plus) -- [Duplicate Character Counter in COBOL](/projects/duplicate-character-counter/cobol) -- [Duplicate Character Counter in Commodore BASIC](/projects/duplicate-character-counter/commodore-basic) -- [Duplicate Character Counter in Dart](/projects/duplicate-character-counter/dart) -- [Duplicate Character Counter in Euphoria](/projects/duplicate-character-counter/euphoria) -- [Duplicate Character Counter in F#](/projects/duplicate-character-counter/f-sharp) -- [Duplicate Character Counter in Go](/projects/duplicate-character-counter/go) -- [Duplicate Character Counter in Haskell](/projects/duplicate-character-counter/haskell) -- [Duplicate Character Counter in Java](/projects/duplicate-character-counter/java) -- [Duplicate Character Counter in JavaScript](/projects/duplicate-character-counter/javascript) -- [Duplicate Character Counter in Kotlin](/projects/duplicate-character-counter/kotlin) -- [Duplicate Character Counter in Lua](/projects/duplicate-character-counter/lua) -- [Duplicate Character Counter in Mathematica](/projects/duplicate-character-counter/mathematica) -- [Duplicate Character Counter in OCaml](/projects/duplicate-character-counter/ocaml) -- [Duplicate Character Counter in PHP](/projects/duplicate-character-counter/php) -- [Duplicate Character Counter in Pascal](/projects/duplicate-character-counter/pascal) -- [Duplicate Character Counter in PowerShell](/projects/duplicate-character-counter/powershell) -- [Duplicate Character Counter in Python](/projects/duplicate-character-counter/python) -- [Duplicate Character Counter in R](/projects/duplicate-character-counter/r) -- [Duplicate Character Counter in Ruby](/projects/duplicate-character-counter/ruby) -- [Duplicate Character Counter in Rust](/projects/duplicate-character-counter/rust) -- [Duplicate Character Counter in Swift](/projects/duplicate-character-counter/swift) -- [Duplicate Character Counter in TI-BASIC](/projects/duplicate-character-counter/ti-basic) -- [Duplicate Character Counter in Tcl](/projects/duplicate-character-counter/tcl) -- [Duplicate Character Counter in TypeScript](/projects/duplicate-character-counter/typescript) -- [Duplicate Character Counter in V](/projects/duplicate-character-counter/v) -- [Duplicate Character Counter in Visual Basic](/projects/duplicate-character-counter/visual-basic) -- [Duplicate Character Counter in Wren](/projects/duplicate-character-counter/wren) -- [Duplicate Character Counter in m4](/projects/duplicate-character-counter/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/java/index.md b/docs/projects/duplicate-character-counter/java/index.md deleted file mode 100644 index 7fc867c648..0000000000 --- a/docs/projects/duplicate-character-counter/java/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Vipin Yadav -date: 2022-10-03 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- duplicate-character-counter -- java -title: Duplicate Character Counter in Java -title1: Duplicate Character -title2: Counter in Java ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -public class DuplicateCharacterCounter { - public static void error() { - System.out.println("Usage: please provide a string"); - } - - public static void main(String[] args) { - if (args.length <= 0) { - error(); - } else if (args[0].length() == 0) { - error(); - } else { - String inputStr = args[0]; - Map map = new HashMap<>(); - for (Character c : inputStr.toCharArray()) { - map.put(c, map.getOrDefault(c, 0) + 1); - } - boolean flag = false; - for (Character c : inputStr.toCharArray()) { - if (map.get(c) > 1) { - flag = true; - System.out.printf("%c: %d\n", c, map.get(c)); - map.put(c, 0); - } - } - if (flag == false) { - System.out.println("No duplicate characters"); - } - } - } -} -``` - -{% endraw %} - -Duplicate Character Counter in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/javascript/index.md b/docs/projects/duplicate-character-counter/javascript/index.md deleted file mode 100644 index 690da2bfc8..0000000000 --- a/docs/projects/duplicate-character-counter/javascript/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- duplicate-character-counter -- javascript -title: Duplicate Character Counter in JavaScript -title1: Duplicate Character -title2: Counter in JavaScript ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -"use strict"; - -const USAGE = "Usage: please provide a string"; - -const isAlphaNum = (c) => /^[a-z0-9]$/i.test(c); - -const countDuplicates = (str) => { - const counts = new Map(); - - for (const ch of str) { - if (isAlphaNum(ch)) { - counts.set(ch, (counts.get(ch) ?? 0) + 1); - } - } - - const duplicates = []; - - for (const [ch, count] of counts) { - if (count > 1) { - duplicates.push(`${ch}: ${count}`); - } - } - - return duplicates.length > 0 - ? duplicates.join("\n") - : "No duplicate characters"; -}; - -const run = () => { - const [, , input] = process.argv; - - if (!input) { - console.error(USAGE); - process.exit(1); - } - - console.log(countDuplicates(input)); -}; - -run(); - -``` - -{% endraw %} - -Duplicate Character Counter in [JavaScript](/languages/javascript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/kotlin/index.md b/docs/projects/duplicate-character-counter/kotlin/index.md deleted file mode 100644 index 7aa2a1c449..0000000000 --- a/docs/projects/duplicate-character-counter/kotlin/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2025-10-07 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-10-07 -layout: default -tags: -- duplicate-character-counter -- kotlin -title: Duplicate Character Counter in Kotlin -title1: Duplicate Character -title2: Counter in Kotlin ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -import kotlin.system.exitProcess - -fun main(args: Array) { - val phrase: String = errorChecking(args) - val counts = duplicateCharacterCount(phrase) - outputMap(counts) -} - -fun usageError() { - println("Usage: please provide a string") -} - -fun errorChecking(args: Array): String { - if (args.size == 0 || args[0] == "") { - usageError() - exitProcess(1) - } - return args[0] -} - -fun duplicateCharacterCount(phrase: String): Map { - val counts: Map = phrase.groupingBy { it }.eachCount() - return counts.filter { it.value > 1 } -} - -fun outputMap(counts: Map) { - if (counts.size > 0) { - for (pair in counts) { - println("${pair.key}: ${pair.value}") - } - } else { - println("No duplicate characters") - } -} - -``` - -{% endraw %} - -Duplicate Character Counter in [Kotlin](/languages/kotlin) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/lua/index.md b/docs/projects/duplicate-character-counter/lua/index.md deleted file mode 100644 index 38e3184674..0000000000 --- a/docs/projects/duplicate-character-counter/lua/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- abdirashidexe -date: 2025-02-18 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-02-18 -layout: default -tags: -- duplicate-character-counter -- lua -title: Duplicate Character Counter in Lua -title1: Duplicate Character -title2: Counter in Lua ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -function duplicateCharacterCounter(word) - local hasDuplicates = false; - - -- Empty or no input validation - if word == "" or word == nil then - print("Usage: please provide a string") - return - - -- Check for duplicates validation - elseif (string.len(word) >= 1) then - local myTable = {} - local duplicateList = {} - - for i=1, string.len(word) do - local char = string.sub(word, i, i) - if (myTable[char]) then - myTable[char] = myTable[char]+1 - hasDuplicates = true - - else - myTable[char] = 1; - table.insert(duplicateList, char) - end - end - for _, char in ipairs(duplicateList) do - if myTable[char] > 1 then - print(char .. ": " .. myTable[char]) - end - end - end - - -- No duplicates validation - if not (hasDuplicates) then - print("No duplicate characters") - end -end - -duplicateCharacterCounter(arg[1]) -``` - -{% endraw %} - -Duplicate Character Counter in [Lua](/languages/lua) was written by: - -- abdirashidexe - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/m4/index.md b/docs/projects/duplicate-character-counter/m4/index.md deleted file mode 100644 index f52e52f21d..0000000000 --- a/docs/projects/duplicate-character-counter/m4/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-18 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-08-18 -layout: default -tags: -- duplicate-character-counter -- m4 -title: Duplicate Character Counter in m4 -title1: Duplicate Character -title2: Counter in m4 ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a string -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl count_duplicate_chars(str, var_name) -dnl foreach character in str (ch): -dnl if ch not in var_name: -dnl var_name[ch] = 1 -dnl else: -dnl var_name[ch] = var_name[ch] + 1 -define(`count_duplicate_chars', -`ifelse(eval(len(`$1') > 0), 1, -`define(`ch', substr(`$1', 0, 1))dnl -array_set(`$2', ch, eval(array_get(`$2', ch) + 1))dnl -count_duplicate_chars(substr(`$1', 1), `$2')'dnl -)'dnl -) - -dnl show_duplicate_char_counts(str, var_name) -define(`show_duplicate_char_counts', `_show_duplicate_char_counts(`$1', `$2', `')') - -dnl _show_duplicate_char_counts(str, var_name, has_dupes, dupe_chars) -dnl foreach characters in str (ch): -dnl if var_name[ch] > 1 and ch not in dupe_chars: -dnl dupe_chars = dupe_chars + ch -dnl Output ch ": " var_name[ch] -dnl if dupe_chars is empty: -dnl Output "No duplicate characters" -define(`_show_duplicate_char_counts', -`ifelse(eval(len(`$1') > 0), 1, -`define(`ch', substr(`$1', 0, 1))dnl -ifelse(eval(array_get(`$2', ch) > 1 && index(`$3', ch) < 0), 1, -`ch: array_get(`$2', ch) -_show_duplicate_char_counts(substr(`$1', 1), `$2', `$3'`'ch)', -`_show_duplicate_char_counts(substr(`$1', 1), `$2', `$3')'dnl -)', -len(`$3'), 0, `No duplicate characters' -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1), 1, `show_usage()')dnl -count_duplicate_chars(ARGV1, `counts')dnl -show_duplicate_char_counts(ARGV1, `counts')dnl - -``` - -{% endraw %} - -Duplicate Character Counter in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/mathematica/index.md b/docs/projects/duplicate-character-counter/mathematica/index.md deleted file mode 100644 index dddc5a0be1..0000000000 --- a/docs/projects/duplicate-character-counter/mathematica/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- duplicate-character-counter -- mathematica -title: Duplicate Character Counter in Mathematica -title1: Duplicate Character -title2: Counter in Mathematica ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The inner function does the work, returning the output as a Mathematica list: *) - -duplicateCharacterCounter = Function[{s}, - Select[ - {First[#], Length[#]} & /@ Gather[Characters[s]], - #[[2]] > 1 &]]; - -(* The outer function performs the output text formatting: *) - -duplicateCharacterCounterMain = s \[Function] - Print[#[[1]], ": ", #[[2]]] & /@ duplicateCharacterCounter[s]; - - -(* Valid Tests *) - -duplicateCharacterCounterMain /@ { - "goodbyeblues", - "abba", - "aAbB" - }; - - -(* Invalid Tests *) - -``` - -{% endraw %} - -Duplicate Character Counter in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/ocaml/index.md b/docs/projects/duplicate-character-counter/ocaml/index.md deleted file mode 100644 index d7b66d6600..0000000000 --- a/docs/projects/duplicate-character-counter/ocaml/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-17 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- duplicate-character-counter -- ocaml -title: Duplicate Character Counter in OCaml -title1: Duplicate Character -title2: Counter in OCaml ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -module CharMap = Map.Make (Char) - -let increment_map (counts, seen) k = - match CharMap.find_opt k counts with - | Some n -> (CharMap.add k (n + 1) counts, seen) - | None -> (CharMap.add k 1 counts, k :: seen) - -let count_chars str = - str |> String.to_seq |> Seq.fold_left increment_map (CharMap.empty, []) - -let dupes str = - let counts, seen = count_chars str in - seen |> List.rev - |> List.filter_map (fun c -> - let count = CharMap.find c counts in - if count > 1 then Some (c, count) else None) - -let print_dupes str = - match dupes str with - | [] -> print_endline "No duplicate characters" - | counts -> - List.iter (fun (c, count) -> Printf.printf "%c: %d\n" c count) counts - -let get_arg argv = - match argv with [| _; "" |] -> None | [| _; str |] -> Some str | _ -> None - -let () = - match get_arg Sys.argv with - | Some str -> print_dupes str - | None -> print_endline "Usage: please provide a string" - -``` - -{% endraw %} - -Duplicate Character Counter in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/pascal/index.md b/docs/projects/duplicate-character-counter/pascal/index.md deleted file mode 100644 index caa88ff557..0000000000 --- a/docs/projects/duplicate-character-counter/pascal/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- duplicate-character-counter -- pascal -title: Duplicate Character Counter in Pascal -title1: Duplicate Character -title2: Counter in Pascal ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program DuplicateCharacterCounter; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - SysUtils; - -type - TCountDictionary = specialize TDictionary; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a string'); - Halt(1); -end; - -function IsAlphanumeric(c: char): boolean; -begin - Result := CharInSet(c, ['0'..'9', 'A'..'Z', 'a'..'z']); -end; - -procedure CountDuplicates(const Str: string); -var - Counts: TCountDictionary; - Outputted: TCountDictionary; - Character: char; - CurrentCount: integer; - HasDuplicates: boolean; -begin - Counts := TCountDictionary.Create; - Outputted := TCountDictionary.Create; - try - // Count all alphanumeric characters - for Character in Str do - if IsAlphanumeric(Character) then - begin - if not Counts.TryGetValue(Character, CurrentCount) then - Counts.Add(Character, 1) - else - Counts[Character] := CurrentCount + 1; - end; - - HasDuplicates := False; - - // Output duplicates in order of first appearance - for Character in Str do - if Counts.TryGetValue(Character, CurrentCount) and (CurrentCount > 1) and - not Outputted.ContainsKey(Character) then - begin - Writeln(Character, ': ', CurrentCount); - Outputted.Add(Character, 1); - HasDuplicates := True; - end; - - if not HasDuplicates then - Writeln('No duplicate characters'); - finally - Counts.Free; - Outputted.Free; - end; -end; - -var - InputStr: string; -begin - if ParamCount <> 1 then - ShowUsage; - - InputStr := Trim(ParamStr(1)); - if InputStr = '' then - ShowUsage; - - CountDuplicates(InputStr); -end. - - - -``` - -{% endraw %} - -Duplicate Character Counter in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/php/index.md b/docs/projects/duplicate-character-counter/php/index.md deleted file mode 100644 index 5140971a33..0000000000 --- a/docs/projects/duplicate-character-counter/php/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-22 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- duplicate-character-counter -- php -title: Duplicate Character Counter in PHP -title1: Duplicate Character -title2: Counter in PHP ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - $count) - { - if ($count > 1) - { - echo "$char: $count\n"; - $has_dupes = TRUE; - } - } - - // Indicate if no duplicates found - if (!$has_dupes) - { - echo "No duplicate characters\n"; - } -} - -// Get 1st argument. Exit if too few arguments or empty argument -if (count($argv) < 2 || empty($argv[1])) -{ - usage(); -} - -// Count duplicate characters -$str = $argv[1]; -$counts = duplicate_character_counter($str); - -// Show all duplicate character counts in order in which they occurred in string (if any) -show_duplicate_character_counts($counts); - -``` - -{% endraw %} - -Duplicate Character Counter in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/powershell/index.md b/docs/projects/duplicate-character-counter/powershell/index.md deleted file mode 100644 index 2aadfc9aae..0000000000 --- a/docs/projects/duplicate-character-counter/powershell/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-05-20 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-05-20 -layout: default -tags: -- duplicate-character-counter -- powershell -title: Duplicate Character Counter in PowerShell -title1: Duplicate Character -title2: Counter in PowerShell ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide a string" - Exit 1 -} - -function Get-DuplicateCharacterCounter([string]$Str) { - $Counts = @{} - $Str.ToCharArray() | ForEach-Object { $Counts[$_] += 1 } - $Counts -} - -function Show-DuplicateCharacterCounter([string]$Str, [object]$Counts) { - $Dupes = $false - $Str.ToCharArray() | Select-Object -Unique | ForEach-Object { - if ($Counts[$_] -gt 1) { - Write-Host "${_}: $($Counts[$_])" - $Dupes = $true - } - } - - if (-not $Dupes) { - Write-Host "No duplicate characters" - } -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -$Str = $args[0] -$Counts = Get-DuplicateCharacterCounter $Str -Show-DuplicateCharacterCounter $Str $Counts - -``` - -{% endraw %} - -Duplicate Character Counter in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/python/index.md b/docs/projects/duplicate-character-counter/python/index.md deleted file mode 100644 index e18e1bf89e..0000000000 --- a/docs/projects/duplicate-character-counter/python/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2022-05-14 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2022-05-14 -layout: default -tags: -- duplicate-character-counter -- python -title: Duplicate Character Counter in Python -title1: Duplicate Character -title2: Counter in Python ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - -if len(sys.argv) != 2 or not sys.argv[1]: - print("Usage: please provide a string") - sys.exit() - -counter = dict() -dupes = False -for char in sys.argv[1]: - counter.setdefault(char, 0) - counter[char] += 1 - if counter[char] > 1: - dupes = True - -if dupes: - for key, value in counter.items(): - if value > 1: - print(f"{key}: {value}") -else: - print("No duplicate characters") - -``` - -{% endraw %} - -Duplicate Character Counter in [Python](/languages/python) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/r/index.md b/docs/projects/duplicate-character-counter/r/index.md deleted file mode 100644 index 0788c61de9..0000000000 --- a/docs/projects/duplicate-character-counter/r/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- duplicate-character-counter -- r -title: Duplicate Character Counter in R -title1: Duplicate Character -title2: Counter in R ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -args <- commandArgs(trailingOnly = TRUE) - -USAGE <- "Usage: please provide a string" - -if (length(args) != 1 || !nzchar(x <- args[[1]])) { - cat(USAGE, "\n") - quit(status = 1) -} - -chars <- strsplit(x, "")[[1]] -chars <- chars[grepl("[[:alnum:]]", chars)] - -if (!length(chars)) { - cat("No duplicate characters\n") - quit(status = 0) -} - -counts <- table(chars) - -dups <- counts[counts > 1] -dups <- dups[order(match(names(dups), chars))] - -if (!length(dups)) { - cat("No duplicate characters\n") -} else { - cat(paste(names(dups), dups, sep = ": "), sep = "\n") -} -``` - -{% endraw %} - -Duplicate Character Counter in [R](/languages/r) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/ruby/index.md b/docs/projects/duplicate-character-counter/ruby/index.md deleted file mode 100644 index 5a5e8f72c0..0000000000 --- a/docs/projects/duplicate-character-counter/ruby/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- MSJ -- Ștefan-Iulian Alecu -date: 2024-10-31 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- duplicate-character-counter -- ruby -title: Duplicate Character Counter in Ruby -title1: Duplicate Character -title2: Counter in Ruby ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -input = ARGV.first.to_s - -abort("Usage: please provide a string") if input.empty? - -duplicates = input.each_char.tally.select { _2 > 1 } - -if duplicates.empty? - puts "No duplicate characters" - return -end - -duplicates.each { |char, count| puts "#{char}: #{count}" } - -``` - -{% endraw %} - -Duplicate Character Counter in [Ruby](/languages/ruby) was written by: - -- MSJ -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/rust/index.md b/docs/projects/duplicate-character-counter/rust/index.md deleted file mode 100644 index 966ddd08c4..0000000000 --- a/docs/projects/duplicate-character-counter/rust/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-09 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- duplicate-character-counter -- rust -title: Duplicate Character Counter in Rust -title1: Duplicate Character -title2: Counter in Rust ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::collections::{HashMap, HashSet}; - -fn usage() -> ! { - println!("Usage: please provide a string"); - exit(0); -} - -fn duplicate_character_counter(s: &str) -> HashMap { - let mut counts: HashMap = HashMap::new(); - - // Count number of occurances of each character - for c in s.chars() { - *counts.entry(c).or_insert(0) += 1; - } - - counts -} - -fn show_duplicate_character_counts( - s: &str, counts: &HashMap -) { - // Show characters that have duplicates and keep track of - // which duplicate characters are found - let mut visited: HashSet = HashSet::new(); - for c in s.chars() { - let count: usize = *counts.get(&c).unwrap(); - if count > 1 && !visited.contains(&c) { - println!("{c}: {count}"); - visited.insert(c); - } - } - - // Indicate if no duplicates found - if visited.len() < 1 { - println!("No duplicate characters"); - } -} - -fn main() { - let mut args = args().skip(1); - - // Get 1st command-line argument. Error if empty - let s: &str = &args - .next() - .unwrap_or_else(|| usage()); - if s.len() < 1 { - usage(); - } - - // Count duplicate characters and show results - let counts: HashMap = duplicate_character_counter(&s); - show_duplicate_character_counts(&s, &counts); -} - -``` - -{% endraw %} - -Duplicate Character Counter in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/swift/index.md b/docs/projects/duplicate-character-counter/swift/index.md deleted file mode 100644 index ce4d622b4d..0000000000 --- a/docs/projects/duplicate-character-counter/swift/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Lizock -date: 2024-11-12 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2024-11-12 -layout: default -tags: -- duplicate-character-counter -- swift -title: Duplicate Character Counter in Swift -title1: Duplicate Character -title2: Counter in Swift ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -func error() { - print("Usage: please provide a string") -} - -func duplicateCharacterCounter(string: [String]) { - if string.isEmpty || string[0].isEmpty { - error() - } else { - let input = string[0] - var dict = [Character: Int]() - - for char in input{ - dict[char, default: 0] += 1 - } - - var flag = false - for char in input{ - if let count = dict[char], count > 1 { - flag = true - print("\(char): \(count)") - dict[char] = 0 - } - } - if !flag { - print("No duplicate characters") - } - } -} - -let string = CommandLine.arguments.dropFirst().map { String($0) } -duplicateCharacterCounter(string: Array(string)) -``` - -{% endraw %} - -Duplicate Character Counter in [Swift](/languages/swift) was written by: - -- Lizock - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/tcl/index.md b/docs/projects/duplicate-character-counter/tcl/index.md deleted file mode 100644 index ef7b6cf11e..0000000000 --- a/docs/projects/duplicate-character-counter/tcl/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-10-08 -layout: default -tags: -- duplicate-character-counter -- tcl -title: Duplicate Character Counter in Tcl -title1: Duplicate Character -title2: Counter in Tcl ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr "Usage: please provide a string" - exit 1 -} - -proc countDuplicates {str} { - set counts [dict create] - set order {} - - foreach ch [split $str {}] { - if {[string is alnum -strict $ch]} { - if {![dict exists $counts $ch]} { - lappend order $ch - } - dict incr counts $ch 1 - } - } - - set printed 0 - - foreach ch $order { - set count [dict get $counts $ch] - if {$count > 1} { - puts "$ch: $count" - incr printed - } - } - - if {$printed == 0} { - puts "No duplicate characters" - } -} - -if {$argc != 1} { usage } - -set input [string trim [lindex $argv 0]] -if {$input eq ""} { usage } - -countDuplicates $input - - -``` - -{% endraw %} - -Duplicate Character Counter in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/ti-basic/index.md b/docs/projects/duplicate-character-counter/ti-basic/index.md deleted file mode 100644 index 052c54d5a0..0000000000 --- a/docs/projects/duplicate-character-counter/ti-basic/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-03 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-02-03 -layout: default -tags: -- duplicate-character-counter -- ti-basic -title: Duplicate Character Counter in TI-BASIC -title1: Duplicate Character -title2: Counter in TI-BASIC ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -length(Str1)->L -If L<1 Then Disp "Usage: please provide a string" -Else - {}->l1 - ""->Str2 - 0->M - For(N,1,L) - sub(Str1,N,1)->C - inString(Str2,C)->K - If K<1 - Then - Str2+C->Str2 - M+1->M - M->dim(l1) - 1->l1(M) - Else - l1(K)+1->l1(K) - End - End - 0->D - For(N,1,M) - If l1(N)>1 - Then - Disp sub(Str2,N,1)+": "+toString(l1(N)) - 1->D - End - End - If D=0 - Then Disp "No duplicate characters" - End -End - -``` - -{% endraw %} - -Duplicate Character Counter in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/typescript/index.md b/docs/projects/duplicate-character-counter/typescript/index.md deleted file mode 100644 index 9e1a9cf608..0000000000 --- a/docs/projects/duplicate-character-counter/typescript/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2023-10-02 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2023-10-02 -layout: default -tags: -- duplicate-character-counter -- typescript -title: Duplicate Character Counter in TypeScript -title1: Duplicate Character -title2: Counter in TypeScript ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -const error_msg: string = "Usage: please provide a string" -let str: string = (process.argv.length == 3) ? process.argv[2] : ""; -if (str.length == 0) { - console.log(error_msg); - process.exit(1); -} - -let hash_map: Map = new Map(); -for (let i = 0; i < str.length; i++) { - let char: string = str[i]; - let count: number = hash_map.get(char) || 0; - hash_map.set(char, count + 1); -} -let has_duplicate: boolean = false; -hash_map.forEach((value, key) => { - if (value > 1) { - has_duplicate = true; - console.log(`${key}: ${value}`); - } -}); - -if (!has_duplicate) { - console.log("No duplicate characters"); -} - -``` - -{% endraw %} - -Duplicate Character Counter in [TypeScript](/languages/typescript) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/v/index.md b/docs/projects/duplicate-character-counter/v/index.md deleted file mode 100644 index 4cbab479d3..0000000000 --- a/docs/projects/duplicate-character-counter/v/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Azeb-S -date: 2025-10-30 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-10-30 -layout: default -tags: -- duplicate-character-counter -- v -title: Duplicate Character Counter in V -title1: Duplicate Character -title2: Counter in V ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [V](/languages/v) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```v -import os - -fn show_error() { - println('Usage: please provide a string') -} - -fn main() { - args := os.args[1..] // skip program name - if args.len == 0 { - show_error() - return - } - input_str := args[0] - if input_str.len == 0 { - show_error() - return - } - - mut counts := map[rune]int{} - for c in input_str.runes() { - counts[c]++ - } - - mut found := false - for c in input_str.runes() { - if counts[c] > 1 { - println('${c.str()}: ${counts[c]}') - counts[c] = 0 // prevent duplicate printing - found = true - } - } - - if !found { - println('No duplicate characters') - } -} - -``` - -{% endraw %} - -Duplicate Character Counter in [V](/languages/v) was written by: - -- Azeb-S - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/visual-basic/index.md b/docs/projects/duplicate-character-counter/visual-basic/index.md deleted file mode 100644 index 676f6abe92..0000000000 --- a/docs/projects/duplicate-character-counter/visual-basic/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- duplicate-character-counter -- visual-basic -title: Duplicate Character Counter in Visual Basic -title1: Duplicate Character -title2: Counter in Visual Basic ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System.Text - -Public Module DuplicateCharacterCounter - - Public Sub Main(args As String()) - - If args.Length = 0 OrElse String.IsNullOrEmpty(args(0)) Then - Console.WriteLine("Usage: please provide a string") - Return - End If - - Dim input As String = args(0) - - Dim countMap As New Dictionary(Of Char, Integer) - - For Each c As Char In input - - If countMap.ContainsKey(c) Then - countMap(c) += 1 - Else - countMap(c) = 1 - End If - - Next - - Dim result As New StringBuilder() - Dim seen As New HashSet(Of Char) - - For Each c As Char In input - - If countMap(c) > 1 AndAlso Not seen.Contains(c) Then - result.AppendLine($"{c}: {countMap(c)}") - seen.Add(c) - End If - - Next - - If result.Length = 0 Then - Console.WriteLine("No duplicate characters") - Else - Console.WriteLine(result.ToString().TrimEnd()) - End If - - End Sub - -End Module -``` - -{% endraw %} - -Duplicate Character Counter in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/duplicate-character-counter/wren/index.md b/docs/projects/duplicate-character-counter/wren/index.md deleted file mode 100644 index 10ce50e655..0000000000 --- a/docs/projects/duplicate-character-counter/wren/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Zia -date: 2025-02-17 -featured-image: duplicate-character-counter-in-every-language.jpg -last-modified: 2025-02-17 -layout: default -tags: -- duplicate-character-counter -- wren -title: Duplicate Character Counter in Wren -title1: Duplicate Character -title2: Counter in Wren ---- - - - -Welcome to the [Duplicate Character Counter](/projects/duplicate-character-counter) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -import "os" for Process - -var args = Process.arguments - -if (args.count != 1 || args[0] == "") { - System.print("Usage: please provide a string") - Fiber.suspend() -} - -var chars = {} -var order = [] -var dupes = false - -for (c in args[0]) { - if (chars[c] == null) { - chars[c] = 0 - } else { - dupes = true - } - - chars[c] = chars[c] + 1 - - var contains = false - for (a in order) { - if (c == a) { - contains = true - break - } - } - - if (!contains) { - order.add(c) - } -} - -if (dupes) { - for (c in order) { - if (chars[c] > 1) { - System.print(c + ": " + chars[c].toString) - } - } -} else { - System.print("No duplicate characters") -} - -``` - -{% endraw %} - -Duplicate Character Counter in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/ada/index.md b/docs/projects/even-odd/ada/index.md deleted file mode 100644 index 75e1630a1d..0000000000 --- a/docs/projects/even-odd/ada/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-10 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-05-10 -layout: default -tags: -- ada -- even-odd -title: Even Odd in Ada -title1: Even Odd -title2: in Ada ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; - -procedure Even_Odd is - - procedure Print_Usage is - begin - Put_Line ("Usage: please input a number"); - end Print_Usage; - -begin - if Argument_Count /= 1 then - Print_Usage; - return; - end if; - - declare - Value : Integer; - begin - Value := Integer'Value (Argument (1)); - Put_Line (if Value rem 2 = 0 then "Even" else "Odd"); - - exception - when Constraint_Error => - Print_Usage; - end; - -end Even_Odd; - -``` - -{% endraw %} - -Even Odd in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/algol60/index.md b/docs/projects/even-odd/algol60/index.md deleted file mode 100644 index 1b37afc00f..0000000000 --- a/docs/projects/even-odd/algol60/index.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-17 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- algol60 -- even-odd -title: Even Odd in ALGOL 60 -title1: Even Odd in -title2: ALGOL 60 ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please input a number\n"); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - null byte maps to 17 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch); - integer result, ch; - begin - boolean valid; - integer s; - - result := 0; - valid := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment Ignore characters until end of argument. Indicate invalid - if not whitespace; - ignoreloop: - if ch != -1 then - begin - if ch != 12 then valid := false; - ch := indigit; - goto ignoreloop - end; - - inValidInteger := valid - end inValidInteger; - - boolean procedure iseven(x); - value x; - integer x; - begin - iseven := (x - 2 * (x % 2)) = 0 - end iseven; - - integer argc, result, ch; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get integer value from 1st argument. Exit if invalid; - if !inValidInteger(result, ch) then usage; - - comment Output "Even" if number is even, "Odd" otherwise; - if iseven(result) then outstring(1, "Even\n") - else outstring(1, "Odd\n") -end - -``` - -{% endraw %} - -Even Odd in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/algol68/index.md b/docs/projects/even-odd/algol68/index.md deleted file mode 100644 index 779dd0ef89..0000000000 --- a/docs/projects/even-odd/algol68/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-21 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- even-odd -title: Even Odd in ALGOL 68 -title1: Even Odd in -title2: ALGOL 68 ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC usage = VOID: printf(($gl$, "Usage: please input a number")); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINT_RESULT result := parse int(s); - -# If invalid or extra characters, exit # -INT n := value OF result; -IF NOT (valid OF result) OR (leftover OF result) /= "" -THEN - usage; - stop -FI; - -printf(($gl$, (n MOD 2 = 0 | "Even" | "Odd"))) - -``` - -{% endraw %} - -Even Odd in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/awk/index.md b/docs/projects/even-odd/awk/index.md deleted file mode 100644 index 81970c5a05..0000000000 --- a/docs/projects/even-odd/awk/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-06 -featured-image: even-odd-in-every-language.jpg -last-modified: 2025-04-06 -layout: default -tags: -- awk -- even-odd -title: Even Odd in AWK -title1: Even Odd -title2: in AWK ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please input a number" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function is_even(n) { - return (n % 2) == 0 -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - result = str_to_number(ARGV[1]) - if (result == "ERROR") { - usage() - } - - print is_even(result) ? "Even" : "Odd" -} - -``` - -{% endraw %} - -Even Odd in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/bash/index.md b/docs/projects/even-odd/bash/index.md deleted file mode 100644 index a656ba56c4..0000000000 --- a/docs/projects/even-odd/bash/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- allievo-sudo -- Jeremy Grifski -date: 2019-10-09 -featured-image: even-odd-in-every-language.jpg -last-modified: 2019-10-29 -layout: default -tags: -- bash -- even-odd -title: Even Odd in Bash -title1: Even Odd -title2: in Bash ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash -count=$1 - -[[ $count =~ ^[-+]?[0-9]+$ ]] || { echo "Usage: please input a number"; exit 1; } - -rem=$(( $count % 2 )) - -if [ $rem -eq 0 ] -then - echo "Even" -else - echo "Odd" -fi - -``` - -{% endraw %} - -Even Odd in [Bash](/languages/bash) was written by: - -- allievo-sudo -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/beef/index.md b/docs/projects/even-odd/beef/index.md deleted file mode 100644 index f2c8aea6b3..0000000000 --- a/docs/projects/even-odd/beef/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-14 -featured-image: even-odd-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- even-odd -title: Even Odd in Beef -title1: Even Odd -title2: in Beef ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace EvenOdd; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please input a number"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - switch (ParseInt(args[0])) - { - case .Ok(let val): - Console.WriteLine((val % 2 == 0) ? "Even" : "Odd"); - case .Err: - Usage(); - } - - return 0; - } -} - -``` - -{% endraw %} - -Even Odd in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/c-plus-plus/index.md b/docs/projects/even-odd/c-plus-plus/index.md deleted file mode 100644 index 4cc5d017fe..0000000000 --- a/docs/projects/even-odd/c-plus-plus/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Grifski -- killbotxd -- Ștefan-Iulian Alecu -date: 2019-10-09 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- even-odd -title: Even Odd in C++ -title1: Even Odd -title2: in C++ ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cout << "Usage: please input a number\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - s = trim(s); - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - const auto input_opt = to_int(argv[1]); - if (!input_opt) usage(); - - const int input = *input_opt; - - std::cout << ((input % 2 == 0) ? "Even" : "Odd") << '\n'; -} -``` - -{% endraw %} - -Even Odd in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- killbotxd -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/c-sharp/index.md b/docs/projects/even-odd/c-sharp/index.md deleted file mode 100644 index 22f2e28cf5..0000000000 --- a/docs/projects/even-odd/c-sharp/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-28 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- even-odd -title: Even Odd in C# -title1: Even Odd -title2: in C# ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var input] || !int.TryParse(input, out int n)) -{ - Console.Error.WriteLine("Usage: please input a number"); - return; -} - -Console.WriteLine(n % 2 == 0 ? "Even" : "Odd"); -``` - -{% endraw %} - -Even Odd in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/c/index.md b/docs/projects/even-odd/c/index.md deleted file mode 100644 index ba0193d3bb..0000000000 --- a/docs/projects/even-odd/c/index.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -authors: -- AceKnight -- Jeremy Grifski -- rzuckerm -- shubhragupta-code -- Ștefan-Iulian Alecu -date: 2018-10-21 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- even-odd -title: Even Odd in C -title1: Even Odd -title2: in C ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -int main(int argc, char **argv) -{ - if (argc == 1 - || argv[1][0] == '\0' - || (atoi(argv[1]) == 0 && strcmp(argv[1], "0") != 0)) - { - printf("Usage: please input a number\n"); - } - else - { - int input = atoi(argv[1]); - if (input % 2 == 0) - printf("Even\n"); - else - printf("Odd\n"); - } - - return 0; -} - -``` - -{% endraw %} - -Even Odd in [C](/languages/c) was written by: - -- AceKnight -- Jeremy Grifski -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Apr 15 2026 00:50:56. The solution was first committed on Oct 21 2018 19:46:02. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Let's understand this code block by block. - -### Main Function -```c -#include -#include -#include - -int main(int argc, char **argv) { -``` -In the first three lines, we are including header files using [include directive][1] to utilise some functions defined in header files later in the program. -Here, Standard Input/Output header file (``) is called to use **printf()** function, C Standard Library (``) to use **atoi()** function and `` to use **strcmp()** function. - -In C, we declare a function using general form: -``` -return_type function_name(parameter){ - ... -} -``` -So, we are declaring main function with return_type integer and **argc** and **argv** as parameters to access command line arguments. -**argc** and **argv** are variables which main function will get when run in command-line. **argc** stores argument count while **argv** stores array of strings that are arguments. This should be kept in mind that all command-line arguments are stored as strings. - -**argv[0]** represents first argument which always is equal to name of our program. If we type the following command in terminal: -```console -./even-odd 2 -``` -Here, `./even-odd` represents **argv[0]** and `2` represents **argv[1]**. - -### Control Flow -Before we move onto the control flow, let's look on the functions which we called from header files. -**[atoi()][2]** converts argument string into an integer. **[strcmp()][3]** compares two strings and **[printf()][4]** prints formatted string as output. -For the if-else statements, first if condition checks if the argument count is 1 or if the argument provided is only a null string or if the argument is equal to 0(integer). For that it prints correct usage pattern. -Otherwise the value of **argv[1]** is converted into integer and stored in variable *input*. `%` represents modulo operator which gives remainder for integer division. So, in case of `input % 2`, 0 as remainder shows that *input* is divisible by 2 and non zero remainder shows indivisibility. Thus, prints *Even* or *Odd* depending on *input* for the next if statement. -Return value is called exit code. So, 0 as exit code represents zero error. - -[1]: https://en.wikipedia.org/wiki/Include_directive -[2]: https://man7.org/linux/man-pages/man3/atoi.3.html -[3]: https://man7.org/linux/man-pages/man3/strcmp.3.html -[4]: https://man7.org/linux/man-pages/man3/printf.3.html - - -## How to Run the Solution - -```console -gcc -o even-odd even-odd.c -./even-odd -``` -Another handy option is to compile and run using online C Compiler such as [OnlineGDB][5], [Repl][6] - -[5]: https://www.onlinegdb.com/ -[6]: https://replit.com/languages/c diff --git a/docs/projects/even-odd/cobol/index.md b/docs/projects/even-odd/cobol/index.md deleted file mode 100644 index 597c9b1906..0000000000 --- a/docs/projects/even-odd/cobol/index.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- ShivaniThevar -- Ștefan-Iulian Alecu -date: 2021-10-17 -featured-image: even-odd-in-cobol.jpg -last-modified: 2026-04-18 -layout: default -tags: -- cobol -- even-odd -title: Even Odd in COBOL -title1: Even Odd -title2: in COBOL ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. even-odd. - -data division. -working-storage section. - -01 cmdargs pic x(38). -01 num pic s9(30). - -procedure division. - -main. - accept cmdargs from command-line - - if function test-numval(cmdargs) not = 0 - display "Usage: please input a number" - stop run - end-if - - compute num = function numval(cmdargs) - - if function mod(num 2) = 0 - display "Even" - else - display "Odd" - end-if - - stop run. - -``` - -{% endraw %} - -Even Odd in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- ShivaniThevar - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let us try to understand the code step-wise. - -First, we must make sure we include the mandatory `DIVISIONS` in the beginning. The `IDENTIFICATION DIVISION` is used to specify the metadata of the program including the `PROGRAM-ID`. In this case, we have written `EVEN-ODD` to identify the code. - -Next comes the `DATA DIVISION`. Here, we define our data variables, which will contain data like integer, alphabets etc. Here, we have mentioned `CMDARGS` and `NUM` which are short for Command Arguments and Number respectively. `PIC` stands for 'Picture Clause' which defines the type and size of data. `X` means an Alpha-numeric data can be expected in Command Arguments (maximum size is 38 bytes). We have used alphanumeric because the user can also enter alphabets instead of a number. On the other hand, `S9` shows that a number with positive or negative values can be expected as data (maximum size is 30 bytes). - -Moving on, we encounter `PROCEDURE DIVISION`. This section includes the actual code with its functions. To solve this problem, we will use a computing operator 'Modulo' (%) which divides one number from the other and returns the remainder. So, if we divide any even number with 2, the remainder will always be 0, whereas, if we divide any odd number with 2, the remainder would be 1. - -For example, 12 % 2 = 0 and 13 % 2 = 1. - -`ACCEPT` is a keyword used to accept arguments (data) from the Command-Line. So, this statement is used to accept the data entered by the user and run it through the code. - -If command arguments are alphabetic, the program will display the error message `Usage: please input a number` and stop the program. - -`NUMVAL` extracts numeric data from an alphanumeric data and stores them. - -Next, we have nested (one inside the other) IF conditions. `IF NUM IS NUMERIC THEN` is used to make sure again that we are only using a numeric data to print an output. So, if the data entered is a number, the program will go ahead with this condition and the `MOD` (modulo) operator will be applied on the number. - -`MOD (NUM, 2) = 0 THEN DISPLAY "Even"`. If the remainder is 0, then the number is even and so is the output. - -If this condition is not true, i.e., if the remainder is not 0, the output will be `"Odd"`. - -And finally, if the data is not a number, the output will be an error message "Usage: please input a number". - - -## How to Run the Solution - -To run the solution we will need [a COBOL compiler](https://gnucobol.sourceforge.io/) installed and [the actual code file](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/c/cobol/even-odd.cbl). -Finally we need to run these commands in order: - -```console -cobc -x even-odd.cbl -$ ./even-odd -``` -The commands first compile the source code into an executable and then execute it. -Alternatively, you might want to use an [online COBOL compiler](https://www.jdoodle.com/execute-cobol-online/) diff --git a/docs/projects/even-odd/coffeescript/index.md b/docs/projects/even-odd/coffeescript/index.md deleted file mode 100644 index 8aaed42631..0000000000 --- a/docs/projects/even-odd/coffeescript/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Sayantan Sarkar -date: 2020-10-09 -featured-image: even-odd-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- coffeescript -- even-odd -title: Even Odd in CoffeeScript -title1: Even Odd in -title2: CoffeeScript ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -USAGE = "Usage: please input a number" -main = (arg) -> - numberParsed = parseInt(arg) - isNumber = Number.isInteger(numberParsed) - if isNumber - if numberParsed % 2 == 0 then "Even" else "Odd" - else - USAGE - -console.log main(process.argv[2]) -``` - -{% endraw %} - -Even Odd in [CoffeeScript](/languages/coffeescript) was written by: - -- Sayantan Sarkar - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/commodore-basic/index.md b/docs/projects/even-odd/commodore-basic/index.md deleted file mode 100644 index dbea32cdaa..0000000000 --- a/docs/projects/even-odd/commodore-basic/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- even-odd -title: Even Odd in Commodore BASIC -title1: Even Odd in -title2: Commodore BASIC ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input N -10 GOSUB 1000 -20 IF V = 0 OR C >=0 THEN GOTO 80: REM invalid or not end character -30 N = NR -40 R$ = "Odd" -50 IF N - INT(N / 2) * 2 = 0 THEN R$ = "Even" -60 PRINT R$ -70 END -80 PRINT "Usage: please input a number" -90 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN - -``` - -{% endraw %} - -Even Odd in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/dart/index.md b/docs/projects/even-odd/dart/index.md deleted file mode 100644 index 8891c896e0..0000000000 --- a/docs/projects/even-odd/dart/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-10-18 -featured-image: even-odd-in-every-language.jpg -last-modified: 2019-10-18 -layout: default -tags: -- dart -- even-odd -title: Even Odd in Dart -title1: Even Odd -title2: in Dart ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -void main(List args) { - try{ - (int.parse(args[0])%2 == 0)?print("Even"):print("Odd"); - } - catch(e){ - print("Usage: please input a number"); - } -} - - - -``` - -{% endraw %} - -Even Odd in [Dart](/languages/dart) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/elixir/index.md b/docs/projects/even-odd/elixir/index.md deleted file mode 100644 index 7a208a5ab1..0000000000 --- a/docs/projects/even-odd/elixir/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Zapnuk -date: 2020-10-03 -featured-image: even-odd-in-every-language.jpg -last-modified: 2020-10-04 -layout: default -tags: -- elixir -- even-odd -title: Even Odd in Elixir -title1: Even Odd -title2: in Elixir ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Elixir](/languages/elixir) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elixir -defmodule EvenOdd do - require Integer - - @doc """ - Determine whether a supplied number is Even or Odd. - Return an error-string if the argument is missing or invalid. - """ - @spec main(argv :: list( String.t())) :: String.t() - def main(argv) do - if length(argv) != 1 do - "Usage: please input a number" - else - case argv |> List.first |> Integer.parse do - {number, ""} -> even_odd_string(number) - {_, _rest} -> "Usage: please input a number" - :error -> "Usage: please input a number" - end - end - end - - @spec even_odd_string(number :: integer) :: String.t() - defp even_odd_string(number) do - case Integer.is_even(number) do - true -> "Even" - false -> "Odd" - end - end -end - -EvenOdd.main(System.argv()) |> IO.puts -``` - -{% endraw %} - -Even Odd in [Elixir](/languages/elixir) was written by: - -- Zapnuk - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/elvish/index.md b/docs/projects/even-odd/elvish/index.md deleted file mode 100644 index cd9b5c7f16..0000000000 --- a/docs/projects/even-odd/elvish/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-07 -featured-image: even-odd-in-every-language.jpg -last-modified: 2025-01-07 -layout: default -tags: -- elvish -- even-odd -title: Even Odd in Elvish -title1: Even Odd -title2: in Elvish ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -use re - -if (> 1 (count $args)) { - echo "Usage: please input a number" - exit 1 -} - -if (not (re:match '^[+-]?[0-9]+(\.[0-9]+)?$' $args[0])) { - echo "Usage: please input a number" - exit 1 -} - -if (== 0 (% $args[0] 2)) { - echo Even -} else { - echo Odd -} - -``` - -{% endraw %} - -Even Odd in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/euphoria/index.md b/docs/projects/even-odd/euphoria/index.md deleted file mode 100644 index 1d9ad6c03a..0000000000 --- a/docs/projects/even-odd/euphoria/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- even-odd -title: Even Odd in Euphoria -title1: Even Odd in -title2: Euphoria ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/math.e -include std/utils.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - -procedure usage() - puts(STDOUT, "Usage: please input a number\n") - abort(0) -end procedure - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int(argv[4]) -integer value = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] -then - usage() -end if - --- Indicate whether even or odd -puts(STDOUT, iif(is_even(value), "Even\n", "Odd\n")) - -``` - -{% endraw %} - -Even Odd in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/f-sharp/index.md b/docs/projects/even-odd/f-sharp/index.md deleted file mode 100644 index ecbf85c31e..0000000000 --- a/docs/projects/even-odd/f-sharp/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- even-odd -- f-sharp -title: Even Odd in F# -title1: Even Odd -title2: in F# ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -let usage = "Usage: please input a number" - -module EvenOdd = - let run n = if n % 2 = 0 then "Even" else "Odd" - -module Helpers = - let (|Int|_|) (s: string) = - match s.Trim() |> Int32.TryParse with - | true, n -> Some n - | false, _ -> None - - let parseArgs argv = - match argv with - | [| Int n |] -> Ok n - | _ -> Error usage - - let handleResults = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map EvenOdd.run - |> Helpers.handleResults -``` - -{% endraw %} - -Even Odd in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/fortran/index.md b/docs/projects/even-odd/fortran/index.md deleted file mode 100644 index 4ed836cf25..0000000000 --- a/docs/projects/even-odd/fortran/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- Ștefan-Iulian Alecu -date: 2020-10-29 -featured-image: even-odd-in-every-language.jpg -last-modified: 2025-10-15 -layout: default -tags: -- even-odd -- fortran -title: Even Odd in Fortran -title1: Even Odd -title2: in Fortran ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program evenodd - implicit none - character(len=12) :: arg - character(len=52) :: letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - integer :: number, ios, argc - - argc = command_argument_count() - if (argc /= 1) call usage() - - call get_command_argument(1, arg) - if (len_trim(arg) == 0) call usage() - if (scan(arg, letters) > 0) call usage() - - read(arg, *, iostat=ios) number - if (ios /= 0) call usage() - - if (mod(number,2) == 0) then - write(*,*) "Even" - else - write(*,*) "Odd" - end if - -contains - - subroutine usage() - write(*,*) "Usage: please input a number" - stop - end subroutine - -end program evenodd - -``` - -{% endraw %} - -Even Odd in [Fortran](/languages/fortran) was written by: - -- Mallikarjuna S J -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/gnu-make/index.md b/docs/projects/even-odd/gnu-make/index.md deleted file mode 100644 index eacf58bc8d..0000000000 --- a/docs/projects/even-odd/gnu-make/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-05 -featured-image: even-odd-in-every-language.jpg -last-modified: 2025-10-05 -layout: default -tags: -- even-odd -- gnu-make -title: Even Odd in GNU Make -title1: Even Odd in -title2: GNU Make ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -USAGE := Usage: please input a number - -# Numbers are represented as x's so that they can be manipulated with text functions. -# This idea is based on how the GNU Make Standard Library (https://github.com/jgrahamc/gmsl) -# handles numbers. -X0 := -X1 := x - -# Constants -NUMBERS := 0 1 2 3 4 5 6 7 8 9 -EVEN_NUMBERS := 0 2 4 6 8 - -# Get rest of words in a list -# Arg 1: The list -# Return: List with first word removed -REST = $(wordlist 2,$(words $(1)),$(1)) - -# Repeatedly apply a function -# Arg 1: Name of function. This function must take two arguments: -# - Function Arg1: Current value -# - Function Arg2: New value -# Arg 2: The list to repeated apply the function to -# Arg 3: Initial value -_REDUCE = $(if $(4),$(call _REDUCE,$(1),$(call $(1),$(2),$(3)),$(firstword $(4)),$(call REST,$(4))),$(call $(1),$(2),$(3))) -REDUCE = $(call _REDUCE,$(1),$(3),$(firstword $(2)),$(call REST,$(2))) - -# Split number into individual digits -# Arg 1: Number to split -# Return: Number split into individual digits -_SUBST_SPACE = $(subst $(2), $(2),$(1)) -SPLIT_NUMBER = $(strip $(call REDUCE,_SUBST_SPACE,$(NUMBERS),$(1))) - -# Indicate if valid number -# Arg 1: Number -# Return: $(X1) if valid number, $(X0) otherwise -IS_VALID_NUMBER = $(if $(strip $(1)),$(if $(filter-out $(NUMBERS),$(call SPLIT_NUMBER,$(1))),$(X0),$(X1)),$(X0)) - -# Indicate if number is even or odd -# Arg 1: Number -# Return: $(X1) if even, $(X0) otherwise -IS_EVEN = $(if $(filter $(EVEN_NUMBERS),$(lastword $(call SPLIT_NUMBER,$(1)))),$(X1),$(X0)) - -# Remove leading minus sign from input value -ABS_VALUE := $(patsubst -%,%,$(ARGV1)) - -# If invalid number, display usage statement -# Else if indicate if number is even or odd -ifeq (,$(call IS_VALID_NUMBER,$(ABS_VALUE))) -$(info $(USAGE)) -else -$(info $(if $(call IS_EVEN,$(ABS_VALUE)),Even,Odd)) -endif - -.PHONY: -all: ;@: - -``` - -{% endraw %} - -Even Odd in [GNU Make](/languages/gnu-make) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/go/index.md b/docs/projects/even-odd/go/index.md deleted file mode 100644 index dfac3cd013..0000000000 --- a/docs/projects/even-odd/go/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- clarkimusmax -- Parker Johansen -date: 2018-10-25 -featured-image: even-odd-in-every-language.jpg -last-modified: 2019-04-01 -layout: default -tags: -- even-odd -- go -title: Even Odd in Go -title1: Even Odd -title2: in Go ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" -) - -func exitWithError() { - fmt.Println("Usage: please input a number") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - n, err := strconv.Atoi(os.Args[1]) - if err != nil { - exitWithError() - } - - if n%2 == 0 { - fmt.Printf("Even\n") - } else { - fmt.Printf("Odd\n") - } -} - -``` - -{% endraw %} - -Even Odd in [Go](/languages/go) was written by: - -- clarkimusmax -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/groovy/index.md b/docs/projects/even-odd/groovy/index.md deleted file mode 100644 index b934cb4834..0000000000 --- a/docs/projects/even-odd/groovy/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- robin -date: 2019-07-01 -featured-image: even-odd-in-every-language.jpg -last-modified: 2019-07-01 -layout: default -tags: -- even-odd -- groovy -title: Even Odd in Groovy -title1: Even Odd -title2: in Groovy ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -class EvenOdd { - static void main(String... args) { - if(args?.length != 1 || !args[0]?.isInteger()) { - println 'Usage: please input a number' - } else { - println args[0].toInteger() % 2 == 0 ? 'Even' : 'Odd' - } - } -} - -``` - -{% endraw %} - -Even Odd in [Groovy](/languages/groovy) was written by: - -- robin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/haskell/index.md b/docs/projects/even-odd/haskell/index.md deleted file mode 100644 index 2b722463dc..0000000000 --- a/docs/projects/even-odd/haskell/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-11-16 -featured-image: even-odd-in-every-language.jpg -last-modified: 2018-11-16 -layout: default -tags: -- even-odd -- haskell -title: Even Odd in Haskell -title1: Even Odd -title2: in Haskell ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read - -data EvenOdd = Even | Odd deriving (Show) - -isEvenOdd :: Int -> EvenOdd -isEvenOdd x - | x `mod` 2 == 0 = Even - | otherwise = Odd - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - -main :: IO () -main = do - args <- getArgs - let x = headMaybe args - case x >>= readMaybe of - Nothing -> putStrLn "Usage: please input a number" - Just x -> putStrLn $ show $ isEvenOdd x - -``` - -{% endraw %} - -Even Odd in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/index.md b/docs/projects/even-odd/index.md deleted file mode 100644 index 356fc70587..0000000000 --- a/docs/projects/even-odd/index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -date: 2018-10-21 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- even-odd -title: Even Odd -title1: Even -title2: Odd ---- - - - -Welcome to the Even Odd page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -An even number is an integer which is "evenly divisible" by two. This -means that if the integer is divided by 2, it yields no remainder. - -An odd number is an integer which is not evenly divisible by two. This -means that if the integer is divided by 2, it yields a remainder of 1. - - -## Requirements - -Create a file called "Even Odd" using the naming -convention appropriate for your language of choice. - -Write a sample program which accepts an integer on the command line and -outputs if the integer is Even or Odd. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Even Odd. -In order to keep things simple, we split up the testing as follows: - -- Even Odd Valid Tests -- Even Odd Invalid Tests - -### Even Odd Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: Even | "2" | "Even" | -| Sample Input: Odd | "5" | "Odd" | -| Sample Input: Negative Even | "-14" | "Even" | -| Sample Input: Negative Odd | "-27" | "Odd" | - -### Even Odd Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A Number | "a" | - -All of these tests should output the following: - -``` -Usage: please input a number -``` - - -## Articles - -There are 52 articles: - -- [Even Odd in ALGOL 60](/projects/even-odd/algol60) -- [Even Odd in ALGOL 68](/projects/even-odd/algol68) -- [Even Odd in AWK](/projects/even-odd/awk) -- [Even Odd in Ada](/projects/even-odd/ada) -- [Even Odd in Bash](/projects/even-odd/bash) -- [Even Odd in Beef](/projects/even-odd/beef) -- [Even Odd in C](/projects/even-odd/c) -- [Even Odd in C#](/projects/even-odd/c-sharp) -- [Even Odd in C++](/projects/even-odd/c-plus-plus) -- [Even Odd in COBOL](/projects/even-odd/cobol) -- [Even Odd in CoffeeScript](/projects/even-odd/coffeescript) -- [Even Odd in Commodore BASIC](/projects/even-odd/commodore-basic) -- [Even Odd in Dart](/projects/even-odd/dart) -- [Even Odd in Elixir](/projects/even-odd/elixir) -- [Even Odd in Elvish](/projects/even-odd/elvish) -- [Even Odd in Euphoria](/projects/even-odd/euphoria) -- [Even Odd in F#](/projects/even-odd/f-sharp) -- [Even Odd in Fortran](/projects/even-odd/fortran) -- [Even Odd in GNU Make](/projects/even-odd/gnu-make) -- [Even Odd in Go](/projects/even-odd/go) -- [Even Odd in Groovy](/projects/even-odd/groovy) -- [Even Odd in Haskell](/projects/even-odd/haskell) -- [Even Odd in Java](/projects/even-odd/java) -- [Even Odd in JavaScript](/projects/even-odd/javascript) -- [Even Odd in Julia](/projects/even-odd/julia) -- [Even Odd in Kotlin](/projects/even-odd/kotlin) -- [Even Odd in Lisp](/projects/even-odd/lisp) -- [Even Odd in Lua](/projects/even-odd/lua) -- [Even Odd in Mathematica](/projects/even-odd/mathematica) -- [Even Odd in Objective-C](/projects/even-odd/objective-c) -- [Even Odd in Octave](/projects/even-odd/octave) -- [Even Odd in Odin](/projects/even-odd/odin) -- [Even Odd in PHP](/projects/even-odd/php) -- [Even Odd in Pascal](/projects/even-odd/pascal) -- [Even Odd in Perl](/projects/even-odd/perl) -- [Even Odd in PowerShell](/projects/even-odd/powershell) -- [Even Odd in Pyret](/projects/even-odd/pyret) -- [Even Odd in Python](/projects/even-odd/python) -- [Even Odd in R](/projects/even-odd/r) -- [Even Odd in Rexx](/projects/even-odd/rexx) -- [Even Odd in Ruby](/projects/even-odd/ruby) -- [Even Odd in Rust](/projects/even-odd/rust) -- [Even Odd in Scala](/projects/even-odd/scala) -- [Even Odd in Swift](/projects/even-odd/swift) -- [Even Odd in TI-BASIC](/projects/even-odd/ti-basic) -- [Even Odd in Tcl](/projects/even-odd/tcl) -- [Even Odd in TypeScript](/projects/even-odd/typescript) -- [Even Odd in V](/projects/even-odd/v) -- [Even Odd in Visual Basic](/projects/even-odd/visual-basic) -- [Even Odd in Wren](/projects/even-odd/wren) -- [Even Odd in m4](/projects/even-odd/m4) -- [Even Odd in x86-64](/projects/even-odd/x86-64) - -*** - - \ No newline at end of file diff --git a/docs/projects/even-odd/java/index.md b/docs/projects/even-odd/java/index.md deleted file mode 100644 index edf5705410..0000000000 --- a/docs/projects/even-odd/java/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -date: 2018-12-30 -featured-image: even-odd-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- even-odd -- java -title: Even Odd in Java -title1: Even Odd -title2: in Java ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class EvenOdd { - public static void verifyNumber(String n) throws NumberFormatException { - if (n.startsWith("-")) - n = n.substring(1); - char[] nArray = n.toCharArray(); - for (char c : nArray) { - if (!Character.isDigit(c)) - throw new NumberFormatException(); - } - } - - public static void ErrorAndExit() { - System.out.println("Usage: please input a number"); - System.exit(1); - } - - public static void main(String[] args) { - try { - String nstr = args[0].trim(); - verifyNumber(nstr); - String lastDigit = nstr.substring(nstr.length() - 1); - int n = Integer.parseInt(lastDigit); - String result = n % 2 == 0 ? "Even" : "Odd"; - System.out.println(result); - } catch (NumberFormatException | ArrayIndexOutOfBoundsException | StringIndexOutOfBoundsException e) { - ErrorAndExit(); - } - } -} - -``` - -{% endraw %} - -Even Odd in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/javascript/index.md b/docs/projects/even-odd/javascript/index.md deleted file mode 100644 index e82efdae1b..0000000000 --- a/docs/projects/even-odd/javascript/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- Manan Gill -date: 2019-10-11 -featured-image: even-odd-in-every-language.jpg -last-modified: 2019-10-12 -layout: default -tags: -- even-odd -- javascript -title: Even Odd in JavaScript -title1: Even Odd in -title2: JavaScript ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const input = process.argv[2] != '' ? Number(process.argv[2]) : null; //coerce the input into a number, ignore empty string -if(!Number.isInteger(input)){ //if there is no input, input = undefined and the statement still prints - console.log('Usage: please input a number'); -} else { - console.log(input%2 === 0 ? 'Even' : 'Odd'); -} - -``` - -{% endraw %} - -Even Odd in [JavaScript](/languages/javascript) was written by: - -- Manan Gill - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/julia/index.md b/docs/projects/even-odd/julia/index.md deleted file mode 100644 index 230737ca74..0000000000 --- a/docs/projects/even-odd/julia/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- smjalageri -date: 2021-11-01 -featured-image: even-odd-in-every-language.jpg -last-modified: 2021-11-01 -layout: default -tags: -- even-odd -- julia -title: Even Odd in Julia -title1: Even Odd -title2: in Julia ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia - -#!/usr/bin/julia - -function err() - println("Usage: please input a number") -end - -function even_odd(n) - - if (n % 2 == 0 ) - return "Even" - else - return "Odd" - end -end - -try - println(even_odd(parse(Int, ARGS[1]))) -catch e - err() -end - -``` - -{% endraw %} - -Even Odd in [Julia](/languages/julia) was written by: - -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/kotlin/index.md b/docs/projects/even-odd/kotlin/index.md deleted file mode 100644 index 339a119957..0000000000 --- a/docs/projects/even-odd/kotlin/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Blake.Ke -- mikenmo -date: 2020-10-01 -featured-image: even-odd-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- even-odd -- kotlin -title: Even Odd in Kotlin -title1: Even Odd -title2: in Kotlin ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) { - if (args.isNullOrEmpty() || args[0].toIntOrNull() == null) { - println("Usage: please input a number") - return - } - val num = args[0].toInt() - if (num % 2 == 0) { - println("Even") - } else { - println("Odd") - } -} -``` - -{% endraw %} - -Even Odd in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- mikenmo - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/lisp/index.md b/docs/projects/even-odd/lisp/index.md deleted file mode 100644 index 844fee82f9..0000000000 --- a/docs/projects/even-odd/lisp/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2020-10-11 -featured-image: even-odd-in-every-language.jpg -last-modified: 2020-10-11 -layout: default -tags: -- even-odd -- lisp -title: Even Odd in Lisp -title1: Even Odd -title2: in Lisp ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(defun even-odd (x) - (cond - ((evenp x) "Even") - ((oddp x) "Odd"))) - -(defun maybe-int (input) - (cond - ((null input) nil) - ((string= input "") nil) - ((every #'digit-char-p (string-left-trim "-" input)) (parse-integer input)) - (t nil))) - -(defparameter num (maybe-int (cadr *posix-argv*))) -(cond - ((null num) (write-line "Usage: please input a number")) - (t (write-line (even-odd num)))) - -``` - -{% endraw %} - -Even Odd in [Lisp](/languages/lisp) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/lua/index.md b/docs/projects/even-odd/lua/index.md deleted file mode 100644 index 2ef4a239b2..0000000000 --- a/docs/projects/even-odd/lua/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Berry Semexan -date: 2019-10-17 -featured-image: even-odd-in-every-language.jpg -last-modified: 2019-10-17 -layout: default -tags: -- even-odd -- lua -title: Even Odd in Lua -title1: Even Odd -title2: in Lua ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -main = function(input) - usage = "Usage: please input a number" - - if tonumber(input) ~= nil then - if input % 2 == 0 then - print("Even") - else - print("Odd") - end - else - print(usage) - end -end - -main(arg[1]) -``` - -{% endraw %} - -Even Odd in [Lua](/languages/lua) was written by: - -- Berry Semexan - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/m4/index.md b/docs/projects/even-odd/m4/index.md deleted file mode 100644 index ccb7bf153e..0000000000 --- a/docs/projects/even-odd/m4/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-11 -featured-image: even-odd-in-every-language.jpg -last-modified: 2025-08-11 -layout: default -tags: -- even-odd -- m4 -title: Even Odd in m4 -title1: Even Odd -title2: in m4 ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please input a number -m4exit(`1')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl is_even(n) -define(`is_even', `eval($1 % 2 == 0)') -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !is_valid(ARGV1)), 1, `show_usage()', dnl -`ifelse(is_even(ARGV1), 1, `Even', `Odd')') - -``` - -{% endraw %} - -Even Odd in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/mathematica/index.md b/docs/projects/even-odd/mathematica/index.md deleted file mode 100644 index d1955de2ea..0000000000 --- a/docs/projects/even-odd/mathematica/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- even-odd -- mathematica -title: Even Odd in Mathematica -title1: Even Odd in -title2: Mathematica ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The Mathematica built-in EvenQ essentially provides the required behavior; -so the only code needed is the 'user interface' to make it look a little more -like a Unix command-line tool: *) - -evenOddMain = Catch[ - Module[{fromNegativeDigits}, - (* oddly, Mathematica doesn't appear to provide a function which can parse strings representing negative integers *) - fromNegativeDigits = Piecewise[{ - {FromDigits[#], StringMatchQ[#, DigitCharacter ..]}, - {-FromDigits[StringDrop[#, 1]], - StringMatchQ[#, "-" ~~ DigitCharacter ..]}}, - Throw["Usage: please input a number"] - ] &; - If[EvenQ[fromNegativeDigits[#]], "Even", "Odd"]]] &; - - -(* Valid Tests *) - -Print /@ evenOddMain /@ {"2", "5", "-14", "-27"}; - - -(* Invalid Tests *) - -evenOddMain[""] -evenOddMain["a"] -``` - -{% endraw %} - -Even Odd in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/objective-c/index.md b/docs/projects/even-odd/objective-c/index.md deleted file mode 100644 index 7c1655d09b..0000000000 --- a/docs/projects/even-odd/objective-c/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- rzuckerm -- Siddhant -- Ștefan-Iulian Alecu -date: 2020-10-01 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- even-odd -- objective-c -title: Even Odd in Objective-C -title1: Even Odd in -title2: Objective-C ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -@interface NSString (Parsing) -@property(nonatomic, readonly, nullable) NSNumber* strictIntegerNumber; -@end - -@implementation NSString (Parsing) - -- (NSNumber*)strictIntegerNumber { - NSString* trimmed = [self - stringByTrimmingCharactersInSet:NSCharacterSet - .whitespaceAndNewlineCharacterSet]; - if (trimmed.length == 0) return nil; - - NSInteger offset = 0; - if ([trimmed hasPrefix:@"-"] || [trimmed hasPrefix:@"+"]) { - offset = 1; - } - - if (trimmed.length <= offset) return nil; - - NSString* core = [trimmed substringFromIndex:offset]; - NSRange invalidRange = - [core rangeOfCharacterFromSet:NSCharacterSet.decimalDigitCharacterSet - .invertedSet]; - - if (invalidRange.location != NSNotFound) { - return nil; - } - - return @(trimmed.longLongValue); -} - -@end - -int main(int argc, const char* argv[]) { - @autoreleasepool { - if (argc < 2) { - puts("Usage: please input a number"); - return 1; - } - - NSNumber* number = @(argv[1]).strictIntegerNumber; - - if (!number) { - puts("Usage: please input a number"); - return 1; - } - - puts(number.longLongValue % 2 == 0 ? "Even" : "Odd"); - } - return 0; -} -``` - -{% endraw %} - -Even Odd in [Objective-C](/languages/objective-c) was written by: - -- rzuckerm -- Siddhant -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/octave/index.md b/docs/projects/even-odd/octave/index.md deleted file mode 100644 index fcf6496885..0000000000 --- a/docs/projects/even-odd/octave/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- even-odd -- octave -title: Even Odd in Octave -title1: Even Odd -title2: in Octave ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function even_odd() - usage = 'Usage: please input a number'; - arg_list = argv(); - nargin = length(arg_list); - if (nargin==0) - %if there was no input - disp(usage); - else - number = str2num(arg_list{1}); - if length(number) ~= 1 || mod(number, 1) ~= 0 - %check whether input is a number - %also check if input is an integer - disp(usage); - else - if mod(number, 2) == 0 - disp('Even'); - else - disp('Odd'); - end - end - end -end - -``` - -{% endraw %} - -Even Odd in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/odin/index.md b/docs/projects/even-odd/odin/index.md deleted file mode 100644 index f1efb95d40..0000000000 --- a/docs/projects/even-odd/odin/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- nallovint -date: 2024-07-12 -featured-image: even-odd-in-every-language.jpg -last-modified: 2024-07-12 -layout: default -tags: -- even-odd -- odin -title: Even Odd in Odin -title1: Even Odd -title2: in Odin ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main - -import "core:fmt" -import "core:strconv" -import "core:os" - -main :: proc() { - if len(os.args) != 2 { - usage() - return - } - n, ok := strconv.parse_int(os.args[1]) - if !ok { - usage() - return - } - evenodd(n) -} - -evenodd :: proc(n: int) { - if n % 2 == 0 { - fmt.println("Even") - } else { - fmt.println("Odd") - } -} - -usage :: proc() { - fmt.println("Usage: please input a number") -} -``` - -{% endraw %} - -Even Odd in [Odin](/languages/odin) was written by: - -- nallovint - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/pascal/index.md b/docs/projects/even-odd/pascal/index.md deleted file mode 100644 index 943dacd476..0000000000 --- a/docs/projects/even-odd/pascal/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- smjalageri -date: 2020-10-18 -featured-image: even-odd-in-every-language.jpg -last-modified: 2020-10-18 -layout: default -tags: -- even-odd -- pascal -title: Even Odd in Pascal -title1: Even Odd -title2: in Pascal ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program a1(input, output, stdErr); -(* Read Number from commandline, print Even or Odd *) -var - buf: String; - a, check:integer; -begin - buf:= paramStr(1); - Val(buf, a, check) ; - if check <> 0 - then - writeln('Usage: please input a number') - else - begin - if( (a mod 2) = 0) then - begin - writeln('Even'); - end - else - begin - writeln('Odd'); - end - end -end. - -``` - -{% endraw %} - -Even Odd in [Pascal](/languages/pascal) was written by: - -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/perl/index.md b/docs/projects/even-odd/perl/index.md deleted file mode 100644 index ab9f230e70..0000000000 --- a/docs/projects/even-odd/perl/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Gabriela Kandová -- Ștefan-Iulian Alecu -date: 2019-10-16 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- even-odd -- perl -title: Even Odd in Perl -title1: Even Odd -title2: in Perl ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -sub usage { - say "Usage: please input a number"; - exit; -} - -my ($number) = @ARGV; - -usage() unless defined $number && $number =~ /\A-?\d+\z/; - -say $number % 2 == 0 ? "Even" : "Odd"; - -``` - -{% endraw %} - -Even Odd in [Perl](/languages/perl) was written by: - -- Gabriela Kandová -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/php/index.md b/docs/projects/even-odd/php/index.md deleted file mode 100644 index 1118dd38e6..0000000000 --- a/docs/projects/even-odd/php/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Berry Semexan -- Jeremy Grifski -date: 2019-10-16 -featured-image: even-odd-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- even-odd -- php -title: Even Odd in PHP -title1: Even Odd -title2: in PHP ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Even Odd](/projects/even-odd) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please input a number" - Exit 1 -} - -function Test-IsEven([int]$Value) { - $Value % 2 -eq 0 -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $Value = [int]::Parse($args[0]) -} catch { - Show-Usage -} - -Write-Host ((Test-IsEven $Value) ? "Even" : "Odd") - -``` - -{% endraw %} - -Even Odd in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/pyret/index.md b/docs/projects/even-odd/pyret/index.md deleted file mode 100644 index 652786e7db..0000000000 --- a/docs/projects/even-odd/pyret/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-26 -featured-image: even-odd-in-every-language.jpg -last-modified: 2024-01-01 -layout: default -tags: -- even-odd -- pyret -title: Even Odd in Pyret -title1: Even Odd -title2: in Pyret ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Pyret](/languages/pyret) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pyret -import cmdline-lib as CL - -usage = "Usage: please input a number\n" -args = CL.command-line-arguments() -cases(Option) string-to-number(if args.length() > 1: args.get(1) else: "" end): - | none => print(usage) - | some(n) => - if not(num-is-integer(n)): print(usage) - else if num-modulo(n, 2) == 0: print("Even\n") - else: print("Odd\n") - end -end - -``` - -{% endraw %} - -Even Odd in [Pyret](/languages/pyret) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/python/index.md b/docs/projects/even-odd/python/index.md deleted file mode 100644 index 60115af98d..0000000000 --- a/docs/projects/even-odd/python/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -- rzuckerm -date: 2018-12-22 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- even-odd -- python -title: Even Odd in Python -title1: Even Odd -title2: in Python ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def even_odd(x): - return "Even" if x % 2 == 0 else "Odd" - - -def exit_with_error(): - print('Usage: please input a number') - sys.exit(1) - - -def main(args): - try: - num = int(args[0]) - print(even_odd(num)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Even Odd in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Parker Johansen - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's look at the code in detail: - -Here we have a function called `even_odd` that returns "Even" if a number is even and "Odd" if it is odd. We are checking this using the modulus operator (%) which returns the remainder after division. The result after a modulo operation of an even integer will always be 0 while the result after a modulo operation of an odd integer will always be 1. - -Ex. -* 14 % 2 => 0 (14 / 2 is 7 with no remainder) -* 15 % 2 => 1 (15 / 2 is 7 with a remainder of 1) - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of -Hello World in Python. After that, we should make sure we have the -[latest Python interpreter][1]. From there, we can simply run the following -command in the terminal: - -```console -python even-odd.py -``` - -With being any integer. For example - -```console -python even-odd.py 12 -``` - -Alternatively, we can copy the solution into an [online Python interpreter][2] -and hit run. - -[1]: https://docs.python.org/3/tutorial/interpreter.html -[2]: https://www.onlinegdb.com/online_python_interpreter diff --git a/docs/projects/even-odd/r/index.md b/docs/projects/even-odd/r/index.md deleted file mode 100644 index 7f50294f81..0000000000 --- a/docs/projects/even-odd/r/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Grooble -date: 2021-10-22 -featured-image: even-odd-in-every-language.jpg -last-modified: 2021-10-22 -layout: default -tags: -- even-odd -- r -title: Even Odd in R -title1: Even Odd -title2: in R ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -args<-commandArgs(TRUE) -number = args[1] - -if (length(args) < 1 || !suppressWarnings(!is.na(as.numeric(number)))) { - cat("Usage: please input a number") -}else { - number = as.numeric(number) - if (number %% 2 == 0) { - cat("Even") - }else { - cat("Odd") - } -} - -``` - -{% endraw %} - -Even Odd in [R](/languages/r) was written by: - -- Grooble - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/rexx/index.md b/docs/projects/even-odd/rexx/index.md deleted file mode 100644 index 1957bfdaa1..0000000000 --- a/docs/projects/even-odd/rexx/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Sudhanshu Dubey -date: 2020-10-07 -featured-image: even-odd-in-every-language.jpg -last-modified: 2020-10-07 -layout: default -tags: -- even-odd -- rexx -title: Even Odd in Rexx -title1: Even Odd -title2: in Rexx ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Rexx](/languages/rexx) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rexx -/* ARG with source string named in REXX program invocation */ -arg number -If (DATATYPE(number, 'W') == 0) then signal err -if (number // 2 == 0) then - say "Even" -else - say "Odd" -;exit - -Err: -say 'Usage: please input a number'; exit - -``` - -{% endraw %} - -Even Odd in [Rexx](/languages/rexx) was written by: - -- Sudhanshu Dubey - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/ruby/index.md b/docs/projects/even-odd/ruby/index.md deleted file mode 100644 index 777a536f27..0000000000 --- a/docs/projects/even-odd/ruby/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- Ștefan-Iulian Alecu -date: 2019-10-31 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- even-odd -- ruby -title: Even Odd in Ruby -title1: Even Odd -title2: in Ruby ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -input = ARGV.first - -abort("Usage: please input a number") if input.nil? || input.strip.empty? - -begin - num = Integer(input) - puts num.even? ? "Even" : "Odd" -rescue ArgumentError - warn "Usage: please input a number" -end - -``` - -{% endraw %} - -Even Odd in [Ruby](/languages/ruby) was written by: - -- Mallikarjuna S J -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/rust/index.md b/docs/projects/even-odd/rust/index.md deleted file mode 100644 index bded0463f8..0000000000 --- a/docs/projects/even-odd/rust/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- rzuckerm -date: 2019-10-31 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- even-odd -- rust -title: Even Odd in Rust -title1: Even Odd -title2: in Rust ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -// Requirement is in https://sample-programs.therenegadecoder.com/projects/even-odd/ -// Program to accept an integer on the command line and outputs if the integer is Even or Odd. - -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please input a number"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn main() { - let mut args = args().skip(1); - - // Exit if 1st command-line argument not an integer - let mut input_num: i32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Even if divisible by 2, Odd otherwise - match input_num % 2 == 0 { - true => println!("Even"), - false => println!("Odd"), - } -} - -``` - -{% endraw %} - -Even Odd in [Rust](/languages/rust) was written by: - -- Mallikarjuna S J -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/scala/index.md b/docs/projects/even-odd/scala/index.md deleted file mode 100644 index dc2fc3b4ed..0000000000 --- a/docs/projects/even-odd/scala/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -- Ștefan-Iulian Alecu -date: 2023-05-15 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- even-odd -- scala -title: Even Odd in Scala -title1: Even Odd -title2: in Scala ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -import scala.util.Try - -object EvenOdd: - private val usage = "Usage: please input a number" - - def main(args: Array[String]): Unit = - val result = - args.headOption - .flatMap(a => Try(a.toInt).toOption) - .map(n => if n % 2 == 0 then "Even" else "Odd") - .getOrElse(usage) - - println(result) -``` - -{% endraw %} - -Even Odd in [Scala](/languages/scala) was written by: - -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/swift/index.md b/docs/projects/even-odd/swift/index.md deleted file mode 100644 index 1d5ea538fb..0000000000 --- a/docs/projects/even-odd/swift/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Jonas Halstrup -date: 2020-10-05 -featured-image: even-odd-in-every-language.jpg -last-modified: 2020-10-05 -layout: default -tags: -- even-odd -- swift -title: Even Odd in Swift -title1: Even Odd -title2: in Swift ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -// for System.exit() -import Foundation - - -/* - Check if there is exactly one argument and if it can be parsed as an integer -*/ -guard CommandLine.argc == 2, let number = Int(CommandLine.arguments[1]) else { - print("Usage: please input a number") - exit(0) -} - -let is_even = number % 2 == 0 - -if is_even { - print("Even") -} else { - print("Odd") -} -``` - -{% endraw %} - -Even Odd in [Swift](/languages/swift) was written by: - -- Jonas Halstrup - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/tcl/index.md b/docs/projects/even-odd/tcl/index.md deleted file mode 100644 index 2a05fee099..0000000000 --- a/docs/projects/even-odd/tcl/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: even-odd-in-every-language.jpg -last-modified: 2025-10-08 -layout: default -tags: -- even-odd -- tcl -title: Even Odd in Tcl -title1: Even Odd -title2: in Tcl ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts "Usage: please input a number" - exit 1 -} - -if {$argc != 1} { - usage -} - -set arg [lindex $argv 0] - -if {![string is integer -strict $arg]} { - usage -} - -set num [expr {$arg + 0}] -puts [expr {$num % 2 == 0 ? "Even" : "Odd"}] - -``` - -{% endraw %} - -Even Odd in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/ti-basic/index.md b/docs/projects/even-odd/ti-basic/index.md deleted file mode 100644 index f00c3c0ff7..0000000000 --- a/docs/projects/even-odd/ti-basic/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-02 -featured-image: even-odd-in-every-language.jpg -last-modified: 2025-02-02 -layout: default -tags: -- even-odd -- ti-basic -title: Even Odd in TI-BASIC -title1: Even Odd in -title2: TI-BASIC ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -"0123456789"->Str2 -length(Str1)->L -L<1->E -0->D -0->V -1->N -While E=0 and N<=L - sub(Str1,N,1)->C - inString(Str2,C)-1->K - If C="+" or C="-" Then D>0->E - Else - K<0->E - D+1->D - V*10+K->V - End - N+1->N -End -If E or D<1 Then Disp "Usage: please input a number" -Else - If remainder(V,2)=0 Then Disp "Even" - Else Disp "Odd" - End -End - -``` - -{% endraw %} - -Even Odd in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/typescript/index.md b/docs/projects/even-odd/typescript/index.md deleted file mode 100644 index def2083a6b..0000000000 --- a/docs/projects/even-odd/typescript/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2023-10-02 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-10-02 -layout: default -tags: -- even-odd -- typescript -title: Even Odd in TypeScript -title1: Even Odd in -title2: TypeScript ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -const error_msg: string = "Usage: please input a number" -let num_str:string = (process.argv.length == 3) ? process.argv[2] : ""; -let num:number = parseInt(num_str); -if (isNaN(num)) { - console.log(error_msg); - process.exit(1); -} -let is_even:boolean = (num % 2 == 0); -console.log(is_even ? "Even" : "Odd"); -``` - -{% endraw %} - -Even Odd in [TypeScript](/languages/typescript) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/v/index.md b/docs/projects/even-odd/v/index.md deleted file mode 100644 index d6062fdbfb..0000000000 --- a/docs/projects/even-odd/v/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Zia -date: 2024-12-15 -featured-image: even-odd-in-every-language.jpg -last-modified: 2024-12-15 -layout: default -tags: -- even-odd -- v -title: Even Odd in V -title1: Even Odd -title2: in V ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [V](/languages/v) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```v -module main - -import os -import strconv - -fn main() { - if os.args.len < 2 { - println('Usage: please input a number') - exit(1) - } - - num := strconv.atoi(os.args[1]) or { - println('Usage: please input a number') - exit(1) - } - - print(match num % 2 { - 0 { 'Even' } - 1, -1 { 'Odd' } - else { 'Usage: please input a number' } - }) -} - -``` - -{% endraw %} - -Even Odd in [V](/languages/v) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/visual-basic/index.md b/docs/projects/even-odd/visual-basic/index.md deleted file mode 100644 index 3a1d670fb5..0000000000 --- a/docs/projects/even-odd/visual-basic/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: even-odd-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- even-odd -- visual-basic -title: Even Odd in Visual Basic -title1: Even Odd in -title2: Visual Basic ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Module EvenOdd - - Public Sub Main(args As String()) - - If args.Length = 0 Then - Console.WriteLine("Usage: please input a number") - Environment.Exit(1) - End If - - Dim n As Integer - - If Not Integer.TryParse(args(0), n) Then - Console.WriteLine("Usage: please input a number") - Environment.Exit(1) - End If - - Dim result As String = If(n Mod 2 = 0, "Even", "Odd") - - Console.WriteLine(result) - - End Sub - -End Module -``` - -{% endraw %} - -Even Odd in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/wren/index.md b/docs/projects/even-odd/wren/index.md deleted file mode 100644 index 3a0e58d092..0000000000 --- a/docs/projects/even-odd/wren/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-20 -featured-image: even-odd-in-every-language.jpg -last-modified: 2025-01-20 -layout: default -tags: -- even-odd -- wren -title: Even Odd in Wren -title1: Even Odd -title2: in Wren ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -import "os" for Process - -var args = Process.arguments // Process.args is a bit long and annoying to type. - -if (args.count < 1 || args[0].count < 1) { - System.print("Usage: please input a number") - Fiber.suspend() -} - -var n = Num.fromString(args[0]) - -if (n == null) { - System.print("Usage: please input a number") - Fiber.suspend() -} - -if (n % 2 == 0) { - System.print("Even") -} else { - System.print("Odd") -} - -``` - -{% endraw %} - -Even Odd in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/even-odd/x86-64/index.md b/docs/projects/even-odd/x86-64/index.md deleted file mode 100644 index c8c4f320ae..0000000000 --- a/docs/projects/even-odd/x86-64/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -authors: -- alope107 -date: 2023-05-07 -featured-image: even-odd-in-every-language.jpg -last-modified: 2023-05-07 -layout: default -tags: -- even-odd -- x86-64 -title: Even Odd in x86-64 -title1: Even Odd -title2: in x86-64 ---- - - - -Welcome to the [Even Odd](/projects/even-odd) in [x86-64](/languages/x86-64) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```x86-64 -section .data - error_msg db "Usage: please input a number" - error_len equ $-error_msg - even_msg db "Even" - even_len equ $-even_msg - odd_msg db "Odd" - odd_len equ $-odd_msg - -section .bss - buff resb 1 - -section .text - global _start - -_start: - ; Need to have at least 2 args (program name & number) - mov rdi, [rsp] - cmp rdi, 2 - jl error - - ; Store pointer to second arg in r8 - lea rsi, [rsp + 8] - mov r8, [rsi + 8] - - xor r12, r12 ; r12 will hold whether we've looked at at least one byte - read_loop: - ; Read one byte of the string - mov byte al, [r8] - - ; Stop reading once we reach the null terminator - cmp al, 0 - je end_loop - - ; Keep the last character read in bl so it doesn't get overwritten once the null is eventually read - mov bl, al - - ; Check for minus - cmp bl, "-" - jne non_minus - - minus_sign: - ; If we've already read at least one character, reading a minus is invalid - cmp r12, 0 - jne error - - jmp valid_char - - non_minus: - ; If it's not a minus sign and has an ascii value not in the range '0'-'9', it's invalid - cmp bl, '0' - jl error - cmp bl, '9' - jg error - - valid_char: - mov r12, 1 ; Mark that at least one byte has been read - inc r8 - jmp read_loop - - end_loop: - ; If we didn't read at least one character, there is an error - cmp r12, 0 - je error - - ; If the only character we read is '-', there is an error - cmp bl, '-' - je error - - ; Check whether the last bit of the last char inputted is 1 - ; Because even ASCII digits have even ascii codes we don't need to convert it to the number first - and rbx, 1 - cmp rbx, 0 - jne odd - - even: - ; Print 'Even' - mov rax, 1 - mov rdi, 1 - mov rsi, even_msg - mov rdx, even_len - syscall - jmp cleanup - - odd: - ; Print 'Odd' - mov rax, 1 - mov rdi, 1 - mov rsi, odd_msg - mov rdx, odd_len - syscall - jmp cleanup - - error: - ; Print error message - mov rax, 1 - mov rdi, 1 - mov rsi, error_msg - mov rdx, error_len - syscall - - cleanup: - ; Exit with return value 0 - mov rax, 60 - xor rdi, rdi - syscall -``` - -{% endraw %} - -Even Odd in [x86-64](/languages/x86-64) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/ada/index.md b/docs/projects/factorial/ada/index.md deleted file mode 100644 index bdb7781985..0000000000 --- a/docs/projects/factorial/ada/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-10 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-10 -layout: default -tags: -- ada -- factorial -title: Factorial in Ada -title1: Factorial -title2: in Ada ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; - -procedure Factorial is - - procedure Print_Usage is - begin - Put_Line ("Usage: please input a non-negative integer"); - end Print_Usage; - - function Fact (N : Natural) return Natural is - Result : Natural := 1; - begin - for I in 2 .. N loop - Result := Result * I; - end loop; - return Result; - end Fact; - - Max_Allowed : constant Natural := 12; -- Fact (13) > Natural'Last - -begin - if Argument_Count /= 1 then - Print_Usage; - return; - end if; - - declare - N : Natural; - begin - begin - N := Natural'Value (Argument (1)); - exception - when Constraint_Error => - Print_Usage; - return; - end; - - if N > Max_Allowed then - Print_Usage; - return; - end if; - - Put_Line (Natural'Image (Fact (N))); - - end; - -end Factorial; - -``` - -{% endraw %} - -Factorial in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/algol60/index.md b/docs/projects/factorial/algol60/index.md deleted file mode 100644 index c83104a0ec..0000000000 --- a/docs/projects/factorial/algol60/index.md +++ /dev/null @@ -1,168 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-20 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- algol60 -- factorial -title: Factorial in ALGOL 60 -title1: Factorial -title2: in ALGOL 60 ---- - - - -Welcome to the [Factorial](/projects/factorial) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please input a non-negative integer\n"); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - null byte maps to 17 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch); - integer result, ch; - begin - boolean valid; - integer s; - - result := 0; - valid := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment Ignore characters until end of argument. Indicate invalid - if not whitespace; - ignoreloop: - if ch != -1 then - begin - if ch != 12 then valid := false; - ch := indigit; - goto ignoreloop - end; - - inValidInteger := valid - end inValidInteger; - - integer procedure factorial(n); - value n; - integer n; - begin - integer result, i; - - result := 1; - for i := 1 step 1 until n do result := result * i; - - factorial := result - end factorial; - - integer argc, result, ch; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get integer value from 1st argument. Exit if invalid or - negative; - if !inValidInteger(result, ch) | result < 0 then usage; - - comment Output factorial; - outinteger(1, factorial(result)); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Factorial in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/algol68/index.md b/docs/projects/factorial/algol68/index.md deleted file mode 100644 index 8efb552050..0000000000 --- a/docs/projects/factorial/algol68/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-21 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-01-30 -layout: default -tags: -- algol68 -- factorial -title: Factorial in ALGOL 68 -title1: Factorial -title2: in ALGOL 68 ---- - - - -Welcome to the [Factorial](/projects/factorial) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC usage = VOID: printf(($gl$, "Usage: please input a non-negative integer")); - -# Allow answer to be up to 201 digits (googol squared!) # -PR precision=201 PR - -PROC factorial = (INT n) LONG LONG INT: -( - # Multiply from 1 through n (note that 0! = 1) # - LONG LONG INT fact := 1; - FOR k FROM 2 TO n - DO - # Exit if next multiplication will cause an overlow # - IF fact > long long max int / k - THEN - putf(stand error, ($gl$, "Overflow!")); - stop - FI; - - fact *:= k - OD; - - fact -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINT_RESULT result := parse int(s); - -# If invalid, extra characters, or negative, exit # -INT n := value OF result; -IF NOT (valid OF result) OR (leftover OF result) /= "" OR n < 0 -THEN - usage; - stop -FI; - -# Calculate and display factorial # -LONG LONG INT fact := factorial(n); -print((whole(fact, 0), newline)) - -``` - -{% endraw %} - -Factorial in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/awk/index.md b/docs/projects/factorial/awk/index.md deleted file mode 100644 index bac1739d93..0000000000 --- a/docs/projects/factorial/awk/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-14 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- factorial -title: Factorial in AWK -title1: Factorial -title2: in AWK ---- - - - -Welcome to the [Factorial](/projects/factorial) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please input a non-negative integer" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function factorial(n, f) { - f = 1 - while (n >= 2) { - f *= n - n-- - } - - return f -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - result = str_to_number(ARGV[1]) - if (result == "ERROR" || result < 0) { - usage() - } - - print factorial(result) -} - -``` - -{% endraw %} - -Factorial in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/bash/index.md b/docs/projects/factorial/bash/index.md deleted file mode 100644 index 331fd991f0..0000000000 --- a/docs/projects/factorial/bash/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Amanda Hager Lopes de Andrade Katz -date: 2019-10-09 -featured-image: factorial-in-every-language.jpg -last-modified: 2019-10-09 -layout: default -tags: -- bash -- factorial -title: Factorial in Bash -title1: Factorial -title2: in Bash ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -number=$1 - -if [[ -z "$number" ]] -then - echo "Usage: please input a non-negative integer" - exit 1 -fi - -if ! [[ "$number" =~ ^[0-9]+$ ]] -then - echo "Usage: please input a non-negative integer" - exit 1 -fi - -value=1 - -while [ $number -gt 1 ] -do - - value=$((value * number)) - - number=$((number - 1)) - -done - -echo $value - -``` - -{% endraw %} - -Factorial in [Bash](/languages/bash) was written by: - -- Amanda Hager Lopes de Andrade Katz - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/beef/index.md b/docs/projects/factorial/beef/index.md deleted file mode 100644 index 9b6a606665..0000000000 --- a/docs/projects/factorial/beef/index.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-22 -featured-image: factorial-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- factorial -title: Factorial in Beef -title1: Factorial -title2: in Beef ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace Factorial; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please input a non-negative integer"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result Factorial(int32 n) - { - uint64 result = 1; - for (int32 i in 2...n) - { - if (result > (uint64.MaxValue / (uint64)i)) - { - return .Err; - } - - result *= (uint64)i; - } - - return .Ok(result); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - int32 val = 0; - switch (ParseInt(args[0])) - { - case .Ok(out val): - if (val < 0) - { - Usage(); - } - case .Err: - Usage(); - } - - uint64 result = 0; - switch (Factorial(val)) - { - case .Ok(out result): - Console.WriteLine(result); - case .Err: - Console.WriteLine("Overflow!"); - } - - return 0; - } -} - -``` - -{% endraw %} - -Factorial in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/c-plus-plus/index.md b/docs/projects/factorial/c-plus-plus/index.md deleted file mode 100644 index 9e7b6f0f61..0000000000 --- a/docs/projects/factorial/c-plus-plus/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Angooj Kumar Singh -- Ștefan-Iulian Alecu -date: 2019-10-09 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- factorial -title: Factorial in C++ -title1: Factorial -title2: in C++ ---- - - - -Welcome to the [Factorial](/projects/factorial) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please input a non-negative integer\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - s = trim(s); - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - if (auto n = to_int(argv[1]); !n || *n < 0) { - usage(); - } else { - unsigned long long result = 1; - for (int i = 2; i <= *n; ++i) { - result *= i; - } - std::cout << result << '\n'; - } -} -``` - -{% endraw %} - -Factorial in [C++](/languages/c-plus-plus) was written by: - -- Angooj Kumar Singh -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/c-sharp/index.md b/docs/projects/factorial/c-sharp/index.md deleted file mode 100644 index 04fab8dabe..0000000000 --- a/docs/projects/factorial/c-sharp/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-28 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- factorial -title: Factorial in C# -title1: Factorial -title2: in C# ---- - - - -Welcome to the [Factorial](/projects/factorial) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Numerics; - -if (args is not [var input] || !BigInteger.TryParse(input, out var n) || n < 0) -{ - Console.Error.WriteLine("Usage: please input a non-negative integer"); - return; -} - -Console.WriteLine(Factorial(n)); - -static BigInteger Factorial(BigInteger n) => n < 2 ? BigInteger.One : MultiplyRange(2, n); - -static BigInteger MultiplyRange(BigInteger lo, BigInteger hi) -{ - if (lo > hi) - return BigInteger.One; - if (lo == hi) - return lo; - if (hi - lo == 1) - return lo * hi; - - BigInteger mid = (lo + hi) / 2; - return MultiplyRange(lo, mid) * MultiplyRange(mid + 1, hi); -} - -``` - -{% endraw %} - -Factorial in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/c/index.md b/docs/projects/factorial/c/index.md deleted file mode 100644 index f227dac1a8..0000000000 --- a/docs/projects/factorial/c/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- clarkimusmax -- Ștefan-Iulian Alecu -date: 2018-10-26 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- factorial -title: Factorial in C -title1: Factorial -title2: in C ---- - - - -Welcome to the [Factorial](/projects/factorial) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include -#include -#include - -int uint64_overflow(long, long); - -int main(int argc, char *argv[]) -{ - long n; - char *endptr; - uint64_t result = 1; - long i; - - /* Correct nmber of args? */ - if (argc != 2) - { - printf("Usage: please input a non-negative integer\n"); - exit(0); - } - - /* Convert argument to number */ - errno = 0; - n = strtol(argv[1], &endptr, 10); - if ((errno == ERANGE && (n == LONG_MAX || n == LONG_MIN)) - || (errno != 0 && n == 0)) - { - perror("strtol"); - exit(1); - } - - if (endptr == argv[1] || !(*endptr == '\0' || *endptr == '\n') || n < 0) - { - fprintf(stderr, "Usage: please input a non-negative integer\n"); - exit(1); - } - - /* For non-zero numbers, compute factorial */ - if (n) - { - for (i = 1; i <= n; i++) - { - if (uint64_overflow(result, i)) - { - printf("Results overflowed\n"); - exit(1); - } - - result *= i; - } - } - - /* Print result */ - printf("%" PRIu64 "\n", result); - - return 0; -} - -/* - * Detects overflow from 64-bit multiplication. - * - * Returns 1 if an overflow occurs, 0 if not - */ -int uint64_overflow(long a, long b) -{ - uint64_t x; - uint64_t b_64; - - x = a * b; - b_64 = b; - - return (a != 0 && x / a != b_64) ? 1 : 0; -} - -``` - -{% endraw %} - -Factorial in [C](/languages/c) was written by: - -- clarkimusmax -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/cobol/index.md b/docs/projects/factorial/cobol/index.md deleted file mode 100644 index 47a524a4a1..0000000000 --- a/docs/projects/factorial/cobol/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-18 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- cobol -- factorial -title: Factorial in COBOL -title1: Factorial -title2: in COBOL ---- - - - -Welcome to the [Factorial](/projects/factorial) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. factorial. - -data division. -working-storage section. - -01 cmd-args pic x(38). -01 num pic s9(7). -01 result pic z(18)9 value 1. - -procedure division. - -main. - accept cmd-args from command-line - - if function test-numval(cmd-args) not = 0 - perform show-usage - end-if - - compute num = function numval(cmd-args) - - if num < 0 - perform show-usage - end-if - - compute result = function factorial(num) - display result - - stop run. - -show-usage. - display "Usage: please input a non-negative integer" - stop run. - -``` - -{% endraw %} - -Factorial in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/coffeescript/index.md b/docs/projects/factorial/coffeescript/index.md deleted file mode 100644 index c79b5f85bd..0000000000 --- a/docs/projects/factorial/coffeescript/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Hanyuan Li -- Jeremy Grifski -date: 2019-10-11 -featured-image: factorial-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- coffeescript -- factorial -title: Factorial in CoffeeScript -title1: Factorial in -title2: CoffeeScript ---- - - - -Welcome to the [Factorial](/projects/factorial) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -factorial = (n) -> - return usage() if n < 0 - return 1 if n == "0" - [1..n].reduce (x, y) -> x * y - -usage = () -> - "Usage: please input a non-negative integer" - -main = () -> - args = process.argv - return factorial(args[2]) if args.length == 3 and isFinite(args[2]) and args[2] != "" - usage() - -console.log main() - -``` - -{% endraw %} - -Factorial in [CoffeeScript](/languages/coffeescript) was written by: - -- Hanyuan Li -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/commodore-basic/index.md b/docs/projects/factorial/commodore-basic/index.md deleted file mode 100644 index db86f1451e..0000000000 --- a/docs/projects/factorial/commodore-basic/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- factorial -title: Factorial in Commodore BASIC -title1: Factorial in -title2: Commodore BASIC ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input N -10 GOSUB 1000 -20 IF V = 0 OR C >=0 OR NR < 0 THEN GOTO 110: REM invalid or not end character -30 N = NR -40 F = 1 -50 IF N < 2 THEN GOTO 90 -60 FOR K = 2 TO N -70 F = F * K -80 NEXT K -90 PRINT MID$(STR$(F), 2) -100 END -110 PRINT "Usage: please input a non-negative integer" -120 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN - -``` - -{% endraw %} - -Factorial in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/crystal/index.md b/docs/projects/factorial/crystal/index.md deleted file mode 100644 index 3262f038f6..0000000000 --- a/docs/projects/factorial/crystal/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- HunterYates -date: 2025-02-16 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-02-16 -layout: default -tags: -- crystal -- factorial -title: Factorial in Crystal -title1: Factorial -title2: in Crystal ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Crystal](/languages/crystal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```crystal -begin - if ARGV.empty? - raise "Usage: please input a non-negative integer" - end - - input = ARGV[0].to_i? - - if input.nil? - raise "Usage: please input a non-negative integer" - end - - input = input.not_nil! - - if input >= 0 && input <= 12 - puts factorial(input) - elsif input > 12 - raise "#{input} is out of the reasonable bounds for calculation." - else - raise "Usage: please input a non-negative integer" - end - -rescue e - puts e.message -end - -def factorial(n) - return 1 if n == 0 - n * factorial(n - 1) -end -``` - -{% endraw %} - -Factorial in [Crystal](/languages/crystal) was written by: - -- HunterYates - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/d/index.md b/docs/projects/factorial/d/index.md deleted file mode 100644 index efd1238dc8..0000000000 --- a/docs/projects/factorial/d/index.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -authors: -- rzuckerm -- Scott Little -date: 2020-10-04 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-05-13 -layout: default -tags: -- d -- factorial -title: Factorial in D -title1: Factorial -title2: in D ---- - - - -Welcome to the [Factorial](/projects/factorial) in [D](/languages/d) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```d -// Factorial program in D -import std.stdio: writeln; -import std.conv: to, ConvException; -import core.stdc.stdlib: exit; - -void usage() -{ - writeln("Usage: please input a non-negative integer"); - exit(0); -} - -int fac(int a) -{ - if (a <= 1) - { - return 1; - } - return a*fac(a-1); -} - -int main(string[] args) -{ - if (args.length < 2) - { - usage(); - } - - int depth; - try { - depth = to!int(args[1]); - if (depth < 0) - { - usage(); - } - } - catch(ConvException _) - { - usage(); - } - - int result = fac(depth); - writeln(result); - return 0; -} - -``` - -{% endraw %} - -Factorial in [D](/languages/d) was written by: - -- rzuckerm -- Scott Little - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/dart/index.md b/docs/projects/factorial/dart/index.md deleted file mode 100644 index 53ac8d4cd5..0000000000 --- a/docs/projects/factorial/dart/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- gangaasoonu -date: 2025-10-04 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-10-04 -layout: default -tags: -- dart -- factorial -title: Factorial in Dart -title1: Factorial -title2: in Dart ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -// Issue 4969 -void main(List args){ - const String error_message = "Usage: please input a non-negative integer"; - try{ - - int factorial = 1; - int num_needed = int.parse(args[0]); - if (num_needed.isNegative == true){ - print(error_message); - } - else{ - for (int i_index = 1; i_index <= num_needed; i_index ++){ - factorial *= i_index; - } - print(factorial.toString()); - } - - } - catch(e){ - print(error_message); - } -} - -``` - -{% endraw %} - -Factorial in [Dart](/languages/dart) was written by: - -- gangaasoonu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/elixir/index.md b/docs/projects/factorial/elixir/index.md deleted file mode 100644 index b22e9fb35f..0000000000 --- a/docs/projects/factorial/elixir/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -- pearl2201 -date: 2019-10-12 -featured-image: factorial-in-every-language.jpg -last-modified: 2019-10-16 -layout: default -tags: -- elixir -- factorial -title: Factorial in Elixir -title1: Factorial -title2: in Elixir ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Elixir](/languages/elixir) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elixir -defmodule Factorial do - def main(args) do - args - |> List.first - |> as_integer - |> get - |> IO.puts() - end - - def get(0, acc) do - acc - end - - def get(n, acc) do - get(n - 1, acc * n) - end - - def get(n) when not is_integer(n) or n < 0 do - "Usage: please input a non-negative integer" - end - - def get(n) do - get(n, 1) - end - - def as_integer(n) do - try do - String.to_integer(n) - rescue - ArgumentError -> -1 - end - end -end - -Factorial.main(System.argv()) - -``` - -{% endraw %} - -Factorial in [Elixir](/languages/elixir) was written by: - -- Jeremy Grifski -- Parker Johansen -- pearl2201 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/elvish/index.md b/docs/projects/factorial/elvish/index.md deleted file mode 100644 index b2d34563bd..0000000000 --- a/docs/projects/factorial/elvish/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-12 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-01-12 -layout: default -tags: -- elvish -- factorial -title: Factorial in Elvish -title1: Factorial -title2: in Elvish ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -if (> 1 (count $args)) { - echo "Usage: please input a non-negative integer" - exit 1 -} - -try { - var r = (+ $args[0] 1) # Hacky, but it tries to add the argument with one. -} catch { # If it fails, the value is not a number. - echo "Usage: please input a non-negative integer" - exit 1 -} - -if (> 0 $args[0]) { - echo "Usage: please input a non-negative integer" - exit 1 -} - -var f = 1 - -for i [(range 1 (+ 1 $args[0]))] { - set f = (* $f $i) -} - -echo $f - -``` - -{% endraw %} - -Factorial in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/erlang/index.md b/docs/projects/factorial/erlang/index.md deleted file mode 100644 index f6b6872dde..0000000000 --- a/docs/projects/factorial/erlang/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Mark Magahis -- rzuckerm -date: 2019-10-06 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-11-21 -layout: default -tags: -- erlang -- factorial -title: Factorial in Erlang -title1: Factorial -title2: in Erlang ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Erlang](/languages/erlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```erlang --module(factorial). --export([main/1]). - -usage() -> - io:format("Usage: please input a non-negative integer~n"), - halt(). - -convert_to_integer(Str) -> - Result = catch string:to_integer(string:strip(Str)), - case Result of - {Int, Rest} when Rest == "" -> - {ok, Int}; - _ -> - {error, 0} - end. - -main(Args) -> - if - length(Args) < 1 -> - usage(); - true -> - ok - end, - - StrValue = lists:nth(1, Args), - Value = case convert_to_integer(StrValue) of - {ok, Int} -> - Int; - _ -> - usage() - end, - - if - Value < 0 -> - usage(); - true -> - ok - end, - - FValue = factorial(Value), - io:format("~w~n", [FValue]). - -%%-------------------------------------------------------------------- -%% Recursively multiply N times N-1 until N <= 1 -%%-------------------------------------------------------------------- -factorial(0) -> - 1; -factorial(N) -> - N * factorial(N-1). - -``` - -{% endraw %} - -Factorial in [Erlang](/languages/erlang) was written by: - -- Mark Magahis -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/euphoria/index.md b/docs/projects/factorial/euphoria/index.md deleted file mode 100644 index e32685f135..0000000000 --- a/docs/projects/factorial/euphoria/index.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- factorial -title: Factorial in Euphoria -title1: Factorial -title2: in Euphoria ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/math.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - -procedure usage() - puts(STDOUT, "Usage: please input a non-negative integer\n") - abort(0) -end procedure - -function factorial(integer value) - -- Multiply from 1 through n (note that 0! = 1) - atom fact = 1 - for n = 2 to value - do - -- Exit if next multiplication will cause an overlow - fact *= n - if not integer(fact) - then - puts(STDERR, "Overflow!\n") - abort(0) - end if - end for - - return fact -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int(argv[4]) -integer value = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] or value < 0 -then - usage() -end if - --- Calculate and display factorial -atom fact = factorial(value) -printf(STDOUT, "%d\n", {fact}) - -``` - -{% endraw %} - -Factorial in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/f-sharp/index.md b/docs/projects/factorial/f-sharp/index.md deleted file mode 100644 index 4385df440c..0000000000 --- a/docs/projects/factorial/f-sharp/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- factorial -title: Factorial in F# -title1: Factorial -title2: in F# ---- - - - -Welcome to the [Factorial](/projects/factorial) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Factorial = - let rec private factorial n acc = - if n <= 1L then acc else factorial (n - 1L) (acc * n) - - let run n = factorial n 1L |> string - -module Helpers = - let usage = "Usage: please input a non-negative integer" - - let (|NonNegativeInteger|_|) (s: string) = - match s.Trim() |> Int64.TryParse with - | true, n when n >= 0L -> Some n - | _ -> None - - let parseArgs argv = - match argv with - | [| NonNegativeInteger n |] -> Ok n - | _ -> Error usage - - let handleResults = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.map Factorial.run |> Helpers.handleResults - -``` - -{% endraw %} - -Factorial in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/fortran/index.md b/docs/projects/factorial/fortran/index.md deleted file mode 100644 index f8f9df7877..0000000000 --- a/docs/projects/factorial/fortran/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-15 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-10-15 -layout: default -tags: -- factorial -- fortran -title: Factorial in Fortran -title1: Factorial -title2: in Fortran ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program factorial - use, intrinsic :: iso_fortran_env, only: int64 - implicit none - - character(len=64) :: arg - integer :: ios - integer(kind=int64) :: n, i - - if (command_argument_count() /= 1) call usage() - - call get_command_argument(1, arg) - arg = adjustl(trim(arg)) - if (len_trim(arg) == 0) call usage() - - read(arg, *, iostat=ios) n - if (ios /= 0 .or. n < 0_int64) call usage() - - write(*,'(i0)') product((/(i, i = 1_int64, n)/)) - -contains - - subroutine usage() - write(*,'(a)') "Usage: please input a non-negative integer" - stop - end subroutine usage - -end program factorial - -``` - -{% endraw %} - -Factorial in [Fortran](/languages/fortran) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/go/index.md b/docs/projects/factorial/go/index.md deleted file mode 100644 index a6f1625ffa..0000000000 --- a/docs/projects/factorial/go/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-02-24 -featured-image: factorial-in-every-language.jpg -last-modified: 2019-02-24 -layout: default -tags: -- factorial -- go -title: Factorial in Go -title1: Factorial -title2: in Go ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" -) - -func factorial(n uint64) uint64 { - if n <= 0 { - return 1 - } - return n * factorial(n-1) -} - -func exitWithError(msg string) { - fmt.Println(msg) - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError("Usage: please input a non-negative integer") - } - n, err := strconv.ParseUint(os.Args[1], 0, 64) - if err != nil { - exitWithError("Usage: please input a non-negative integer") - } - if n > 65 { - exitWithError(fmt.Sprintf("!%d is out of the reasonable bounds for calculation", n)) - } - fmt.Println(factorial(n)) -} - -``` - -{% endraw %} - -Factorial in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/groovy/index.md b/docs/projects/factorial/groovy/index.md deleted file mode 100644 index fa7aa41137..0000000000 --- a/docs/projects/factorial/groovy/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Rafael Vargas -date: 2019-10-12 -featured-image: factorial-in-every-language.jpg -last-modified: 2019-10-12 -layout: default -tags: -- factorial -- groovy -title: Factorial in Groovy -title1: Factorial -title2: in Groovy ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -class Factorial { - static def factorial(BigInteger n) { - if (n == 0) { - return 1 - } - return n * factorial(n - 1) - } - - static void main(args){ - if(args?.size() != 1 || !args[0].isInteger() || args[0].toInteger() < 0) { - println "Usage: please input a non-negative integer" - return - } - - if(args[0].toInteger() >= 1000){ - println "Usage: please input a value below 1000" - return - } - - println factorial(args[0].toInteger()) - } -} -``` - -{% endraw %} - -Factorial in [Groovy](/languages/groovy) was written by: - -- Rafael Vargas - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/haskell/index.md b/docs/projects/factorial/haskell/index.md deleted file mode 100644 index 1912c36504..0000000000 --- a/docs/projects/factorial/haskell/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-11-16 -featured-image: factorial-in-every-language.jpg -last-modified: 2018-11-16 -layout: default -tags: -- factorial -- haskell -title: Factorial in Haskell -title1: Factorial -title2: in Haskell ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read - -factorial :: Integer -> Integer -factorial 0 = 1 -factorial n = n * factorial (n - 1) - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - -main :: IO () -main = do - args <- getArgs - let n = headMaybe args - case n >>= readMaybe of - Nothing -> putStrLn "Usage: please input a non-negative integer" - Just n - | n < 0 -> putStrLn "Usage: please input a non-negative integer" - | n <= 250000 -> putStrLn $ take 10 $ show $ factorial n - | otherwise -> putStrLn $ "!" ++ (show n) ++ " is out of the reasonable bounds for calculation" - -``` - -{% endraw %} - -Factorial in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/index.md b/docs/projects/factorial/index.md deleted file mode 100644 index d9a53dd34e..0000000000 --- a/docs/projects/factorial/index.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -date: 2018-10-26 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- factorial -title: Factorial -title1: Factorial -title2: '' ---- - - - -Welcome to the Factorial page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -The factorial of an integer `n` is defined as: - -`n! = 1 x 2 x 3 x 4 x ... x n` - -With the special case `0! = 1`. - - -## Requirements - -You must write an executable program that accepts an integer `n` on standard -input via the command line, and outputs `n!` to standard output. - -Note that the factorial function grows very quickly. For example, `4! = 24` -but `8! = 40320`. Therefore, you should impose a limit on the input, so that -the largest factorial still fits into your language's largest supported datatype. - -Also note that the factorial is not defined for negative integers. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Factorial. -In order to keep things simple, we split up the testing as follows: - -- Factorial Valid Tests -- Factorial Invalid Tests - -### Factorial Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: Zero | "0" | "1" | -| Sample Input: One | "1" | "1" | -| Sample Input: Four | "4" | "24" | -| Sample Input: Eight | "8" | "40320" | -| Sample Input: Ten | "10" | "3628800" | - -### Factorial Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A Number | "asdf" | -| Invalid Input: Negative | "-1" | - -All of these tests should output the following: - -``` -Usage: please input a non-negative integer -``` - - -## Articles - -There are 52 articles: - -- [Factorial in ALGOL 60](/projects/factorial/algol60) -- [Factorial in ALGOL 68](/projects/factorial/algol68) -- [Factorial in AWK](/projects/factorial/awk) -- [Factorial in Ada](/projects/factorial/ada) -- [Factorial in Bash](/projects/factorial/bash) -- [Factorial in Beef](/projects/factorial/beef) -- [Factorial in C](/projects/factorial/c) -- [Factorial in C#](/projects/factorial/c-sharp) -- [Factorial in C++](/projects/factorial/c-plus-plus) -- [Factorial in COBOL](/projects/factorial/cobol) -- [Factorial in CoffeeScript](/projects/factorial/coffeescript) -- [Factorial in Commodore BASIC](/projects/factorial/commodore-basic) -- [Factorial in Crystal](/projects/factorial/crystal) -- [Factorial in D](/projects/factorial/d) -- [Factorial in Dart](/projects/factorial/dart) -- [Factorial in Elixir](/projects/factorial/elixir) -- [Factorial in Elvish](/projects/factorial/elvish) -- [Factorial in Erlang](/projects/factorial/erlang) -- [Factorial in Euphoria](/projects/factorial/euphoria) -- [Factorial in F#](/projects/factorial/f-sharp) -- [Factorial in Fortran](/projects/factorial/fortran) -- [Factorial in Go](/projects/factorial/go) -- [Factorial in Groovy](/projects/factorial/groovy) -- [Factorial in Haskell](/projects/factorial/haskell) -- [Factorial in Java](/projects/factorial/java) -- [Factorial in JavaScript](/projects/factorial/javascript) -- [Factorial in Julia](/projects/factorial/julia) -- [Factorial in Kotlin](/projects/factorial/kotlin) -- [Factorial in Lisp](/projects/factorial/lisp) -- [Factorial in Lua](/projects/factorial/lua) -- [Factorial in Mathematica](/projects/factorial/mathematica) -- [Factorial in Nim](/projects/factorial/nim) -- [Factorial in OCaml](/projects/factorial/ocaml) -- [Factorial in Objective-C](/projects/factorial/objective-c) -- [Factorial in Octave](/projects/factorial/octave) -- [Factorial in PHP](/projects/factorial/php) -- [Factorial in Pascal](/projects/factorial/pascal) -- [Factorial in Perl](/projects/factorial/perl) -- [Factorial in PowerShell](/projects/factorial/powershell) -- [Factorial in Python](/projects/factorial/python) -- [Factorial in R](/projects/factorial/r) -- [Factorial in Ruby](/projects/factorial/ruby) -- [Factorial in Rust](/projects/factorial/rust) -- [Factorial in Scala](/projects/factorial/scala) -- [Factorial in Swift](/projects/factorial/swift) -- [Factorial in TI-BASIC](/projects/factorial/ti-basic) -- [Factorial in Tcl](/projects/factorial/tcl) -- [Factorial in TypeScript](/projects/factorial/typescript) -- [Factorial in V](/projects/factorial/v) -- [Factorial in Visual Basic](/projects/factorial/visual-basic) -- [Factorial in Wren](/projects/factorial/wren) -- [Factorial in m4](/projects/factorial/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/factorial/java/index.md b/docs/projects/factorial/java/index.md deleted file mode 100644 index 1733add931..0000000000 --- a/docs/projects/factorial/java/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Bharath -- Jeremy Grifski -- Parker Johansen -date: 2018-12-30 -featured-image: factorial-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- factorial -- java -title: Factorial in Java -title1: Factorial -title2: in Java ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class Factorial { - public static long fact(long n) { - if (n <= 0) - return 1; - return n * fact(n - 1); - } - - public static void main(String[] args) { - try { - long n = Long.parseLong(args[0]); - if (n > 59) { - System.out.println(String.format("%1$s! is out of the reasonable bounds for calculation.", n)); - System.exit(1); - } else if (n < 0) { - System.out.println("Usage: please input a non-negative integer"); - System.exit(1); - } - long result = fact(n); - System.out.println(result); - } catch (Exception e) { - System.out.println("Usage: please input a non-negative integer"); - System.exit(1); - } - } -} - -``` - -{% endraw %} - -Factorial in [Java](/languages/java) was written by: - -- Bharath -- Jeremy Grifski -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/javascript/index.md b/docs/projects/factorial/javascript/index.md deleted file mode 100644 index 44c82304be..0000000000 --- a/docs/projects/factorial/javascript/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Bharath -- Matt Wiley -- rzuckerm -date: 2019-10-10 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- factorial -- javascript -title: Factorial in JavaScript -title1: Factorial in -title2: JavaScript ---- - - - -Welcome to the [Factorial](/projects/factorial) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -/** - * Calculate the factorial of a given integer input. - * - * @param {Integer} num - */ -function factorial(num) { - let product = 1; - if ( num > 1 ) { - for ( let i = 2; i <= num; i++ ) { - product *= i; - } - } - return product; -} - -/** - * Executable function - * - * @param {Command line input} input - */ -function main(input) { - // Usage text - const usage = 'Usage: please input a non-negative integer'; - - // No input - if ( !input ) { - console.log(usage); - return; - } - - /** - * If we remove all the integer characters from the input and are left with - * an empty string, then we have a valid integer. - */ - const inputValidation = input.replace(/[0-9]/g,''); - - if ( inputValidation === '' ) { - // Valid integer - const parsedInput = parseInt(input); - if ( parsedInput < 0 ) { - console.log(usage); - } - else if ( parsedInput > 170 ) { - console.log(`Input of ${parsedInput} is too large to calculate a factorial for. Max input is 170.`); - } - else { - console.log(factorial(parsedInput)); - } - } - else { - // Anything non integer - console.log(usage); - } - -} - -// Run the executable function -const input = process.argv[2]; -main(input); - -``` - -{% endraw %} - -Factorial in [JavaScript](/languages/javascript) was written by: - -- Bharath -- Matt Wiley -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/julia/index.md b/docs/projects/factorial/julia/index.md deleted file mode 100644 index c067e21f0c..0000000000 --- a/docs/projects/factorial/julia/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- sniklas142 -date: 2020-10-01 -featured-image: factorial-in-every-language.jpg -last-modified: 2020-10-01 -layout: default -tags: -- factorial -- julia -title: Factorial in Julia -title1: Factorial -title2: in Julia ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -#!/usr/bin/julia - -function err() - println("Usage: please input a non-negative integer") -end - -function fac(n) - if n < 0 - err() - exit() - end - - out = 1 - for i = 1:n - out = out * i - end - return out -end - -try - println(fac(parse(Int, ARGS[1]))) -catch e - err() -end - -``` - -{% endraw %} - -Factorial in [Julia](/languages/julia) was written by: - -- sniklas142 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/kotlin/index.md b/docs/projects/factorial/kotlin/index.md deleted file mode 100644 index 9c6cd9ae96..0000000000 --- a/docs/projects/factorial/kotlin/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Blake.Ke -- Satyajit Pradhan -date: 2019-10-06 -featured-image: factorial-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- factorial -- kotlin -title: Factorial in Kotlin -title1: Factorial -title2: in Kotlin ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -import java.math.BigInteger - -fun main(args: Array) { - if (args.isNullOrEmpty() || args[0].toIntOrNull()?.takeIf { it >= 0 } == null) { - println("Usage: please input a non-negative integer") - return - } - - val num = args[0].toInt() - var factorial = BigInteger.ONE - for (i in 1..num) { - // factorial = factorial * i; - factorial = factorial.multiply(BigInteger.valueOf(i.toLong())) - } - println(factorial) -} -``` - -{% endraw %} - -Factorial in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- Satyajit Pradhan - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/lisp/index.md b/docs/projects/factorial/lisp/index.md deleted file mode 100644 index eb22380b40..0000000000 --- a/docs/projects/factorial/lisp/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Parker Johansen -- Renato -date: 2020-10-01 -featured-image: factorial-in-every-language.jpg -last-modified: 2020-10-11 -layout: default -tags: -- factorial -- lisp -title: Factorial in Lisp -title1: Factorial -title2: in Lisp ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(defun factorial (n) - (if (= n 0) - 1 - (* n (factorial (- n 1))) ) ) - -(defun maybe-pos-int (input) - (cond - ((null input) nil) - ((string= input "") nil) - ((every #'digit-char-p input) (parse-integer input)) - (t nil))) - -(defparameter num (maybe-pos-int (cadr *posix-argv*))) -(cond - ((null num) (write-line "Usage: please input a non-negative integer")) - (t (print (factorial num))) -) -``` - -{% endraw %} - -Factorial in [Lisp](/languages/lisp) was written by: - -- Parker Johansen -- Renato - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/lua/index.md b/docs/projects/factorial/lua/index.md deleted file mode 100644 index 09f04f38de..0000000000 --- a/docs/projects/factorial/lua/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Matt Wiley -date: 2019-10-10 -featured-image: factorial-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- factorial -- lua -title: Factorial in Lua -title1: Factorial -title2: in Lua ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua - --- --- Calculate the factorial --- -factorial = function(num) - product = 1 - if num > 1 - then - for i = 2, num - do - product = product * i - end - end - return product -end - --- --- Main executable logic --- -main = function(input) - maxInput = 20 - usage = "Usage: please input a non-negative integer" - - if not (input == nil or input == "") - then - inputValidation = input:gsub('[0-9]','') - if inputValidation:len() == 0 - then - inputNum = tonumber(input) - if inputNum > maxInput - then - print('Input of ' .. inputNum .. ' is too large to calculate a factorial for. Max input is ' .. maxInput .. '.') - else - print(factorial(tonumber(input))) - end - else - print(usage) - end - else - print(usage) - end - -end - --- Run the script -main(arg[1]) - -``` - -{% endraw %} - -Factorial in [Lua](/languages/lua) was written by: - -- Jeremy Grifski -- Matt Wiley - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/m4/index.md b/docs/projects/factorial/m4/index.md deleted file mode 100644 index b6e67bb7b4..0000000000 --- a/docs/projects/factorial/m4/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-11 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-08-11 -layout: default -tags: -- factorial -- m4 -title: Factorial in m4 -title1: Factorial -title2: in m4 ---- - - - -Welcome to the [Factorial](/projects/factorial) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please input a non-negative integer -m4exit(`1')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl factorial(n) -define(`factorial', `ifelse(eval(`$1' <= 1), 1, 1, `eval($1 * factorial(decr($1)))')') -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !is_valid(ARGV1)), 1, `show_usage()')dnl -ifelse(eval(ARGV1 < 0), 1, `show_usage()', `factorial(ARGV1)') - -``` - -{% endraw %} - -Factorial in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/mathematica/index.md b/docs/projects/factorial/mathematica/index.md deleted file mode 100644 index 56e749d15e..0000000000 --- a/docs/projects/factorial/mathematica/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- factorial -- mathematica -title: Factorial in Mathematica -title1: Factorial in -title2: Mathematica ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The Mathematica built-in Factorial essentially provides the required behavior; -so the only code needed is the 'user interface' to make it look a little more -like a Unix command-line tool: *) - -factorialMain = Catch[ - (* convert string to integer, or throw *) - If[ - StringMatchQ[#, DigitCharacter ..], - FromDigits[#]!, - Throw["Usage: please input a non-negative integer"]]] &; - - -(* Valid Tests *) - -Print /@ factorialMain /@ {"0", "1", "4", "8", "10"}; - -(* Note that Mathematica (as far as I know) doesn't impose an upper limit on computations: *) -factorialMain["10000"] - - -(* Invalid Tests *) - -factorialMain[""] -factorialMain["asdf"] -factorialMain["-1"] - -``` - -{% endraw %} - -Factorial in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/nim/index.md b/docs/projects/factorial/nim/index.md deleted file mode 100644 index 456228fc55..0000000000 --- a/docs/projects/factorial/nim/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- allenres -date: 2025-10-29 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-10-29 -layout: default -tags: -- factorial -- nim -title: Factorial in Nim -title1: Factorial -title2: in Nim ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Nim](/languages/nim) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nim -#[ - Factorial in Nim - This program calculates the factorial of a non-negative integer. -]# - -import os -import strutils - -const UsageMessage = "Usage: please input a non-negative integer" - -proc factorial(n: int): int = - # Calculates the factorial of n (n!). - if n == 0: - return 1 - - var result = 1 - for i in 1..n: - result *= i - - return result - -# The main execution block: -block: - # Check 1: No input argument provided. - if paramCount() == 0: - quit(UsageMessage, 1) - - let inputStr = paramStr(1) - - # Check 2: Invalid Input (Empty String or Not a Number) - var n: int - try: - n = parseInt(inputStr) - except: - quit(UsageMessage, 1) - - # Check 3: Invalid Input (Negative Number) - if n < 0: - quit(UsageMessage, 1) - - # Print the calculated result. - echo factorial(n) - -``` - -{% endraw %} - -Factorial in [Nim](/languages/nim) was written by: - -- allenres - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/objective-c/index.md b/docs/projects/factorial/objective-c/index.md deleted file mode 100644 index 49aba9a5b0..0000000000 --- a/docs/projects/factorial/objective-c/index.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -authors: -- niftycode -- rzuckerm -- Ștefan-Iulian Alecu -date: 2020-10-01 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- factorial -- objective-c -title: Factorial in Objective-C -title1: Factorial in -title2: Objective-C ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -@interface NSString (Parsing) -@property(nonatomic, readonly, nullable) NSNumber* strictIntegerNumber; -@end - -@implementation NSString (Parsing) - -- (NSNumber*)strictIntegerNumber { - NSString* trimmed = [self - stringByTrimmingCharactersInSet:NSCharacterSet - .whitespaceAndNewlineCharacterSet]; - if (trimmed.length == 0) return nil; - - NSInteger offset = 0; - if ([trimmed hasPrefix:@"-"] || [trimmed hasPrefix:@"+"]) { - offset = 1; - } - - if (trimmed.length <= offset) return nil; - - NSString* core = [trimmed substringFromIndex:offset]; - NSRange invalidRange = - [core rangeOfCharacterFromSet:NSCharacterSet.decimalDigitCharacterSet - .invertedSet]; - - if (invalidRange.location != NSNotFound) { - return nil; - } - - return @(trimmed.longLongValue); -} - -@end - -static unsigned long long Factorial(NSUInteger n) { - if (n == 0 || n == 1) return 1; - - unsigned long long result = 1; - for (NSUInteger i = 2; i <= n; i++) { - result *= i; - } - - return result; -} - -int main(int argc, const char* argv[]) { - @autoreleasepool { - const char* usage = "Usage: please input a non-negative integer"; - if (argc < 2) { - puts(usage); - return 1; - } - - NSNumber* number = @(argv[1]).strictIntegerNumber; - - if (!number || number.integerValue < 0) { - puts(usage); - return 1; - } - - printf("%llu\n", Factorial(number.unsignedIntegerValue)); - } - return 0; -} -``` - -{% endraw %} - -Factorial in [Objective-C](/languages/objective-c) was written by: - -- niftycode -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/ocaml/index.md b/docs/projects/factorial/ocaml/index.md deleted file mode 100644 index 318d58f99f..0000000000 --- a/docs/projects/factorial/ocaml/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-17 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- factorial -- ocaml -title: Factorial in OCaml -title1: Factorial -title2: in OCaml ---- - - - -Welcome to the [Factorial](/projects/factorial) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let factorial n = - (* Use accumulator so OCaml can do tail call recursion *) - let rec helper acc n = - match n with 0 | 1 -> acc | n -> helper (acc * n) (n - 1) - in - helper 1 n - -let parse_args argv = - match argv with [| _; n |] -> int_of_string_opt n | _ -> None - -let () = - print_endline - (match parse_args Sys.argv with - | Some num when num >= 0 -> num |> factorial |> string_of_int - | _ -> "Usage: please input a non-negative integer") - -``` - -{% endraw %} - -Factorial in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/octave/index.md b/docs/projects/factorial/octave/index.md deleted file mode 100644 index b132d2bdf2..0000000000 --- a/docs/projects/factorial/octave/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- factorial -- octave -title: Factorial in Octave -title1: Factorial -title2: in Octave ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function factorial() - usage = 'Usage: please input a non-negative integer'; - arg_list = argv(); - nargin = length(arg_list); - if nargin == 0 - disp(usage); - return; - end - - n = str2num(arg_list{1}); - if length(n) ~= 1 || mod(n, 1) ~= 0 || n < 0 - disp(usage); - return; - end - - x = 1; - for i = 1:n - x = x * i; - end - - disp(x); -end - -``` - -{% endraw %} - -Factorial in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/pascal/index.md b/docs/projects/factorial/pascal/index.md deleted file mode 100644 index bfbdd89c8f..0000000000 --- a/docs/projects/factorial/pascal/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- Mr Anand Somashekhara Rao Somavarapete -date: 2023-10-05 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-10-05 -layout: default -tags: -- factorial -- pascal -title: Factorial in Pascal -title1: Factorial -title2: in Pascal ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program factorial_calculate(input, output, stdErr); -(* Read a number from Commandline, Return it's factorial value -Cardinal, int-64 and qWord are the relevant data type to store long int in pascal. -With Cardinal data type, maximum factorial that can be computed is 34, 4926277576697053184 -With int-64 data type, maximum factorial that can be computed is 44, 2673996885588443136 -With qWord data type, maximum factorial that can be computed is 65, 9223372036854775808 -*) -var - buf: String; -(* input_value, factorial, check:qWord;*) -i, check: integer; -input_value, factorial_value: qWord; -begin - buf:= paramStr(1); - Val(buf, input_value, check); - if check <> 0 - then - writeln('Usage: please input a non-negative integer') - else - if input_value < 0 - then - writeln('Usage: please input a non-negative integer') - else - begin - if (input_value = 0) then - writeln('1') - else - begin - factorial_value := 1; - for i := 1 to input_value do - begin - factorial_value := factorial_value * i; - end; - writeln(factorial_value); - end; - - end; -end. - -``` - -{% endraw %} - -Factorial in [Pascal](/languages/pascal) was written by: - -- Mr Anand Somashekhara Rao Somavarapete - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/perl/index.md b/docs/projects/factorial/perl/index.md deleted file mode 100644 index 25eb2a8e07..0000000000 --- a/docs/projects/factorial/perl/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Gabriela Kandová -- Ștefan-Iulian Alecu -date: 2019-10-14 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- factorial -- perl -title: Factorial in Perl -title1: Factorial -title2: in Perl ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -sub usage { - say "Usage: please input a non-negative integer"; - exit; -} - -my ($number) = @ARGV; -usage() unless defined $number && $number =~ /\A\d+\z/; - -my $factorial = 1; -$factorial *= $_ for 2 .. $number; - -say $factorial; - -``` - -{% endraw %} - -Factorial in [Perl](/languages/perl) was written by: - -- Gabriela Kandová -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/php/index.md b/docs/projects/factorial/php/index.md deleted file mode 100644 index 31591a2bec..0000000000 --- a/docs/projects/factorial/php/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Italo Sousa -- Jeremy Grifski -date: 2019-10-10 -featured-image: factorial-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- factorial -- php -title: Factorial in PHP -title1: Factorial -title2: in PHP ---- - - - -Welcome to the [Factorial](/projects/factorial) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php -= 1; $x--) { - $factorial = $factorial * $x; -} - -echo ("$factorial\n"); - -``` - -{% endraw %} - -Factorial in [PHP](/languages/php) was written by: - -- Italo Sousa -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/powershell/index.md b/docs/projects/factorial/powershell/index.md deleted file mode 100644 index e694f6fb3d..0000000000 --- a/docs/projects/factorial/powershell/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-05-20 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-05-20 -layout: default -tags: -- factorial -- powershell -title: Factorial in PowerShell -title1: Factorial in -title2: PowerShell ---- - - - -Welcome to the [Factorial](/projects/factorial) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please input a non-negative integer" - Exit 1 -} - -function Get-Factorial([int]$Value) { - $Product = 1 - if ($Value -gt 0) { - 1..$Value | ForEach-Object { $Product *= $_ } - } - - $Product -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $Value = [int]::Parse($args[0]) -} catch { - Show-Usage -} - -if ($Value -lt 0) { - Show-Usage -} - -Write-Host (Get-Factorial $Value) - -``` - -{% endraw %} - -Factorial in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/python/index.md b/docs/projects/factorial/python/index.md deleted file mode 100644 index 908a8c2245..0000000000 --- a/docs/projects/factorial/python/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -authors: -- Anuj Singh -- Bharath -- Jeremy Grifski -- Parker Johansen -- rzuckerm -date: 2018-12-22 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- factorial -- python -title: Factorial in Python -title1: Factorial -title2: in Python ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def factorial(n): - if n <= 0: - return 1 - return n * factorial(n - 1) - - -def exit_with_error(msg=None): - msg = msg or 'Usage: please input a non-negative integer' - print(msg) - sys.exit(1) - - -def main(args): - try: - n = int(args[0]) - if n < 0: - exit_with_error() - elif n >= 996: - msg = f'{n}! is out of the reasonable bounds for calculation' - exit_with_error(msg) - print(factorial(n)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Factorial in [Python](/languages/python) was written by: - -- Bharath -- Jeremy Grifski -- Parker Johansen - -This article was written by: - -- Anuj Singh -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's look at the -code for [factorial.py](https://github.com/TheRenegadeCoder/sample-programs/blob/master/archive/p/python/factorial.py). - - -### The Main Function - -Let us breakdown the code in smaller parts, - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` -This bit of code checks to see if this is the `main` module run. If true then it calls the `main` function and passes user input to it. In this case the user input would be a number like `0` or `1` or `50` or `n` (`0<=n<996`). - -```python -def main(args): - try: - n = int(args[0]) - if n < 0: - exit_with_error() - elif n >= 996: - msg = f'{n}! is out of the reasonable bounds for calculation' - exit_with_error(msg) - print(factorial(n)) - except (IndexError, ValueError): - exit_with_error() -``` - -This is the `main` function of this file. It parses the input into an integer, then calls our `factorial` function (and prints the results). It also deals with any errors which arise when the input `n` is such that it violates the property: (`0<=n<996`), i.e. `n` is greater than equal to `0` and less than `996`. - -### Throw Errors - -```python -def exit_with_error(msg=None): - msg = msg or 'Usage: please input a non-negative integer' - print(msg) - sys.exit(1) -``` - -This function prints a message if given (else default) and then exits the script with an error, `sys.exit(1)`. If any non-zero value is returned then the program didn't complete properly. This function is called if the user input is either less than zero or greater than equal to 996. - -### Factorial - -```python -def factorial(n): - if n <= 0: - return 1 - return n * factorial (n - 1) -``` - -Finally, the real deal. This function takes a positive integer (less than 996) and returns the factorial of that number. This function `factorial` is a recursive function that calls itself repeatedly while decreasing the input parameter by one on each subsequent call, until the base case is reached -(`n <= 0`). - -Once the base case is reached the call-stack unfolds itself propagating the results to the subsequent calling function, which in this case will be the same function itself. - -For example, if `3` is the input: - -* First we compare, if 3 <= 0 -* False -* return 3 * factorial(3-1) -* Call `factorial(2)` - -Now, for `2` as the input: - -* First we compare, if 2 <= 0 -* False -* return 2 * factorial(2-1) -> meanwhile the original call would look like: -> return 3 * 2 * factorial(2-1) -* Call `factorial(1)` - -Now, for `1` as the input: -* First we compare, if 1 <= 0 -* False -* return 1 * factorial(1-1) -> meanwhile the original call would look like: -> return 3 * 2 * 1 * factorial(1-1) -* Call `factorial(0)` - -Now, for `0` as the input: -* First we compare, if 0 <= 0 -* True -* return 1 - -Since we reached the base case, now we calculate the the values while moving up towards the original function call. - - factorial(0) = 1 (base-case) - - factorial(1) = 1 * factorial(1-1) = 1 * factorial(0) = 1 * 1 = 1 - - factorial(2) = 2 * factorial(2-1) = 2 * factorial(1) = 2 * 1 = 2 - - factorial(3) = 3 * factorial(3-1) = 3 * factorial(2) = 3 * 2 = 6 - - -## How to Run the Solution - -If you want to run this program, you can download a copy of [Factorial in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/master/archive/p/python/factorial.py). - -Next, make sure you have the latest Python interpreter (latest stable version of Python 3 will do). - -Finally, open a terminal in the directory of the downloaded file and run the following command: - -`python factorial.py 3` - -Alternatively, copy the solution into an online [Python interpreter](https://colab.research.google.com) and hit run. diff --git a/docs/projects/factorial/r/index.md b/docs/projects/factorial/r/index.md deleted file mode 100644 index 3c0fa69b6e..0000000000 --- a/docs/projects/factorial/r/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Veena ManikPrabhu -date: 2020-10-19 -featured-image: factorial-in-every-language.jpg -last-modified: 2020-10-19 -layout: default -tags: -- factorial -- r -title: Factorial in R -title1: Factorial -title2: in R ---- - - - -Welcome to the [Factorial](/projects/factorial) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -args<-commandArgs(TRUE) -if(length(args) > 0){ - a = args[1] - # Check if String or numeral only, .. - numbers_only <- function(a) !grepl("\\D", a) - if(numbers_only(a) == TRUE){ - if(a == 0){ - cat("1") - }else if (a > 0){ - fact = 1 - for(i in 1:a){ - fact = fact * i - } - cat(fact) - # else a < 0 - } else{ - cat("Usage: please input a non-negative integer") - } - # Negative Input - }else{ - cat("Usage: please input a non-negative integer") - } -# Empty Command Line Param -}else{ - cat("Usage: please input a non-negative integer") - } - -``` - -{% endraw %} - -Factorial in [R](/languages/r) was written by: - -- Veena ManikPrabhu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/ruby/index.md b/docs/projects/factorial/ruby/index.md deleted file mode 100644 index aed04f311b..0000000000 --- a/docs/projects/factorial/ruby/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- factorial -- ruby -title: Factorial in Ruby -title1: Factorial -title2: in Ruby ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def usage! - abort("Usage: please input a non-negative integer") -end - -input = ARGV.first - -usage! if input.nil? || input.strip.empty? - -begin - num = Integer(input) -rescue ArgumentError - usage! -end - -usage! if num.negative? - -puts (1..num).reduce(1, :*) - -``` - -{% endraw %} - -Factorial in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/rust/index.md b/docs/projects/factorial/rust/index.md deleted file mode 100644 index ed74679983..0000000000 --- a/docs/projects/factorial/rust/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- rzuckerm -date: 2019-10-31 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- factorial -- rust -title: Factorial in Rust -title1: Factorial -title2: in Rust ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -// Requirement https://sample-programs.therenegadecoder.com/projects/factorial/ -// Accept a number on command line and print it's factorial -// Works till factorial 34, which is 39 digits, ... -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please input a non-negative integer"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn main() { - let mut args = args().skip(1); - - // confirm positive integer is passed as command-line argument - let mut input_num: u32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - let mut n = input_num as u128; - let mut result = 1; - while n > 0 { - result *= n; - n -= 1; - } - println!("{result}"); -} - -``` - -{% endraw %} - -Factorial in [Rust](/languages/rust) was written by: - -- Mallikarjuna S J -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/scala/index.md b/docs/projects/factorial/scala/index.md deleted file mode 100644 index d01662d349..0000000000 --- a/docs/projects/factorial/scala/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- rzuckerm -- Ștefan-Iulian Alecu -date: 2023-05-15 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- factorial -- scala -title: Factorial in Scala -title1: Factorial -title2: in Scala ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -import scala.util.Try - -object Factorial: - private val usage = "Usage: please input a non-negative integer" - - def main(args: Array[String]): Unit = - val result = - args.headOption - .flatMap(a => Try(a.toInt).toOption) - .filter(_ >= 0) - .map(factorial) - - result match - case Some(value) => println(value) - case None => println(usage) - - private def factorial(n: Int): Int = - (1 to n).product -``` - -{% endraw %} - -Factorial in [Scala](/languages/scala) was written by: - -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/swift/index.md b/docs/projects/factorial/swift/index.md deleted file mode 100644 index 0eb10399ab..0000000000 --- a/docs/projects/factorial/swift/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- factorial -- swift -title: Factorial in Swift -title1: Factorial -title2: in Swift ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please input a non-negative integer - """ - -extension FixedWidthInteger { - var factorial: Self? { - guard self >= 0 else { return nil } - guard self > 1 else { return 1 } - - var result: Self = 1 - - for i in 2...self { - let (value, overflow) = result.multipliedReportingOverflow(by: i) - if overflow { return nil } - result = value - } - - return result - } -} - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -guard - let raw = CommandLine.arguments.dropFirst().first?.trimmed, - let n = Int(raw), - let result = n.factorial -else { - print(usage) - exit(1) -} - -print(result) - -``` - -{% endraw %} - -Factorial in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/tcl/index.md b/docs/projects/factorial/tcl/index.md deleted file mode 100644 index 9c25168672..0000000000 --- a/docs/projects/factorial/tcl/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-10-08 -layout: default -tags: -- factorial -- tcl -title: Factorial in Tcl -title1: Factorial -title2: in Tcl ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require math - -proc usage {} { - puts "Usage: please input a non-negative integer" - exit 1 -} - -if {$argc != 1} { usage } - -set n [lindex $argv 0] -if {![string is integer -strict $n] || $n < 0} { usage } - -puts [::math::factorial $n] - -``` - -{% endraw %} - -Factorial in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/ti-basic/index.md b/docs/projects/factorial/ti-basic/index.md deleted file mode 100644 index d55442c140..0000000000 --- a/docs/projects/factorial/ti-basic/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-03 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-02-03 -layout: default -tags: -- factorial -- ti-basic -title: Factorial in TI-BASIC -title1: Factorial -title2: in TI-BASIC ---- - - - -Welcome to the [Factorial](/projects/factorial) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -"0123456789"->Str2 -length(Str1)->L -L<1->E -0->D -0->V -1->N -1->S -While E=0 and N<=L - sub(Str1,N,1)->C - inString(Str2,C)-1->K - If C="+" or C="-" - Then - D>0->E - If C="-" - Then 0-S->S - End - Else - K<0->E - D+1->D - V*10+K*S->V - End - N+1->N -End -If E or D<1 or V<0 Then Disp "Usage: please input a non-negative integer" -Else Disp V! -End - -``` - -{% endraw %} - -Factorial in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/typescript/index.md b/docs/projects/factorial/typescript/index.md deleted file mode 100644 index cb3cf083e9..0000000000 --- a/docs/projects/factorial/typescript/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2023-10-02 -featured-image: factorial-in-every-language.jpg -last-modified: 2023-10-02 -layout: default -tags: -- factorial -- typescript -title: Factorial in TypeScript -title1: Factorial in -title2: TypeScript ---- - - - -Welcome to the [Factorial](/projects/factorial) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -let error_msg: string = "Usage: please input a non-negative integer" -let num_str: string = (process.argv.length == 3) ? process.argv[2] : "" -let num: number = parseInt(num_str); -if (isNaN(num) || num < 0) { - console.log(error_msg); - process.exit(1); -} -let factorial: number = 1; -for (let i = 1; i <= num; i++) { - factorial *= i; -} -console.log(factorial); - -``` - -{% endraw %} - -Factorial in [TypeScript](/languages/typescript) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/v/index.md b/docs/projects/factorial/v/index.md deleted file mode 100644 index 0e8accc42f..0000000000 --- a/docs/projects/factorial/v/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Zia -date: 2024-12-16 -featured-image: factorial-in-every-language.jpg -last-modified: 2024-12-16 -layout: default -tags: -- factorial -- v -title: Factorial in V -title1: Factorial -title2: in V ---- - - - -Welcome to the [Factorial](/projects/factorial) in [V](/languages/v) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```v -module main - -import os -import strconv - -fn factorial(n u64) u64 { - return match true { - n <= 1 { 1 } - else { n * factorial(n-1) } - } -} - -fn usage() { - println("Usage: please input a non-negative integer") - exit(1) -} - -fn main() { - if os.args.len != 2 { - usage() - } - - n := strconv.atoi(os.args[1]) or { - usage() - exit(1) - } - if n < 0 { - usage() - } - println(factorial(u64(n))) -} - -``` - -{% endraw %} - -Factorial in [V](/languages/v) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/visual-basic/index.md b/docs/projects/factorial/visual-basic/index.md deleted file mode 100644 index a4ee64098d..0000000000 --- a/docs/projects/factorial/visual-basic/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: factorial-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- factorial -- visual-basic -title: Factorial in Visual Basic -title1: Factorial in -title2: Visual Basic ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System.Numerics - -Module Factorial - - Private Function Fact(n As BigInteger) As BigInteger - If n <= 1 Then - Return 1 - End If - - Return n * Fact(n - 1) - End Function - - - Public Sub Main(args As String()) - - If args.Length = 0 Then - ShowUsage() - Return - End If - - Dim n As BigInteger - - If Not BigInteger.TryParse(args(0), n) Then - ShowUsage() - Return - End If - - If n < 0 Then - ShowUsage() - Return - End If - - If n > 4550 Then - Console.WriteLine($"{n}! is out of the reasonable bounds for calculation.") - Environment.Exit(1) - End If - - Dim result = Fact(n) - Console.WriteLine(result) - - End Sub - - - Private Sub ShowUsage() - Console.WriteLine("Usage: please input a non-negative integer") - Environment.Exit(1) - End Sub - -End Module -``` - -{% endraw %} - -Factorial in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/factorial/wren/index.md b/docs/projects/factorial/wren/index.md deleted file mode 100644 index 0c56951aee..0000000000 --- a/docs/projects/factorial/wren/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-21 -featured-image: factorial-in-every-language.jpg -last-modified: 2025-01-21 -layout: default -tags: -- factorial -- wren -title: Factorial in Wren -title1: Factorial -title2: in Wren ---- - - - -Welcome to the [Factorial](/projects/factorial) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -import "os" for Process - -var args = Process.arguments - -if (args.count < 1 || args[0].count < 1) { - System.print("Usage: please input a non-negative integer") - Fiber.suspend() -} - -var n = Num.fromString(args[0]) -if (n == null || n < 0) { - System.print("Usage: please input a non-negative integer") - Fiber.suspend() -} - -if (n <= 1) { - System.print(1) - Fiber.suspend() -} - -var res = 1 -for (i in 1..n) { - res = res * i -} - -System.print(res) - -``` - -{% endraw %} - -Factorial in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/ada/index.md b/docs/projects/fibonacci/ada/index.md deleted file mode 100644 index 22273df2de..0000000000 --- a/docs/projects/fibonacci/ada/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-10 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-10 -layout: default -tags: -- ada -- fibonacci -title: Fibonacci in Ada -title1: Fibonacci -title2: in Ada ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; - -procedure Fibonacci is - - procedure Print_Usage is - begin - Put_Line - ("Usage: please input the count of fibonacci numbers to output"); - end Print_Usage; - - function Img (N : Natural) return String - is (Trim (Natural'Image (N), Ada.Strings.Left)); - -begin - if Argument_Count /= 1 then - Print_Usage; - return; - end if; - - declare - N : Natural; - begin - begin - N := Natural'Value (Argument (1)); - exception - when Constraint_Error => - Print_Usage; - return; - end; - - if N = 0 then - return; - end if; - - declare - A, B : Natural := 1; - Next : Natural; - begin - for I in 1 .. N loop - Put_Line (Img (I) & ": " & Img (A)); - - Next := A + B; - A := B; - B := Next; - end loop; - end; - end; - -end Fibonacci; - -``` - -{% endraw %} - -Fibonacci in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/algol60/index.md b/docs/projects/fibonacci/algol60/index.md deleted file mode 100644 index eed09d8271..0000000000 --- a/docs/projects/fibonacci/algol60/index.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-20 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- algol60 -- fibonacci -title: Fibonacci in ALGOL 60 -title1: Fibonacci -title2: in ALGOL 60 ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please input the count of fibonacci numbers to output\n"); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - null byte maps to 17 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch); - integer result, ch; - begin - boolean valid; - integer s; - - result := 0; - valid := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment Ignore characters until end of argument. Indicate invalid - if not whitespace; - ignoreloop: - if ch != -1 then - begin - if ch != 12 then valid := false; - ch := indigit; - goto ignoreloop - end; - - inValidInteger := valid - end inValidInteger; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - procedure fibonacci(n); - value n; - integer n; - begin - integer a, b, c, i; - - a := 0; - b := 1; - for i := 1 step 1 until n do - begin - c := a + b; - a := b; - b := c; - outIntegerNoSpace(i); - outstring(1, ": "); - outIntegerNoSpace(a); - outstring(1, "\n") - end - end fibonacci; - - integer argc, result, ch; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get integer value from 1st argument. Exit if invalid or - negative; - if !inValidInteger(result, ch) | result < 0 then usage; - - comment Output Fibonacci values; - fibonacci(result) -end - -``` - -{% endraw %} - -Fibonacci in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/algol68/index.md b/docs/projects/fibonacci/algol68/index.md deleted file mode 100644 index c512838027..0000000000 --- a/docs/projects/fibonacci/algol68/index.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-21 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- fibonacci -title: Fibonacci in ALGOL 68 -title1: Fibonacci -title2: in ALGOL 68 ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC usage = VOID: printf(($gl$, "Usage: please input the count of fibonacci numbers to output")); - -COMMENT -fib(n) = fib(n - 1) + fib(n - 2) -where: -- fib(0) = 0 -- fib(1) = 1 -COMMENT -MODE FIBSTATE = STRUCT(INT prev, INT result); -PROC init fib = FIBSTATE: FIBSTATE(0, 1); -OP FIB = (FIBSTATE state) FIBSTATE: (result OF state, prev OF state + result OF state); -OP FIBRESULT = (FIBSTATE state) INT: prev OF state; - -PROC show fibonacci values = (INT n) VOID: -( - # Initialize Fibonacci state # - FIBSTATE state := init fib; - - # Update Fibonacci state and show results for requested number of values # - FOR k TO n - DO - state := FIB state; - printf(($g": "gl$, whole(k, 0), whole(FIBRESULT state, 0))) - OD -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINT_RESULT result := parse int(s); - -# If invalid or extra characters, exit # -INT n := value OF result; -IF NOT (valid OF result) OR (leftover OF result) /= "" -THEN - usage; - stop -FI; - -# Show requested number of Fibonacci values # -show fibonacci values(n) - -``` - -{% endraw %} - -Fibonacci in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/awk/index.md b/docs/projects/fibonacci/awk/index.md deleted file mode 100644 index 4333ab38a8..0000000000 --- a/docs/projects/fibonacci/awk/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-14 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- fibonacci -title: Fibonacci in AWK -title1: Fibonacci -title2: in AWK ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please input the count of fibonacci numbers to output" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function fibonacci(n, i, a, b, c) { - a = 0 - b = 1 - for (i = 1; i <= n; i++) { - c = a + b - a = b - b = c - printf("%d: %d\n", i, a) - } -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - result = str_to_number(ARGV[1]) - if (result == "ERROR" || result < 0) { - usage() - } - - fibonacci(result) -} - -``` - -{% endraw %} - -Fibonacci in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/bash/index.md b/docs/projects/fibonacci/bash/index.md deleted file mode 100644 index 23c15628fb..0000000000 --- a/docs/projects/fibonacci/bash/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-10-26 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2019-04-07 -layout: default -tags: -- bash -- fibonacci -title: Fibonacci in Bash -title1: Fibonacci -title2: in Bash ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -count=$1 - -[[ $count =~ ^[0-9]+$ ]] || { echo "Usage: please input the count of fibonacci numbers to output"; exit 1; } - -n=1 -n_minus_1=1 -[[ $count < 1 ]] && exit 0 - -echo "1: 1" -for i in $(seq 2 $count); do - echo "$i: $n" - tmp=$n - n=$[$n+$n_minus_1] - n_minus_1=$tmp -done - -``` - -{% endraw %} - -Fibonacci in [Bash](/languages/bash) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/beef/index.md b/docs/projects/fibonacci/beef/index.md deleted file mode 100644 index 4c924210dc..0000000000 --- a/docs/projects/fibonacci/beef/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-22 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- fibonacci -title: Fibonacci in Beef -title1: Fibonacci -title2: in Beef ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace Fibonacci; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please input the count of fibonacci numbers to output"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static void Fibonacci(int32 n) - { - uint64 first = 0; - uint64 second = 1; - for (int i in 1...n) - { - second += first; - first = second - first; - Console.WriteLine($"{i}: {first}"); - } - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - int32 val = 0; - switch (ParseInt(args[0])) - { - case .Ok(out val): - case .Err: - Usage(); - } - - Fibonacci(val); - return 0; - } -} - -``` - -{% endraw %} - -Fibonacci in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/boo/index.md b/docs/projects/fibonacci/boo/index.md deleted file mode 100644 index 603fbdab59..0000000000 --- a/docs/projects/fibonacci/boo/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- rzuckerm -- Subhayu Roy -date: 2020-10-02 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-11-13 -layout: default -tags: -- boo -- fibonacci -title: Fibonacci in Boo -title1: Fibonacci -title2: in Boo ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Boo](/languages/boo) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```boo -import System - -def usage(): - print("Usage: please input the count of fibonacci numbers to output") - Environment.Exit(0) - -def fib(n): - a, b = 0L, 1L # The 'L's make the numbers double word length (typically 64 bits) - for index in range(n): - yield index + 1, b - a, b = b, a + b - -# Print the first n numbers in the series: -try: - n = int.Parse(argv[0]) - for index as int, element in fib(n): - print("${index}: ${element}") -except _ as IndexOutOfRangeException: - usage() -except _ as FormatException: - usage() - -``` - -{% endraw %} - -Fibonacci in [Boo](/languages/boo) was written by: - -- rzuckerm -- Subhayu Roy - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/c-plus-plus/index.md b/docs/projects/fibonacci/c-plus-plus/index.md deleted file mode 100644 index 6ceb5bf995..0000000000 --- a/docs/projects/fibonacci/c-plus-plus/index.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Marius -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-10-06 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- fibonacci -title: Fibonacci in C++ -title1: Fibonacci -title2: in C++ ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include - -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << "Usage: please input the count of fibonacci numbers to output\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - s = trim(s); - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -auto fibonacci_sequence() { - return views::iota(0) | views::transform([a = 1LL, b = 1LL](auto) mutable { - auto out = a; - auto next = a + b; - a = b; - b = next; - return out; - }); -} - -int main(int argc, char* argv[]) { - if (argc < 2) usage(); - - if (auto n_opt = to_int(argv[1]); !n_opt || *n_opt < 0) { - usage(); - } else { - const int n = *n_opt; - - int index = 1; - for (const auto value : fibonacci_sequence() | views::take(n)) { - std::cout << std::format("{}: {}\n", index++, value); - } - } -} - -``` - -{% endraw %} - -Fibonacci in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Marius -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/c-sharp/index.md b/docs/projects/fibonacci/c-sharp/index.md deleted file mode 100644 index 1ea2f76f6a..0000000000 --- a/docs/projects/fibonacci/c-sharp/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Marius -- Ștefan-Iulian Alecu -date: 2018-10-02 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- fibonacci -title: Fibonacci in C# -title1: Fibonacci -title2: in C# ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var input] || !int.TryParse(input, out int n) || n < 0) -{ - Console.Error.WriteLine("Usage: please input the count of fibonacci numbers to output"); - return; -} - -int a = 1, b = 1; - -for (int i = 1; i <= n; i++) -{ - Console.WriteLine($"{i}: {a}"); - (a, b) = (b, a + b); -} -``` - -{% endraw %} - -Fibonacci in [C#](/languages/c-sharp) was written by: - -- Marius -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/c/index.md b/docs/projects/fibonacci/c/index.md deleted file mode 100644 index ce8fc279e6..0000000000 --- a/docs/projects/fibonacci/c/index.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2018-10-04 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- fibonacci -title: Fibonacci in C -title1: Fibonacci -title2: in C ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include - -/* - * This limit is chosen because fib(93) is the first number that is - * still small enough to fit into a 64 bit integer. - */ -#define LIMIT 93 - -void fibonacci(int n) -{ - unsigned long long first = 0; - unsigned long long second = 1; - unsigned long long result = 0; - - for (int i = 1; i <= n; i++) - { - result = first + second; - first = second; - second = result; - printf("%d: %llu\n", i, first); - } -} - -int main(int argc, char **argv) -{ - uintmax_t n; - - if (argc < 2 || strcmp(argv[1], "") == 0) - { - fprintf( - stderr, - "Usage: please input the count of fibonacci numbers to output\n"); - return 1; - } - - errno = 0; - n = strtoumax(argv[1], NULL, 10); - if (n == 0 && strcmp(argv[1], "0") != 0 - || (n == UINTMAX_MAX && errno == ERANGE)) - { - fprintf( - stderr, - "Usage: please input the count of fibonacci numbers to output\n"); - return 1; - } - - if (n > LIMIT) - { - fprintf(stderr, "n cannot be larger than %d\n", LIMIT); - return 1; - } - - fibonacci(n); - return 0; -} - -``` - -{% endraw %} - -Fibonacci in [C](/languages/c) was written by: - -- Christoph Böhmwalder -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/cobol/index.md b/docs/projects/fibonacci/cobol/index.md deleted file mode 100644 index 21f38d1956..0000000000 --- a/docs/projects/fibonacci/cobol/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- fibonacci -title: Fibonacci in COBOL -title1: Fibonacci -title2: in COBOL ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. fibonacci. - -data division. -working-storage section. -01 ws-arg pic x(100). -01 ws-n pic 9(9) value 0. -01 ws-i pic 9(9) value 0. - -01 ws-i-disp pic z(9). -01 ws-f-disp pic z(18). - -01 ws-f1 pic 9(18) value 1. -01 ws-f2 pic 9(18) value 1. -01 ws-fnext pic 9(18) value 0. - -procedure division. -main. - accept ws-arg from command-line - - if ws-arg = spaces - perform show-usage - stop run - end-if - - move function numval(ws-arg) to ws-n - - if ws-n = 0 and function trim(ws-arg) not = "0" - perform show-usage - stop run - end-if - - if ws-n = 0 - stop run - end-if - - display "1: 1" - if ws-n = 1 - stop run - end-if - - display "2: 1" - - perform varying ws-i from 3 by 1 until ws-i > ws-n - compute ws-fnext = ws-f1 + ws-f2 - - move ws-i to ws-i-disp - move ws-fnext to ws-f-disp - - display function trim(ws-i-disp) ": " - function trim(ws-f-disp) - - move ws-f2 to ws-f1 - move ws-fnext to ws-f2 - end-perform - - stop run. - -show-usage. - display "Usage: please input the count of fibonacci numbers to output". -``` - -{% endraw %} - -Fibonacci in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/commodore-basic/index.md b/docs/projects/fibonacci/commodore-basic/index.md deleted file mode 100644 index 2bcfffa9da..0000000000 --- a/docs/projects/fibonacci/commodore-basic/index.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- fibonacci -title: Fibonacci in Commodore BASIC -title1: Fibonacci in -title2: Commodore BASIC ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input N -10 GOSUB 1000 -20 IF V = 0 OR C >=0 OR NR < 0 THEN GOTO 140: REM invalid or not end character -30 N = NR -40 A = 0 -50 B = 1 -60 IF N < 1 THEN GOTO 130 -70 FOR K = 1 TO N -80 C = A + B -90 A = B -100 B = C -110 PRINT MID$(STR$(K), 2); ": "; MID$(STR$(A), 2) -120 NEXT K -130 END -140 PRINT "Usage: please input the count of fibonacci numbers to output" -150 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN - -``` - -{% endraw %} - -Fibonacci in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/dart/index.md b/docs/projects/fibonacci/dart/index.md deleted file mode 100644 index 8e4801e1ad..0000000000 --- a/docs/projects/fibonacci/dart/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Reilly Howell -date: 2019-10-20 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2019-10-20 -layout: default -tags: -- dart -- fibonacci -title: Fibonacci in Dart -title1: Fibonacci -title2: in Dart ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -void main(List args) { - try{ - int first = 0; - int second = 1; - int val = 1; - for(int i=1; i - -Welcome to the [Fibonacci](/projects/fibonacci) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -if (> 1 (count $args)) { - echo "Usage: please input the count of fibonacci numbers to output" - exit 1 -} - -try { - var r = (+ $args[0] 1) # Hacky, but it tries to add the argument with one. -} catch { # If it fails, the value is not a number. - echo "Usage: please input the count of fibonacci numbers to output" - exit 1 -} - -var a = 0 -var b = 1 -var c = 0 - -for i [(range 1 (+ $args[0] 1))] { - set c = (+ $a $b) - set a = $b - set b = $c - echo $i': '$a -} - -``` - -{% endraw %} - -Fibonacci in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/euphoria/index.md b/docs/projects/fibonacci/euphoria/index.md deleted file mode 100644 index 9f58e84a17..0000000000 --- a/docs/projects/fibonacci/euphoria/index.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- fibonacci -title: Fibonacci in Euphoria -title1: Fibonacci -title2: in Euphoria ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - -procedure usage() - puts(STDOUT, "Usage: please input the count of fibonacci numbers to output\n") - abort(0) -end procedure - -procedure show_fibonacci_values(integer value) - -- Initialize Fibonacci state: - -- fib(0) = 0 - -- fib(1) = 1 - integer a = 0 - integer b = 1 - integer t - - -- Update Fibonacci state and show results for requested number of values - for n = 1 to value - do - -- fib(n) = fib(n - 1) + fib(n - 2) - t = a + b - a = b - b = t - - printf(STDOUT, "%d: %d\n", {n, a}) - end for -end procedure - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int(argv[4]) -integer value = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] -then - usage() -end if - --- Show requested number of Fibonacci values -show_fibonacci_values(value) - -``` - -{% endraw %} - -Fibonacci in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/f-sharp/index.md b/docs/projects/fibonacci/f-sharp/index.md deleted file mode 100644 index 631f55f98c..0000000000 --- a/docs/projects/fibonacci/f-sharp/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- fibonacci -title: Fibonacci in F# -title1: Fibonacci -title2: in F# ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Fibonacci = - let run n = - Seq.unfold (fun (a, b) -> Some(a, (b, a + b))) (1, 1) - |> Seq.take n - |> Seq.mapi (fun i v -> sprintf "%d: %d" (i + 1) v) - |> String.concat "\n" - -module Helpers = - let usage = "Usage: please input the count of fibonacci numbers to output" - - let (|NonNegativeInt|_|) (s: string) = - match s.Trim() |> Int32.TryParse with - | true, n when n >= 0 -> Some n - | _ -> None - - let parseArgs argv = - match argv with - | [| NonNegativeInt n |] -> Ok n - | _ -> Error usage - - let handleResults = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.map Fibonacci.run |> Helpers.handleResults - -``` - -{% endraw %} - -Fibonacci in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/fortran/index.md b/docs/projects/fibonacci/fortran/index.md deleted file mode 100644 index 9884aad437..0000000000 --- a/docs/projects/fibonacci/fortran/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Butenkite -- Ștefan-Iulian Alecu -date: 2025-02-16 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2025-10-15 -layout: default -tags: -- fibonacci -- fortran -title: Fibonacci in Fortran -title1: Fibonacci -title2: in Fortran ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program fibonacci - implicit none - integer(kind=8) :: prev, curr, next, n, i - character(len=32) :: arg - integer :: ios - - if (command_argument_count() /= 1) then - call usage() - return - endif - - call get_command_argument(1, arg) - arg = adjustl(trim(arg)) - if (len_trim(arg) == 0) then - call usage() - return - endif - - read(arg, *, iostat=ios) n - if (ios /= 0 .or. n < 0) then - call usage() - return - endif - - if (n == 0) return - - prev = 0 - curr = 1 - - do i = 1, n - write(*,'(I0,": ",I0)') i, curr - next = prev + curr - prev = curr - curr = next - end do - -contains - - subroutine usage() - write(*,'(A)') "Usage: please input the count of fibonacci numbers to output" - end subroutine usage - -end program fibonacci - -``` - -{% endraw %} - -Fibonacci in [Fortran](/languages/fortran) was written by: - -- Butenkite -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/go/index.md b/docs/projects/fibonacci/go/index.md deleted file mode 100644 index 4fc8c6d2c8..0000000000 --- a/docs/projects/fibonacci/go/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-02-24 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2019-04-07 -layout: default -tags: -- fibonacci -- go -title: Fibonacci in Go -title1: Fibonacci -title2: in Go ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" -) - -func fibonacci(n int, c chan int) { - x, y := 1, 1 - for i := 0; i < n; i++ { - c <- x - x, y = y, x+y - } - close(c) -} - -func exitWithError() { - fmt.Println("Usage: please input the count of fibonacci numbers to output") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - n, err := strconv.Atoi(os.Args[1]) - if err != nil { - exitWithError() - } - - c := make(chan int, n) - - go fibonacci(cap(c), c) - i := 1 - for v := range c { - fmt.Printf("%d: %d\n", i, v) - i++ - } -} - -``` - -{% endraw %} - -Fibonacci in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/groovy/index.md b/docs/projects/fibonacci/groovy/index.md deleted file mode 100644 index e90913efd5..0000000000 --- a/docs/projects/fibonacci/groovy/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- Loic Beylot -- rzuckerm -date: 2018-10-18 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-07-25 -layout: default -tags: -- fibonacci -- groovy -title: Fibonacci in Groovy -title1: Fibonacci -title2: in Groovy ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -class Fibonacci { - static void main(String[] args) { - if (args.length < 1 || !args[0].isInteger()) { - println 'Usage: please input the count of fibonacci numbers to output' - } else { - def n = args[0] as Integer - if (n > 0) { - def first = 0G - def second = 1G - (1..n).each { - second += first - first = second - first - println "$it: $first" - } - } - } - } -} - -``` - -{% endraw %} - -Fibonacci in [Groovy](/languages/groovy) was written by: - -- Loic Beylot -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/haskell/index.md b/docs/projects/fibonacci/haskell/index.md deleted file mode 100644 index 92f84c5f3a..0000000000 --- a/docs/projects/fibonacci/haskell/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Panagiotis Georgiadis -- Parker Johansen -date: 2018-10-15 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2019-04-07 -layout: default -tags: -- fibonacci -- haskell -title: Fibonacci in Haskell -title1: Fibonacci -title2: in Haskell ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read - -fibonacci :: Int -> [Integer] -fibonacci = flip (take) fibs - -fibs :: [Integer] -fibs = 1 : 1 : zipWith (+) fibs (tail fibs) - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - --- Takes a list of values and returns a list of strings in the format "ONE_BASED_INDEX: VALUE" -printWithIndex :: (Show a) => [a] -> [[Char]] -printWithIndex = zipWith (\i x -> (show i) ++ ": " ++ (show x)) [1..] - - --- Prints out the first N numbers from the fibonacci sequence --- where N equals to the first command line argument. -main :: IO () -main = do - args <- getArgs - let n = headMaybe args - case n >>= readMaybe of - Nothing -> putStrLn "Usage: please input the count of fibonacci numbers to output" - Just n -> mapM_ (putStrLn) $ (printWithIndex . fibonacci) n - -``` - -{% endraw %} - -Fibonacci in [Haskell](/languages/haskell) was written by: - -- Panagiotis Georgiadis -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/index.md b/docs/projects/fibonacci/index.md deleted file mode 100644 index 3631b72404..0000000000 --- a/docs/projects/fibonacci/index.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -date: 2018-10-02 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- fibonacci -title: Fibonacci -title1: Fibonacci -title2: '' ---- - - - -Welcome to the Fibonacci page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -In mathematics, the Fibonacci numbers are the numbers in the following integer -sequence, called the Fibonacci sequence, and characterized by the fact that -every number after the first two is the sum of the two preceding ones: - - 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... - - -## Requirements - -For this sample program, each solution should leverage dynamic programming to produce this -list up to the nth term. For instance, `./fib 5` on the command line should output - -``` -1: 1 -2: 1 -3: 2 -4: 3 -5: 5 -``` - -In addition, there should be some error handling for situations where the user -doesn't supply any input or the user supplies input that is not a number -(i.e. `./fib` or `./fib hello`, respectively). - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Fibonacci. -In order to keep things simple, we split up the testing as follows: - -- Fibonacci Valid Tests -- Fibonacci Invalid Tests - -### Fibonacci Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input 0 | "0" | | -| Sample Input 1 | "1" | "1: 1" | -| Sample Input 2 | "2" | "1: 1"
"2: 1" | -| Sample Input 5 | "5" | "1: 1"
"2: 1"
"3: 2"
"4: 3"
"5: 5" | -| Sample Input 10 | "10" | "1: 1"
"2: 1"
"3: 2"
"4: 3"
"5: 5"
"6: 8"
"7: 13"
"8: 21"
"9: 34"
"10: 55" | - -### Fibonacci Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A Number | "a" | - -All of these tests should output the following: - -``` -Usage: please input the count of fibonacci numbers to output -``` - - -## Articles - -There are 49 articles: - -- [Fibonacci in ALGOL 60](/projects/fibonacci/algol60) -- [Fibonacci in ALGOL 68](/projects/fibonacci/algol68) -- [Fibonacci in AWK](/projects/fibonacci/awk) -- [Fibonacci in Ada](/projects/fibonacci/ada) -- [Fibonacci in Bash](/projects/fibonacci/bash) -- [Fibonacci in Beef](/projects/fibonacci/beef) -- [Fibonacci in Boo](/projects/fibonacci/boo) -- [Fibonacci in C](/projects/fibonacci/c) -- [Fibonacci in C#](/projects/fibonacci/c-sharp) -- [Fibonacci in C++](/projects/fibonacci/c-plus-plus) -- [Fibonacci in COBOL](/projects/fibonacci/cobol) -- [Fibonacci in Commodore BASIC](/projects/fibonacci/commodore-basic) -- [Fibonacci in Dart](/projects/fibonacci/dart) -- [Fibonacci in Elvish](/projects/fibonacci/elvish) -- [Fibonacci in Euphoria](/projects/fibonacci/euphoria) -- [Fibonacci in F#](/projects/fibonacci/f-sharp) -- [Fibonacci in Fortran](/projects/fibonacci/fortran) -- [Fibonacci in Go](/projects/fibonacci/go) -- [Fibonacci in Groovy](/projects/fibonacci/groovy) -- [Fibonacci in Haskell](/projects/fibonacci/haskell) -- [Fibonacci in Java](/projects/fibonacci/java) -- [Fibonacci in JavaScript](/projects/fibonacci/javascript) -- [Fibonacci in Julia](/projects/fibonacci/julia) -- [Fibonacci in Kotlin](/projects/fibonacci/kotlin) -- [Fibonacci in Lisp](/projects/fibonacci/lisp) -- [Fibonacci in Lua](/projects/fibonacci/lua) -- [Fibonacci in Mathematica](/projects/fibonacci/mathematica) -- [Fibonacci in MoonScript](/projects/fibonacci/moonscript) -- [Fibonacci in Nim](/projects/fibonacci/nim) -- [Fibonacci in OCaml](/projects/fibonacci/ocaml) -- [Fibonacci in Objective-C](/projects/fibonacci/objective-c) -- [Fibonacci in Octave](/projects/fibonacci/octave) -- [Fibonacci in Odin](/projects/fibonacci/odin) -- [Fibonacci in PHP](/projects/fibonacci/php) -- [Fibonacci in Pascal](/projects/fibonacci/pascal) -- [Fibonacci in Perl](/projects/fibonacci/perl) -- [Fibonacci in PowerShell](/projects/fibonacci/powershell) -- [Fibonacci in Python](/projects/fibonacci/python) -- [Fibonacci in R](/projects/fibonacci/r) -- [Fibonacci in Racket](/projects/fibonacci/racket) -- [Fibonacci in Ruby](/projects/fibonacci/ruby) -- [Fibonacci in Rust](/projects/fibonacci/rust) -- [Fibonacci in Scala](/projects/fibonacci/scala) -- [Fibonacci in Swift](/projects/fibonacci/swift) -- [Fibonacci in TI-BASIC](/projects/fibonacci/ti-basic) -- [Fibonacci in Tcl](/projects/fibonacci/tcl) -- [Fibonacci in TypeScript](/projects/fibonacci/typescript) -- [Fibonacci in Visual Basic](/projects/fibonacci/visual-basic) -- [Fibonacci in m4](/projects/fibonacci/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/fibonacci/java/index.md b/docs/projects/fibonacci/java/index.md deleted file mode 100644 index 804372968c..0000000000 --- a/docs/projects/fibonacci/java/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Marius -- Parker Johansen -date: 2018-10-03 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- fibonacci -- java -title: Fibonacci in Java -title1: Fibonacci -title2: in Java ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class Fibonacci { - - public static void main(String[] args) { - try { - int n = Integer.parseInt(args[0]); - int first = 0; - int second = 1; - int result = 0; - for (int i = 1; i <= n; i++) { - result = first + second; - first = second; - second = result; - System.out.println(i + ": " + first); - } - } catch (Exception e) { - System.out.println("Usage: please input the count of fibonacci numbers to output"); - System.exit(1); - } - } - -} - -``` - -{% endraw %} - -Fibonacci in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Marius -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/javascript/index.md b/docs/projects/fibonacci/javascript/index.md deleted file mode 100644 index ac60cc1078..0000000000 --- a/docs/projects/fibonacci/javascript/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Alina 1Black -- Jeremy Grifski -- Marius -- Parker Johansen -- rzuckerm -date: 2018-10-04 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- fibonacci -- javascript -title: Fibonacci in JavaScript -title1: Fibonacci in -title2: JavaScript ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -function fibonacci(num) { - let n = Number(num); - let first = 0; - let second = 1; - let result = 0; - for (let i = 1; i <= n; i++) { - result = first + second; - first = second; - second = result; - console.log(i + ": " + first); - } -} - -num = process.argv[2]; - -if (num && !isNaN(num)) { - fibonacci(num); -} else { - console.log("Usage: please input the count of fibonacci numbers to output"); -} - -``` - -{% endraw %} - -Fibonacci in [JavaScript](/languages/javascript) was written by: - -- Marius -- Parker Johansen -- rzuckerm - -This article was written by: - -- Alina 1Black -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of May 04 2025 12:16:22. The solution was first committed on Oct 04 2018 13:17:58. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Let's look at the code in detail: - -Here we have a function called `fibonacci` that takes in a numeric value as an argument that corresponds to the amount Fibonacci numbers we want to print in succession. - -What `fibonacci`" does is that it starts printing from 1 then each time it just prints the accumulation of the last number it printed (stored in variable named `second`) and the 2nd last number it printed (stored in variable named `first`). - -Then we have a variable named `num` which can have a numeric value of `10` since we want to print the first 10 numbers in the Fibonacci sequence. I can also have the value `process.argv[2]` so we can run the command `node fibonacci.js 10` to execute the file with NodeJS and print the first 10 numbers in the Fibonacci sequence. - -Then we have a function that verifies that `num` has a positive, numeric value so we can run the function named `fibonacci`, else it just returns an instruction/warning. - - -## How to Run the Solution - -### If you want to run this code in a browser - -1. Copy/paste the code provided in a JavaScript file. -2. Give the variable `num` a value of 10 instead of `process.argv[2]`. -3. Link the script in a web page. (example given below) - -For example: -If you copy/paste this code in a file named `fibonacci.js` then use copy/paste the following tag in your HTML file: - -```html - -``` - -4. Also make sure that `fibonacci.js` is in the same folder/directory as your HTML file. -5. Just open the webpage in a web browser and look at it's console. The output will be there. - -### If you want to run this code with NodeJS - -1. Make sure that the variable `num` has a value of `process.argv[2]". -2. Open the Terminal/CMD and move to the directory where you are keeping `fibonacci.js`. -3. Execute the command `node fibonacci.js 10` to execute the file with NodeJS to print the first 10 numbers in the Fibonacci sequence. diff --git a/docs/projects/fibonacci/julia/index.md b/docs/projects/fibonacci/julia/index.md deleted file mode 100644 index a5be6b555f..0000000000 --- a/docs/projects/fibonacci/julia/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Michael King -date: 2018-10-12 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2019-04-16 -layout: default -tags: -- fibonacci -- julia -title: Fibonacci in Julia -title1: Fibonacci -title2: in Julia ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -#!/usr/bin/julia - -function fib(n) - f = BigInt[1 1; 1 0] - for i = 1:n - fn = f ^ i - println(i, ": ", fn[2, 1]) - end -end - -function error() - println("Usage: please input the count of fibonacci numbers to output") -end - -try - fib(parse(Int, ARGS[1])) -catch e - error() -end - - -``` - -{% endraw %} - -Fibonacci in [Julia](/languages/julia) was written by: - -- Jeremy Grifski -- Michael King - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/kotlin/index.md b/docs/projects/fibonacci/kotlin/index.md deleted file mode 100644 index 86296b7f92..0000000000 --- a/docs/projects/fibonacci/kotlin/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Blake.Ke -- Erik Nelson -date: 2018-10-18 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- fibonacci -- kotlin -title: Fibonacci in Kotlin -title1: Fibonacci -title2: in Kotlin ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -import kotlin.system.exitProcess - -// First arg is number of iterations to run -fun main(args: Array) { - if (args.isNullOrEmpty() || args[0].toIntOrNull()?.takeIf { it >= 0 } == null) { - println("Usage: please input the count of fibonacci numbers to output") - return - } - - val iterations = args[0].toInt() - - var j: Int - var k = 0 - var l = 1 - - for (i in 1..iterations) { - println("$i: $l") - - j = k - k = l - l = j + k - } -} -``` - -{% endraw %} - -Fibonacci in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- Erik Nelson - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/lisp/index.md b/docs/projects/fibonacci/lisp/index.md deleted file mode 100644 index 4c0552f281..0000000000 --- a/docs/projects/fibonacci/lisp/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2020-10-10 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2020-10-11 -layout: default -tags: -- fibonacci -- lisp -title: Fibonacci in Lisp -title1: Fibonacci -title2: in Lisp ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(defun fibonacci (n &optional (a 1) (b 1) (acc)) - (if (<= n 0) - (reverse acc) - (fibonacci (- n 1) b (+ a b) (cons a acc)))) - -(defun countfibs(acc n fibs) - (if (< (length fibs) 1) - (reverse acc) - (countfibs (cons (list n (car fibs)) acc) (+ 1 n) (cdr fibs)))) - -(defun maybe-pos-int (input) - (cond - ((null input) nil) - ((string= input "") nil) - ((every #'digit-char-p input) (parse-integer input)) - (t nil))) - -(defparameter num (maybe-pos-int (cadr *posix-argv*))) -(cond - ((null num) (write-line "Usage: please input the count of fibonacci numbers to output")) - (t (dolist (item (countfibs (list) 1 (fibonacci num))) - (format t "~D: ~D~%" (car item) (cadr item))))) - -``` - -{% endraw %} - -Fibonacci in [Lisp](/languages/lisp) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/lua/index.md b/docs/projects/fibonacci/lua/index.md deleted file mode 100644 index b97302815f..0000000000 --- a/docs/projects/fibonacci/lua/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Andy Alban -date: 2019-10-14 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2019-10-14 -layout: default -tags: -- fibonacci -- lua -title: Fibonacci in Lua -title1: Fibonacci -title2: in Lua ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -function fib(n) - local a, b = 0, 1 - for k = 1, n do - a, b = b, a + b - print(k .. ": " .. a) - end -end - -if tonumber(arg[1]) ~= nil then - n = tonumber(arg[1]) - print(fib(n)) -else - print("Usage: please input the count of fibonacci numbers to output") -end - -``` - -{% endraw %} - -Fibonacci in [Lua](/languages/lua) was written by: - -- Andy Alban - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/m4/index.md b/docs/projects/fibonacci/m4/index.md deleted file mode 100644 index 7b6014d344..0000000000 --- a/docs/projects/fibonacci/m4/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-11 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2025-08-11 -layout: default -tags: -- fibonacci -- m4 -title: Fibonacci in m4 -title1: Fibonacci -title2: in m4 ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please input the count of fibonacci numbers to output -m4exit(`1')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl fibonacci(n) -define(`fibonacci', -`ifelse(`$#', 0, ``$0'', -`ifelse(eval(`$1' >= 1), 1, `_fibonacci(`$1', 1, 0, 1)')'dnl -)'dnl -) -dnl _fibonacci(n, k, prev_state, curr_state) -dnl while k <= n: -dnl Output k ": " curr_state -dnl prev_state, curr_state = curr_state, prev_state + curr_state -dnl k = k + 1 -define(`_fibonacci', -`ifelse(eval(`$2' <= `$1'), 1, -`$2: $4 -_fibonacci(`$1', incr($2), `$4', `eval($3 + $4)')dnl -')') -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !is_valid(ARGV1)), 1, `show_usage()', `fibonacci(ARGV1)')dnl - -``` - -{% endraw %} - -Fibonacci in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/mathematica/index.md b/docs/projects/fibonacci/mathematica/index.md deleted file mode 100644 index cf6c4bba84..0000000000 --- a/docs/projects/fibonacci/mathematica/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-19 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-01-19 -layout: default -tags: -- fibonacci -- mathematica -title: Fibonacci in Mathematica -title1: Fibonacci in -title2: Mathematica ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* It would be easy to simply print these out in a 'for' loop; however, in the spirit -of keeping the mathematical operation separate from the UI I opted to return -the Fibonacci sequence as a list explicitly: *) - -fibonacciSequence[0] := {} (* special case *) -fibonacciSequence[1] := {1} (* special case *) -fibonacciSequence[n_] := Nest[Append[#, #[[-2]] + #[[-1]]] &, {1, 1}, n - 2] - -(* The outer function provides the 'user interface': *) - -fibonacciSequenceMain = Function[n, - Catch[ - Module[{s}, - s = fibonacciSequence[ - (* convert string to integer, or throw *) - If[StringMatchQ[n, DigitCharacter ..], - FromDigits[n], - Throw[ - "Usage: please input the count of fibonacci numbers to output"]]]; - Do[Print[i, ": ", s[[i]]], {i, Length[s]}]]]]; - - -(* Valid Tests *) - -fibonacciSequenceMain /@ {"1", "2", "5", "10"}; - - -(* Invalid Tests *) - -fibonacciSequenceMain[""] -fibonacciSequenceMain["word"] - -``` - -{% endraw %} - -Fibonacci in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/moonscript/index.md b/docs/projects/fibonacci/moonscript/index.md deleted file mode 100644 index fbe7eb53d6..0000000000 --- a/docs/projects/fibonacci/moonscript/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- RJ Fredrick Rico -date: 2025-02-17 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2025-02-17 -layout: default -tags: -- fibonacci -- moonscript -title: Fibonacci in MoonScript -title1: Fibonacci in -title2: MoonScript ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [MoonScript](/languages/moonscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```moonscript --- fibonacci function -fibonacci = (n) -> - -- set up a, b, for i until n, print "i: n" then update a & b as the fibonacci sequence - a, b = 1, 1 - for i = 1, n - print "#{i}: #{a}" - a, b = b, a + b - --- main --- check if arg params are numbers and are greater than 0 -if arg[1] and tonumber(arg[1]) ~= nil and tonumber(arg[1]) >= 0 - fibonacci tonumber(arg[1]) --- else, return usage error msg -else - print "Usage: please input the count of fibonacci numbers to output" - -``` - -{% endraw %} - -Fibonacci in [MoonScript](/languages/moonscript) was written by: - -- RJ Fredrick Rico - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/nim/index.md b/docs/projects/fibonacci/nim/index.md deleted file mode 100644 index 3b4e5895bb..0000000000 --- a/docs/projects/fibonacci/nim/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Michael Olson -date: 2019-10-16 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2019-10-16 -layout: default -tags: -- fibonacci -- nim -title: Fibonacci in Nim -title1: Fibonacci -title2: in Nim ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Nim](/languages/nim) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nim -# Fibonacci Sample Program in Nim -# Input the number of iterations as a command-line parameter -import os -import strutils - -var n: BiggestUInt -try: - n = paramStr(1).parseBiggestUInt -except IndexError, ValueError: - echo "Usage: please input the count of fibonacci numbers to output" - quit(1) - -var previouspreviousInt: BiggestUInt -var previousInt: BiggestUInt = 0 -var currentInt: BiggestUInt = 1 - -if n == 0: - echo "" - quit(0) - -for i in 1..n: - echo i, ": ", currentInt - previouspreviousInt = previousInt - previousInt = currentInt - currentInt = previouspreviousInt + previousInt - - -``` - -{% endraw %} - -Fibonacci in [Nim](/languages/nim) was written by: - -- Michael Olson - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/objective-c/index.md b/docs/projects/fibonacci/objective-c/index.md deleted file mode 100644 index 563d0ddf14..0000000000 --- a/docs/projects/fibonacci/objective-c/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- Renato -- rzuckerm -- Ștefan-Iulian Alecu -date: 2020-10-01 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- fibonacci -- objective-c -title: Fibonacci in Objective-C -title1: Fibonacci in -title2: Objective-C ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -@interface NSString (Parsing) -@property(nonatomic, readonly, nullable) NSNumber* strictIntegerNumber; -@end - -@implementation NSString (Parsing) - -- (NSNumber*)strictIntegerNumber { - NSString* trimmed = [self - stringByTrimmingCharactersInSet:NSCharacterSet - .whitespaceAndNewlineCharacterSet]; - if (trimmed.length == 0) return nil; - - NSInteger offset = 0; - if ([trimmed hasPrefix:@"-"] || [trimmed hasPrefix:@"+"]) { - offset = 1; - } - - if (trimmed.length <= offset) return nil; - - NSString* core = [trimmed substringFromIndex:offset]; - NSRange invalidRange = - [core rangeOfCharacterFromSet:NSCharacterSet.decimalDigitCharacterSet - .invertedSet]; - - if (invalidRange.location != NSNotFound) { - return nil; - } - - return @(trimmed.longLongValue); -} - -@end - -static void PrintFibonacciSequence(NSUInteger count) { - unsigned long long previous = 0; - unsigned long long current = 1; - - for (NSUInteger i = 1; i <= count; i++) { - printf("%ld: %llu\n", i, current); - - unsigned long long next = previous + current; - previous = current; - current = next; - } -} - -int main(int argc, const char* argv[]) { - @autoreleasepool { - const char* usage = - "Usage: please input the count of fibonacci numbers to output"; - - if (argc < 2) { - puts(usage); - return 1; - } - - NSNumber* number = @(argv[1]).strictIntegerNumber; - - if (!number || number.integerValue < 0) { - puts(usage); - return 1; - } - - PrintFibonacciSequence(number.unsignedIntegerValue); - } - return 0; -} - -``` - -{% endraw %} - -Fibonacci in [Objective-C](/languages/objective-c) was written by: - -- Renato -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/ocaml/index.md b/docs/projects/fibonacci/ocaml/index.md deleted file mode 100644 index db300f8f63..0000000000 --- a/docs/projects/fibonacci/ocaml/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-17 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- fibonacci -- ocaml -title: Fibonacci in OCaml -title1: Fibonacci -title2: in OCaml ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let fib n = - let rec help current max out = - if current > max then List.rev out - else - match out with - | prev :: prevprev :: _ -> - help (current + 1) max ((prev + prevprev) :: out) - | _ -> help (current + 1) max (1 :: out) - in - help 1 n [] - -let fib_table n = - List.iteri (fun i e -> Printf.printf "%d: %d\n" (i + 1) e) (fib n) - -let parse_args argv = - match argv with [| _; n |] -> int_of_string_opt n | _ -> None - -let () = - match parse_args Sys.argv with - | Some num when num >= 0 -> fib_table num - | _ -> - print_endline - "Usage: please input the count of fibonacci numbers to output" - -``` - -{% endraw %} - -Fibonacci in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/octave/index.md b/docs/projects/fibonacci/octave/index.md deleted file mode 100644 index f971efe854..0000000000 --- a/docs/projects/fibonacci/octave/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- fibonacci -- octave -title: Fibonacci in Octave -title1: Fibonacci -title2: in Octave ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function fibonacci() - usage = 'Usage: please input the count of fibonacci numbers to output'; - arg_list = argv(); - nargin = length(arg_list); - if nargin == 0 - disp(usage); - return; - end - - n = str2num(arg_list{1}); - if length(n) ~= 1 || mod(n, 1) ~= 0 - disp(usage); - return; - end - - a(1) = 1; - a(2) = 1; - - for i=1:n - a(i+2) = a(i+1) + a(i); - printf('%d: %d\n', i, a(i)); - end -end - -``` - -{% endraw %} - -Fibonacci in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/odin/index.md b/docs/projects/fibonacci/odin/index.md deleted file mode 100644 index 90003193c3..0000000000 --- a/docs/projects/fibonacci/odin/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Omnissiah -date: 2025-10-30 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2025-10-30 -layout: default -tags: -- fibonacci -- odin -title: Fibonacci in Odin -title1: Fibonacci -title2: in Odin ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main - -import "core:fmt" -import "core:strconv" -import "core:os" - -main :: proc() { - if len(os.args) != 2 { - usage() - return - } - input, check := strconv.parse_int(os.args[1], 10) - if !check { - usage() - return - } - - use1 := 0 - use2 := 1 - use3 := 0 - for i:=1 ; i <= input; i += 1 { - use3 = use1 + use2 - use1 = use2 - use2 = use3 - fmt.print(i) - fmt.print(": ") - fmt.println(use1) - } -} - -usage :: proc() { - fmt.println("Usage: please input the count of fibonacci numbers to output") -} - -``` - -{% endraw %} - -Fibonacci in [Odin](/languages/odin) was written by: - -- Omnissiah - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/pascal/index.md b/docs/projects/fibonacci/pascal/index.md deleted file mode 100644 index 81627e8369..0000000000 --- a/docs/projects/fibonacci/pascal/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- manasmithamn -date: 2021-10-24 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2021-10-24 -layout: default -tags: -- fibonacci -- pascal -title: Fibonacci in Pascal -title1: Fibonacci -title2: in Pascal ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program Fibonacci(input, output, stdErr); -(*Read count of fibonnaci numbers into a string - -*) -var - buf: String; - count, check, first,second,result, i : integer; - -begin - (*Variable initialisation must be inside begin-end block*) - first := 0; - second := 1; - result := 0; - - begin - buf:= paramStr(1); - Val(buf, count, check); - (*If input is valid integer, check will be 0, else will be 1*) - if (check <> 0) - then - begin - writeln('Usage: please input the count of fibonacci numbers to output'); - end - else - for i := 1 to count do - begin - - result := first + second; - first := second; - second := result; - writeln(i, ': ', first); - end; - end; -end. - -``` - -{% endraw %} - -Fibonacci in [Pascal](/languages/pascal) was written by: - -- manasmithamn - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/perl/index.md b/docs/projects/fibonacci/perl/index.md deleted file mode 100644 index 24dbc57d4a..0000000000 --- a/docs/projects/fibonacci/perl/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- SourabhBadhya -- Ștefan-Iulian Alecu -date: 2020-10-02 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- fibonacci -- perl -title: Fibonacci in Perl -title1: Fibonacci -title2: in Perl ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -sub usage { - say "Usage: please input the count of fibonacci numbers to output"; - exit; -} - -my ($n) = @ARGV; -usage() unless defined $n && $n =~ /\A\d+\z/; - -my ( $a, $b ) = ( 0, 1 ); - -for my $i ( 1 .. $n ) { - ( $a, $b ) = ( $b, $a + $b ); - say "$i: $a"; -} - -``` - -{% endraw %} - -Fibonacci in [Perl](/languages/perl) was written by: - -- SourabhBadhya -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/php/index.md b/docs/projects/fibonacci/php/index.md deleted file mode 100644 index 4288fc8658..0000000000 --- a/docs/projects/fibonacci/php/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Carles Capell -- Parker Johansen -date: 2019-01-03 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2019-10-15 -layout: default -tags: -- fibonacci -- php -title: Fibonacci in PHP -title1: Fibonacci -title2: in PHP ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Fibonacci](/projects/fibonacci) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please input the count of fibonacci numbers to output" - Exit 1 -} - -function Show-Fibonacci([int]$Value) { - if ($Value -gt 0) { - $A, $B = 0, 1 - 1..$Value | ForEach-Object { - $A, $B = $B, ($A + $B) - Write-Host "${_}: $A" - } - } -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $Value = [int]::Parse($args[0]) -} catch { - Show-Usage -} - -if ($Value -lt 0) { - Show-Usage -} - -Show-Fibonacci $Value - -``` - -{% endraw %} - -Fibonacci in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/python/index.md b/docs/projects/fibonacci/python/index.md deleted file mode 100644 index 5b116e498c..0000000000 --- a/docs/projects/fibonacci/python/index.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Marius -- Parker Johansen -- rzuckerm -- shubhragupta-code -date: 2018-10-06 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- fibonacci -- python -title: Fibonacci in Python -title1: Fibonacci -title2: in Python ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def fibonacci(n): - fib = fibs() - for i in range(1, n + 1): - print(f'{i}: {next(fib)}') - - -def fibs(): - first = 1 - second = 1 - yield first - yield second - while True: - new = first + second - yield new - first = second - second = new - - -def main(args): - try: - fibonacci(int(args[0])) - except (IndexError, ValueError): - print("Usage: please input the count of fibonacci numbers to output") - sys.exit(1) - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Fibonacci in [Python](/languages/python) was written by: - -- Marius -- Parker Johansen - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Now, we will consider this code block by block on the order of execution. - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -This code checks if the `main` module is run. If it is, it then passes control to `main` function passing argument string provided by the user. - -```python -def main(args): - try: - fibonacci(int(args[0])) - except (IndexError, ValueError): - print("Usage: please input the count of fibonacci numbers to output") - sys.exit(1) -``` - -This main function was invoked earlier with argument string. Next line invokes `fibonacci()` function. If the function raises [`IndexError`][1] *(Raised when a sequence subscript is out of range)* or [`ValueError`][2] *(Raised for an non-integer value)*, it prints correct usage pattern. And program exits with exit status `1` which specifies abnormal termination. - -```python -def fibonacci(n): - fib = fibs() - for i in range(1, n + 1): - print(f'{i}: {next(fib)}') - -def fibs(): - first = 1 - second = 1 - yield first - yield second - while True: - new = first + second - yield new - first = second - second = new -``` - -In `fibonacci()` function, function `fibs()` is called. In `fibs()`, [`yield`][3] function returns generator which iterates to store and get values. Value of `first` and `second` are initially stored in generator as 1 and 2. In the while loop, values of fibonacci sequence is added using rule `third_num = first_num + second_num`. Control goes back to `fibonacci()` which prints values returned by `next()` which returns next item in iterator. This sequence is repeated till the user specified input times. - -[1]: https://docs.python.org/3/library/exceptions.html#IndexError -[2]: https://docs.python.org/3/library/exceptions.html#ValueError -[3]: https://docs.python.org/3/reference/simple_stmts.html#the-yield-statement - - -## How to Run the Solution - -Fibonacci in Python. After that, we should make sure we have the -[latest Python interpreter][4]. From there, we can simply run the following -command in the terminal: - -```console -python fibonacci.py -``` - -Alternatively, we can copy the solution into an [online Python interpreter][5] -and hit run. - -[4]: https://docs.python.org/3/tutorial/interpreter.html -[5]: https://www.onlinegdb.com/online_python_interpreter diff --git a/docs/projects/fibonacci/r/index.md b/docs/projects/fibonacci/r/index.md deleted file mode 100644 index 13de5bb0f7..0000000000 --- a/docs/projects/fibonacci/r/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- fibonacci -- r -title: Fibonacci in R -title1: Fibonacci -title2: in R ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -USAGE <- "Usage: please input the count of fibonacci numbers to output" -args <- commandArgs(trailingOnly = TRUE) - -if (length(args) != 1 || nchar(args[1]) == 0) { - cat(USAGE, "\n") - quit(status = 1) -} - -n <- suppressWarnings(as.numeric(args[1])) - -if (is.na(n) || n %% 1 != 0) { - cat(USAGE, "\n") - quit(status = 1) -} - -if (n <= 0) { - quit(status = 0) -} - -fib <- numeric(n) -fib[1] <- 1 - -if (n >= 2) { - fib[2] <- 1 -} - -if (n >= 3) { - for (i in 3:n) { - fib[i] <- fib[i - 1] + fib[i - 2] - } -} - -indices <- 1:n -output <- paste0(indices, ": ", fib, collapse = "\n") -cat(output, "\n") -``` - -{% endraw %} - -Fibonacci in [R](/languages/r) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/racket/index.md b/docs/projects/fibonacci/racket/index.md deleted file mode 100644 index 72b853c9a3..0000000000 --- a/docs/projects/fibonacci/racket/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Jeremy Grifski -- zafar hussain -date: 2019-10-31 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2022-05-10 -layout: default -tags: -- fibonacci -- racket -title: Fibonacci in Racket -title1: Fibonacci -title2: in Racket ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Racket](/languages/racket) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```racket -#lang racket - -;; A naive iimplementation of fibonacci - -(define (fib n) - (cond - [(<= n 2) 1] - [else - (+ (fib (- n 1)) (fib (- n 2)))])) - - - -(define (fibonacci n) - (cond - [(or (not n) (< n 0)) (display "Usage: please input the count of fibonacci numbers to output")] - - [else - (for ([i (in-range 1 (add1 n))]) - (displayln (string-append (number->string i) ": " (number->string (fib i))))) - ])) - - -(fibonacci - (string->number - (cond - [(vector-empty? (current-command-line-arguments)) ""] - [else (vector-ref (current-command-line-arguments) 0)] - ) - ) -) - -``` - -{% endraw %} - -Fibonacci in [Racket](/languages/racket) was written by: - -- Jeremy Grifski -- zafar hussain - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/ruby/index.md b/docs/projects/fibonacci/ruby/index.md deleted file mode 100644 index 427af3c4ac..0000000000 --- a/docs/projects/fibonacci/ruby/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Noah Nichols -- Ștefan-Iulian Alecu -date: 2018-10-14 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- fibonacci -- ruby -title: Fibonacci in Ruby -title1: Fibonacci -title2: in Ruby ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def usage! - abort("Usage: please input the count of fibonacci numbers to output") -end - -def fibonacci(n) - a, b = 1, 1 - - n.times do |i| - puts "#{i + 1}: #{a}" - a, b = b, a + b - end -end - -input = ARGV.first -usage! if input.nil? || input.strip.empty? - -begin - num = Integer(input) -rescue ArgumentError - usage! -end - -usage! if num.negative? - -fibonacci(num) - -``` - -{% endraw %} - -Fibonacci in [Ruby](/languages/ruby) was written by: - -- Noah Nichols -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/rust/index.md b/docs/projects/fibonacci/rust/index.md deleted file mode 100644 index 7930b8319e..0000000000 --- a/docs/projects/fibonacci/rust/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Noah Nichols -- rzuckerm -date: 2018-10-05 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- fibonacci -- rust -title: Fibonacci in Rust -title1: Fibonacci -title2: in Rust ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -const LIMIT: i32 = 93; - -fn usage() -> ! { - println!("Usage: please input the count of fibonacci numbers to output"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn fibonacci(terms: i32) { - if terms > LIMIT { - println!("The number of terms you want to calculate is too big!"); - println!("The limit is {}.", LIMIT); - } else { - let mut a = 0u64; - let mut b = 1u64; - for i in 1..(terms + 1) { - (a, b) = (b, a + b); - println!("{i}: {a}"); - } - } -} - -fn main() { - let mut args = args().skip(1); - - // Exit if 1st command-line argument not an integer - let mut input_num: i32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Show request number of Fibonacci numbers - fibonacci(input_num); -} - -``` - -{% endraw %} - -Fibonacci in [Rust](/languages/rust) was written by: - -- Noah Nichols -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/scala/index.md b/docs/projects/fibonacci/scala/index.md deleted file mode 100644 index 6de0a2b3f5..0000000000 --- a/docs/projects/fibonacci/scala/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- rzuckerm -- Ștefan-Iulian Alecu -date: 2023-05-15 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- fibonacci -- scala -title: Fibonacci in Scala -title1: Fibonacci -title2: in Scala ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -object Fibonacci: - - private val fibs: LazyList[BigInt] = - BigInt(1) #:: BigInt(1) #:: fibs.zip(fibs.tail).map(_ + _) - - private val usage = - "Usage: please input the count of fibonacci numbers to output" - - def main(args: Array[String]): Unit = - val output = - for - arg <- args.headOption - n <- arg.toIntOption if n >= 0 - yield - if n == 0 then "" - else - fibs - .take(n) - .zipWithIndex - .map((f, i) => s"${i + 1}: $f") - .mkString("\n") - - println(output.getOrElse(usage)) -``` - -{% endraw %} - -Fibonacci in [Scala](/languages/scala) was written by: - -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/swift/index.md b/docs/projects/fibonacci/swift/index.md deleted file mode 100644 index d5c2e20a75..0000000000 --- a/docs/projects/fibonacci/swift/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- smallblack9 -date: 2020-10-11 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2020-10-11 -layout: default -tags: -- fibonacci -- swift -title: Fibonacci in Swift -title1: Fibonacci -title2: in Swift ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -func fibonacciProgram(_ n: Int) { - var f1=0, f2=1, fib=1 - for i in 0.. Int { - if (n == 0) { - return 0 - } else if (n == 1) { - return 1 - } - return fibonacciRecursive(n-1) + fibonacciRecursive(n-2) -} - -/* - Check if there is exactly one argument and if it can be parsed as an integer -*/ -guard CommandLine.argc == 2, let number = Int(CommandLine.arguments[1]) else { - print("Usage: please input the count of fibonacci numbers to output") - exit(0) -} - -fibonacciProgram(number) -``` - -{% endraw %} - -Fibonacci in [Swift](/languages/swift) was written by: - -- smallblack9 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/tcl/index.md b/docs/projects/fibonacci/tcl/index.md deleted file mode 100644 index 7365e76b72..0000000000 --- a/docs/projects/fibonacci/tcl/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2025-10-08 -layout: default -tags: -- fibonacci -- tcl -title: Fibonacci in Tcl -title1: Fibonacci -title2: in Tcl ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts "Usage: please input the count of fibonacci numbers to output" - exit 1 -} - -if {$argc != 1} { usage } - -set count [lindex $argv 0] - -if {![string is integer -strict $count] || $count < 0} { usage } - -set a 1 -set b 1 - -for {set i 1} {$i <= $count} {incr i} { - puts "$i: $a" - - set next [expr {$a + $b}] - set a $b - set b $next -} - -``` - -{% endraw %} - -Fibonacci in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/ti-basic/index.md b/docs/projects/fibonacci/ti-basic/index.md deleted file mode 100644 index eb6181c89c..0000000000 --- a/docs/projects/fibonacci/ti-basic/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-03 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2025-02-03 -layout: default -tags: -- fibonacci -- ti-basic -title: Fibonacci in TI-BASIC -title1: Fibonacci -title2: in TI-BASIC ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -"0123456789"->Str2 -length(Str1)->L -L<1->E -0->D -0->V -1->N -1->S -While E=0 and N<=L - sub(Str1,N,1)->C - inString(Str2,C)-1->K - If C="+" or C="-" - Then - D>0->E - If C="-" - Then 0-S->S - End - Else - K<0->E - D+1->D - V*10+K*S->V - End - N+1->N -End -If E or D<1 or V<0 Then Disp "Usage: please input the count of fibonacci numbers to output" -Else - 0->A - 1->B - For(N,1,V) - A+B->C - B->A - C->B - Disp toString(N)+": "+toString(A) - End -End - -``` - -{% endraw %} - -Fibonacci in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/typescript/index.md b/docs/projects/fibonacci/typescript/index.md deleted file mode 100644 index b0d2c12558..0000000000 --- a/docs/projects/fibonacci/typescript/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Chris Thomas -- rzuckerm -date: 2018-10-12 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- fibonacci -- typescript -title: Fibonacci in TypeScript -title1: Fibonacci in -title2: TypeScript ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function fibonacci(num: number) { - - let n = Number(num); - let elementOne: number = 0; - let elementTwo: number = 1; - let result: number = 0; - - for (let i: number = 1; i <= n; i++) { - result = elementOne + elementTwo; - elementOne = elementTwo; - elementTwo = result; - console.log(`${i}: ${elementOne}`); - } - -} - -let num_str = (process.argv.length >= 3) ? process.argv[2] : "" -let num: number = parseInt(num_str); -if (isNaN(num)) { - console.log("Usage: please input the count of fibonacci numbers to output") - process.exit(0) -} - -fibonacci(num); - -``` - -{% endraw %} - -Fibonacci in [TypeScript](/languages/typescript) was written by: - -- Chris Thomas -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fibonacci/visual-basic/index.md b/docs/projects/fibonacci/visual-basic/index.md deleted file mode 100644 index 6a64a3b69f..0000000000 --- a/docs/projects/fibonacci/visual-basic/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: fibonacci-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- fibonacci -- visual-basic -title: Fibonacci in Visual Basic -title1: Fibonacci in -title2: Visual Basic ---- - - - -Welcome to the [Fibonacci](/projects/fibonacci) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System.Numerics - -Module Fibonacci - - Public Sub Main(args As String()) - - If args.Length = 0 Then - ShowUsage() - Return - End If - - Dim n As Integer - - If Not Integer.TryParse(args(0), n) OrElse n < 0 Then - ShowUsage() - Return - End If - - Dim first As BigInteger = 0 - Dim second As BigInteger = 1 - - For i As Integer = 1 To n - - Dim current As BigInteger = first + second - first = second - second = current - - Console.WriteLine($"{i}: {first}") - - Next - - End Sub - - - Private Sub ShowUsage() - Console.WriteLine("Usage: please input the count of fibonacci numbers to output") - Environment.Exit(1) - End Sub - -End Module -``` - -{% endraw %} - -Fibonacci in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/ada/index.md b/docs/projects/file-input-output/ada/index.md deleted file mode 100644 index ac60cbc6a4..0000000000 --- a/docs/projects/file-input-output/ada/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-10 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-10 -layout: default -tags: -- ada -- file-input-output -title: File Input Output in Ada -title1: File Input -title2: Output in Ada ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Exceptions; - -procedure File_IO is - - File_Name : constant String := "output.txt"; - - procedure Write_File is - F : File_Type; - begin - Create (F, Out_File, File_Name); - - Put_Line (F, "Hello from Ada!"); - Put_Line (F, "This is a second line."); - Put_Line (F, "File I/O is working."); - - Close (F); - - exception - when Name_Error => - Put_Line ("Error: invalid file name"); - when Use_Error => - Put_Line ("Error: cannot create file"); - end Write_File; - - procedure Read_File is - F : File_Type; - begin - Open (F, In_File, File_Name); - - while not End_Of_File (F) loop - declare - Line : constant String := Get_Line (F); - begin - Put_Line (Line); - end; - end loop; - - Close (F); - - exception - when Name_Error => - Put_Line ("Error: file not found"); - when End_Error => - null; - end Read_File; - -begin - Write_File; - Read_File; -end File_IO; - -``` - -{% endraw %} - -File Input Output in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/algol68/index.md b/docs/projects/file-input-output/algol68/index.md deleted file mode 100644 index fbee9d826f..0000000000 --- a/docs/projects/file-input-output/algol68/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-20 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- file-input-output -title: File Input Output in ALGOL 68 -title1: File Input Output -title2: in ALGOL 68 ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC write file = (STRING file name) INT: -( - FILE f; - INT status := establish(f, file name, stand out channel); - IF status /= 0 - THEN - put(stand error, ("Cannot open ", file name, " for write", new line)) - ELSE - put(f, ("Hello from Algol 68!", new line)); - put(f, ("Here is a line", new line)); - put(f, ("Here is another line", new line)); - put(f, ("Goodbye!", new line)); - close(f) - FI; - - status -); - -PROC read file = (STRING file name) INT: -( - FILE f; - INT status := open(f, file name, stand in channel); - IF status /= 0 - THEN - put(stand error, ("Cannot open ", file name, " for read", new line)) - ELSE - on logical file end(f, (REF FILE inf) BOOL: - ( - close(inf); - done - ) - ); - - STRING line; - DO - get(f, (line, new line)); - write((line, new line)) - OD - FI; - -done: - status -); - -STRING file name := "output.txt"; -IF write file(filename) /= 0 -THEN - stop -FI; - -IF read file(filename) /= 0 -THEN - stop -FI - -``` - -{% endraw %} - -File Input Output in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/awk/index.md b/docs/projects/file-input-output/awk/index.md deleted file mode 100644 index 5df84b2c30..0000000000 --- a/docs/projects/file-input-output/awk/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-06 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2025-04-06 -layout: default -tags: -- awk -- file-input-output -title: File Input Output in AWK -title1: File Input -title2: Output in AWK ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function write_file(filename) { - print "Hello from awk" >filename - print "Line 1" >>filename - print "Line 2" >>filename - print "Goodbye from awk" >>filename - close(filename) -} - -# Reference: https://www.gnu.org/software/gawk/manual/html_node/Getline_002fVariable_002fFile.html -function read_file(filename) { - while (getline line < filename) { - print line - } - - close(filename) -} - -BEGIN { - filename = "output.txt" - write_file(filename) - read_file(filename) -} - -``` - -{% endraw %} - -File Input Output in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/bash/index.md b/docs/projects/file-input-output/bash/index.md deleted file mode 100644 index 15808106ec..0000000000 --- a/docs/projects/file-input-output/bash/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-10-28 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2018-10-28 -layout: default -tags: -- bash -- file-input-output -title: File Input Output in Bash -title1: File Input -title2: Output in Bash ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -read_file () { - cat output.txt -} - -write_file () { - echo -e "$1" > output.txt -} - -write_file "File text line 1\nFile text line 2\nFile text line 3" -read_file - -``` - -{% endraw %} - -File Input Output in [Bash](/languages/bash) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/beef/index.md b/docs/projects/file-input-output/beef/index.md deleted file mode 100644 index b1b696cad2..0000000000 --- a/docs/projects/file-input-output/beef/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-18 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2024-01-18 -layout: default -tags: -- beef -- file-input-output -title: File Input Output in Beef -title1: File Input -title2: Output in Beef ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.IO; - -namespace FileInputOutput; - -class Program -{ - public static Result WriteFile(StringView filename) - { - StreamWriter fs = scope .(); - Try!(fs.Create(filename)); - fs.WriteLine("Hello from Beef!"); - fs.WriteLine("This is line 1"); - fs.WriteLine("This is line 2"); - fs.WriteLine("Goodbye!"); - return .Ok; - } - - public static Result ReadFile(StringView filename) - { - StreamReader fs = scope .(); - Try!(fs.Open(filename)); - String line = scope .(); - while (fs.ReadLine(line) case .Ok) - { - Console.WriteLine(line); - line.Clear(); - } - - return .Ok; - } - - public static int Main(String[] args) - { - String filename = "output.txt"; - - if (WriteFile(filename) case .Err) - { - Console.WriteLine($"Could not write {filename}"); - } - - if (ReadFile(filename) case .Err) - { - Console.WriteLine($"Could not read {filename}"); - } - - return 0; - } -} - -``` - -{% endraw %} - -File Input Output in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/c-plus-plus/index.md b/docs/projects/file-input-output/c-plus-plus/index.md deleted file mode 100644 index 8a8444548b..0000000000 --- a/docs/projects/file-input-output/c-plus-plus/index.md +++ /dev/null @@ -1,298 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Noah Nichols -- rzuckerm -- Ștefan-Iulian Alecu -date: 2018-09-10 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- file-input-output -title: File Input Output in C++ -title1: File Input -title2: Output in C++ ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include - -namespace fs = std::filesystem; - -bool write_file(const fs::path& path, std::string_view content) { - std::ofstream out(path, std::ios::binary | std::ios::trunc); - - if (!out) { - std::cerr << "Error: Could not open '" << path << "' for writing!\n"; - return false; - } - - out.write(content.data(), static_cast(content.size())); - return static_cast(out); -} - -bool read_file(const fs::path& path) { - std::ifstream in(path, std::ios::binary); - - if (!in) { - std::cerr << "Error: Could not open '" << path << "' for reading!\n"; - return false; - } - - std::cout << in.rdbuf(); - return true; -} - -int main() { - const fs::path target = "output.txt"; - - constexpr std::string_view data = - "A line of text\n" - "Another line of text\n"; - - if (!write_file(target, data)) return 1; - if (!read_file(target)) return 1; -} -``` - -{% endraw %} - -File Input Output in [C++](/languages/c-plus-plus) was written by: - -- Noah Nichols -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of May 05 2026 15:57:54. The solution was first committed on Sep 10 2018 22:37:35. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Let's first take a look at the solution. Then, we'll walk through each line of -code: - -In less than 50 lines, we have our solution! - -### Includes - -In our sample, we include three different standard library utilities: - -```c++ -#include -#include -#include -``` - -Here, we can see that we include he standard I/O for printing messages onto the -screen, the standard file I/O for accessing files, and the C++ string library -for storing each line in the file. - -### Writing to a File - -From there, we defined the `write_file()` function which we'll use to write some -arbitrary text to a file: - -```c++ -void write_file() -{ - std::fstream out("output.txt", std::ios::out); - - if (!out.is_open()) - { - std::cout << "Could not open file!\n"; - return; - } - - out << "A line of text\n"; - out << "Another line of text\n"; - - out.flush(); - - out.close(); -} -``` - -Inside this function, we begin by creating a `std::fstream` object called out: - -```c++ -std::fstream out("file.txt", std::ios::out); -``` - -One of the constructors in `std::fstream` takes a C-style string for the first -argument and something called a "mode". A mode in this context refers to how the -file will be opened. Will the file be opened for reading, writing, or even both? -Will reading/writing begin at the beginning of the file or the end? - -In this constructor, the second argument defaults to both reading and writing. -We just want write abilities so we use `std::ios::out`. You can mix and match -different modes together with the bitwise operator `|` (OR). - -Example: `std::fstream out_and_append("file.txt", std::ios::out | std::ios::app);` - -Of course, there are other modes available which we can find in DevDocs C++ File -I/O documentation. At any rate, let's get back to the code: - -```c++ -if (!out.is_open()) -{ - std::cout << "Could not open file!\n"; - return; -} -``` - -These five lines of code are basic error checking to make sure the file is -actually opened. Then, we push a couple of strings to our output file stream: - -```c++ -out << "A line of text\n"; -out << "Another line of text\n"; -``` - -Using a file stream in C++ is the same as using the standard output. However, -we'll need to make sure to do a few things before we're done: - -```c++ -out.flush(); -out.close(); -``` - -Before the function returns, we do a couple of maintenance related tasks. First, -we flush the buffer. Sometimes the function (or in our case, an operator) that -we call to write to the file doesn't immediately write them to disk. It may -still be in memory waiting to be written to the file. We call the method `flush` -to make sure everything in memory is written to disk. - -Next, we close the file. This frees up resources that we are done using. It's a -good idea to always close a file when done. After all, if enough files are open, -the OS might complain and not allow us to open another file until some other -files have been closed. This is called the file descriptor limit and not closing -files and opening new ones over time can exhaust the number of file descriptors -available. - -### Reading from a File - -After we've implemented file writing, we can implement file reading: - -```c++ -void read_file() -{ - std::fstream in; - - in.open("output.txt", std::ios::in); - - if (!in.is_open()) - { - std::cout << "Could not open file!\n"; - return; - } - - std::string line; - while (std::getline(in, line)) - { - std::cout << line << "\n"; - } - - in.close(); -} -``` - -Just like last time, we open the same file. However, this time we're opening it -for reading purposes. Then, we make sure the file is opened. If it isn't, we -print a message to the screen and return: - -```c++ -std::fstream in; - -in.open("output.txt", std::ios::in); - -if (!in.is_open()) -{ - std::cout << "Could not open file!\n"; - return; -} -``` - -After that, we can begin reading: - -```c++ -std::string line; -while (std::getline(in, line)) -{ - std::cout << line << "\n"; -} -``` - -To start, we create an empty `std::string` and loop line by line in the file until -we reach EOF (end of file). `std::getline` takes a reference to a -`std::basic_istream` which `std::fstream` inherits from. The second argument is a -reference to a `std::string`. It returns a reference to a `std::basic_istream`. - -`std::basic_istream` inherits from `std::basic_ios` which overloads the `bool` -operator. This means we can use `std::getline` (or more precisely, -`std::basic_istream`) in boolean contexts such as while conditionals. - -When we're done, we close the file and don't call flush because we just read -from the file and haven't written anything to it: - -```c++ -in.close(); -``` - -And, that's how we read from a file in C++. - -### The Main Function - -As usual, C++ programs cannot be executed without a main function: - -```c++ -int main() -{ - write_file(); - read_file(); -} -``` - -Here, we make a call to each function we've created: `write_file()` and -`read_file()`. And, that's it! - - -## How to Run the Solution - -There are many online compilers such as Compiler Explorer that you can use to -compile C++ code. If you have a compiler installed on your system such g++ or -clang++ use the following commands: - -```console -g++ -o program file.cpp -clang++ -o program file.cpp -``` -And, that's it! You've successfully executed the solution. diff --git a/docs/projects/file-input-output/c-sharp/index.md b/docs/projects/file-input-output/c-sharp/index.md deleted file mode 100644 index 4f47911af9..0000000000 --- a/docs/projects/file-input-output/c-sharp/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-28 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- file-input-output -title: File Input Output in C# -title1: File Input -title2: Output in C# ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.IO; - -const string Path = "output.txt"; -const string Content = """ -line 1 -line 2 -line 3 -"""; - -try -{ - File.WriteAllText(Path, Content); - Console.WriteLine(File.ReadAllText(Path)); -} -catch (IOException ex) -{ - Console.WriteLine($"IO error: {ex.Message}"); -} -``` - -{% endraw %} - -File Input Output in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/c/file-input-output.c b/docs/projects/file-input-output/c/file-input-output.c deleted file mode 100644 index 1cddccf21b..0000000000 --- a/docs/projects/file-input-output/c/file-input-output.c +++ /dev/null @@ -1,61 +0,0 @@ -#define _POSIX_C_SOURCE 200809L -#include -#include - -#define FILENAME "output.txt" - -int write_file() -{ - FILE *handle; - - handle = fopen(FILENAME, "w"); - if (!handle) - { - perror("open file for writing"); - return 1; - } - - fputs("A line of text\n", handle); - fputs("Another line of text\n", handle); - - fclose(handle); - return 0; -} - -int read_file() -{ - char *line = NULL; - ssize_t read; - size_t len = 0; - FILE *handle; - - handle = fopen(FILENAME, "r"); - if (!handle) - { - perror("open file for reading"); - return 1; - } - - while ((read = getline(&line, &len, handle)) != -1) - printf("%s", line); - - fclose(handle); - free(line); - - return 0; -} - -int main(int argc, char **argv) -{ - int rc; - - rc = write_file(); - if (rc != 0) - return EXIT_FAILURE; - - rc = read_file(); - if (rc != 0) - return EXIT_FAILURE; - - return EXIT_SUCCESS; -} diff --git a/docs/projects/file-input-output/c/index.md b/docs/projects/file-input-output/c/index.md deleted file mode 100644 index fb4a913a3a..0000000000 --- a/docs/projects/file-input-output/c/index.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- Ștefan-Iulian Alecu -date: 2018-09-12 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- file-input-output -title: File Input Output in C -title1: File Input -title2: Output in C ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -File Input Output in C - -File Input Output in [C](/languages/c) was written by: - -- Christoph Böhmwalder -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/cobol/index.md b/docs/projects/file-input-output/cobol/index.md deleted file mode 100644 index 620ba034a5..0000000000 --- a/docs/projects/file-input-output/cobol/index.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- file-input-output -title: File Input Output in COBOL -title1: File Input -title2: Output in COBOL ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. file-input-output. - -environment division. -input-output section. -file-control. - select output-file assign to "output.txt" - organization is line sequential - file status is ws-status. - -data division. -file section. -fd output-file. -01 file-line pic x(256). - -working-storage section. -01 ws-status pic xx. - 88 file-ok value "00". - 88 file-eof value "10". - -01 ws-message pic x(256) value "Hello from COBOL!". -01 ws-eof-flag pic x value "n". - 88 eof value "y". - 88 not-eof value "n". - -procedure division. -main. - perform write-file - perform read-file - stop run. - -write-file. - open output output-file - - if not file-ok - display "Error: could not open file for writing" - stop run - end-if - - move ws-message to file-line - write file-line - - close output-file. - -read-file. - open input output-file - - if not file-ok - display "Error: could not open file for reading" - stop run - end-if - - set not-eof to true - perform until eof - read output-file - at end - set eof to true - not at end - display function trim(file-line) - end-read - end-perform - - close output-file. -``` - -{% endraw %} - -File Input Output in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/commodore-basic/index.md b/docs/projects/file-input-output/commodore-basic/index.md deleted file mode 100644 index 7982796227..0000000000 --- a/docs/projects/file-input-output/commodore-basic/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- file-input-output -title: File Input Output in Commodore BASIC -title1: File Input Output -title2: in Commodore BASIC ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 OPEN 1, 1, 1, "output.txt" -20 PRINT#1, "Hello from Commodore Basic" -30 PRINT#1, "This is a line" -40 PRINT#1, "This is another line" -50 PRINT#1, "Goodbye!" -60 CLOSE 1 -70 OPEN 1, 1, 0, "output.txt" -80 INPUT#1, A$ -90 PRINT A$ -100 IF ST = 0 THEN GOTO 80 -110 CLOSE 1 - -``` - -{% endraw %} - -File Input Output in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/dg/index.md b/docs/projects/file-input-output/dg/index.md deleted file mode 100644 index 6c99e7e0fc..0000000000 --- a/docs/projects/file-input-output/dg/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Riley Martine -date: 2018-10-03 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2018-10-10 -layout: default -tags: -- dg -- file-input-output -title: File Input Output in Dg -title1: File Input -title2: Output in Dg ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Dg](/languages/dg) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dg -import '/os' - -write_file = filename s -> - except - err => - open filename 'w' |>.write <| s - err :: OSError => - print "Cannot open file" filename - -read_file = filename -> - except - err => - with fd = open filename 'r' => - print $ fd.read! - err :: OSError => - print "Cannot open file" filename - - -filename = "output.txt" -write_file filename "Example text" -read_file filename - -``` - -{% endraw %} - -File Input Output in [Dg](/languages/dg) was written by: - -- Jeremy Grifski -- Riley Martine - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/elvish/index.md b/docs/projects/file-input-output/elvish/index.md deleted file mode 100644 index c1f903fe21..0000000000 --- a/docs/projects/file-input-output/elvish/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-16 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2025-01-16 -layout: default -tags: -- elvish -- file-input-output -title: File Input Output in Elvish -title1: File Input -title2: Output in Elvish ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -echo "Hello, world!" >> output.txt # Write to output.txt -cat output.txt # Print the contents of output.txt - -``` - -{% endraw %} - -File Input Output in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/euphoria/index.md b/docs/projects/file-input-output/euphoria/index.md deleted file mode 100644 index 776d4c8759..0000000000 --- a/docs/projects/file-input-output/euphoria/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-16 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- file-input-output -title: File Input Output in Euphoria -title1: File Input Output -title2: in Euphoria ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e - -function write_file(sequence filename) - integer fn = open(filename, "w") - if fn < 0 - then - printf(STDERR, "Cannot open %s for write\n", {filename}) - return FALSE - end if - - puts(fn, "Hello from Euphoria!\n") - puts(fn, "This is a line\n") - puts(fn, "This is another line\n") - puts(fn, "Goodbye!\n") - close(fn) - return TRUE -end function - -function read_file(sequence filename) - integer fn = open(filename, "r") - if fn < 0 - then - printf(STDERR, "Cannot open %s for read\n", {filename}) - return FALSE - end if - - object line - while 1 - do - line = gets(fn) - if atom(line) - then - exit - end if - - puts(STDOUT, line) - end while - - close(fn) - return TRUE -end function - -constant filename = "output.txt" -if write_file(filename) -then - read_file(filename) -end if - -``` - -{% endraw %} - -File Input Output in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/f-sharp/index.md b/docs/projects/file-input-output/f-sharp/index.md deleted file mode 100644 index c7afefb79b..0000000000 --- a/docs/projects/file-input-output/f-sharp/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- file-input-output -title: File Input Output in F# -title1: File Input -title2: Output in F# ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System -open System.IO - -type FileError = - | NotFound of string - | AccessDenied of string - | IoError of string - | Unknown of string - - member this.Message = - match this with - | NotFound fn -> $"File '{fn}' does not exist." - | AccessDenied fn -> $"Access denied to file '{fn}'." - | IoError msg -> $"I/O error occurred: {msg}" - | Unknown msg -> $"An unexpected error occurred: {msg}" - -module FileIO = - let private toFileError filename (ex: Exception) = - match ex with - | :? FileNotFoundException -> NotFound filename - | :? UnauthorizedAccessException -> AccessDenied filename - | :? IOException -> IoError ex.Message - | _ -> Unknown ex.Message - - let private wrapIO filename action = - try - action () |> Ok - with ex -> - toFileError filename ex |> Error - - let writeTo (filename: string) (contents: string) = - wrapIO filename (fun () -> File.WriteAllText(filename, contents)) - - let readFrom filename = - wrapIO filename (fun () -> File.ReadLines filename) - -let handleResult = - function - | Ok() -> 0 - | Error(err: FileError) -> - eprintfn "%s" err.Message - 1 - -[] -let main _ = - let filename = "output.txt" - - let contents = - "I am a string.\n\ - I am also a string.\n\ - F# is fun." - - FileIO.writeTo filename contents - |> Result.bind (fun () -> FileIO.readFrom filename) - |> Result.map (Seq.iter (printfn "%s")) - |> handleResult - -``` - -{% endraw %} - -File Input Output in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/gnu-make/index.md b/docs/projects/file-input-output/gnu-make/index.md deleted file mode 100644 index 21b702871c..0000000000 --- a/docs/projects/file-input-output/gnu-make/index.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -authors: -- Ron Zuckerman -- rzuckerm -date: 2023-07-13 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2023-07-29 -layout: default -tags: -- file-input-output -- gnu-make -title: File Input Output in GNU Make -title1: File Input Output -title2: in GNU Make ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -define TEXT -Hello from GNU Make -Here are some lines: -This is line 1 -This is line 2 -Goodbye! -endef - -$(file >output.txt,$(TEXT)) -$(info $(file ` means output to the specified file. - * `>>` means append to the specified file. -* `filename` is the path to the file. -* `text` is the text to be written to the file for the `>` and `>>` file - operations. - -This writes the text (stored in the `TEXT` variable) to a file called -`output.txt`: - -```make -$(file >output.txt,$(TEXT)) -``` - -This reads the text from `output.txt` and displays it using the [info][3] -function. - -```make -$(info $(file - -Welcome to the [File Input Output](/projects/file-input-output) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "io/ioutil" - "log" -) - -func read() (string, error) { - contents, err := ioutil.ReadFile("output.txt") - return string(contents), err -} - -func write(contents string) error { - return ioutil.WriteFile("output.txt", []byte(contents), 0644) -} - -func main() { - err := write("file contents") - if err != nil { - log.Fatal(err) - } - contents, err := read() - if err != nil { - log.Fatal(err) - } - fmt.Println(contents) -} - -``` - -{% endraw %} - -File Input Output in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/haskell/index.md b/docs/projects/file-input-output/haskell/index.md deleted file mode 100644 index ef64004e37..0000000000 --- a/docs/projects/file-input-output/haskell/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-10-22 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2018-10-24 -layout: default -tags: -- file-input-output -- haskell -title: File Input Output in Haskell -title1: File Input Output -title2: in Haskell ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.IO - -main :: IO () -main = do - -- write - handle <- openFile "output.txt" ReadWriteMode - hPutStr handle "file contents" - hClose handle - -- read - handle <- openFile "output.txt" ReadWriteMode - value <- hGetContents handle - -- Print the contents of the file that was read. - -- Haskell reads the file lazily, so the value must be printed before the handle is closed - putStrLn value - hClose handle - -``` - -{% endraw %} - -File Input Output in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/index.md b/docs/projects/file-input-output/index.md deleted file mode 100644 index 6bdad98ff6..0000000000 --- a/docs/projects/file-input-output/index.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -date: 2018-09-10 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-18 -layout: default -tags: -- file-input-output -title: File Input Output -title1: File Input -title2: Output ---- - - - -Welcome to the File Input Output page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Most languages have built-in utilities or functions for reading and writing files. -Many of these input/output functions follow a similar pattern across programming languages: -a string to the path of the file and a "mode". A mode is how the files is opened. -Will the file be opened for reading, writing, or even both? -Will the file be appending new content? Truncated? - - -## Requirements - -In general, a File IO solution should perform the following: - -1. Write some arbitrary content to a file (use `output.txt`) -2. Read back that content and print it to the user - -More specifically, begin with writing a file to disk. In the write function, you should show how -to open a file with write abilities and write some contents to the file. Before closing the file, -you should ensure everything is written to disk. Then, close the file. There should be basic error -checking to confirm file opening was successful. - -With the read file function, open the file with read abilities. Most higher level languages -offer a way to read line by line or even transfer the whole contents into a string. One way -to read the file is to loop line by line and do some processing. Printing each line to the -screen is enough. Like in the write function, make sure there is some basic error checking. - - -## Testing - -Verify that the actual output matches the expected output -(see [Requirements](#requirements)). - - -## Articles - -There are 41 articles: - -- [File Input Output in ALGOL 68](/projects/file-input-output/algol68) -- [File Input Output in AWK](/projects/file-input-output/awk) -- [File Input Output in Ada](/projects/file-input-output/ada) -- [File Input Output in Bash](/projects/file-input-output/bash) -- [File Input Output in Beef](/projects/file-input-output/beef) -- [File Input Output in C](/projects/file-input-output/c) -- [File Input Output in C#](/projects/file-input-output/c-sharp) -- [File Input Output in C++](/projects/file-input-output/c-plus-plus) -- [File Input Output in COBOL](/projects/file-input-output/cobol) -- [File Input Output in Commodore BASIC](/projects/file-input-output/commodore-basic) -- [File Input Output in Dg](/projects/file-input-output/dg) -- [File Input Output in Elvish](/projects/file-input-output/elvish) -- [File Input Output in Euphoria](/projects/file-input-output/euphoria) -- [File Input Output in F#](/projects/file-input-output/f-sharp) -- [File Input Output in GNU Make](/projects/file-input-output/gnu-make) -- [File Input Output in Go](/projects/file-input-output/go) -- [File Input Output in Haskell](/projects/file-input-output/haskell) -- [File Input Output in Java](/projects/file-input-output/java) -- [File Input Output in JavaScript](/projects/file-input-output/javascript) -- [File Input Output in Julia](/projects/file-input-output/julia) -- [File Input Output in Kotlin](/projects/file-input-output/kotlin) -- [File Input Output in Lua](/projects/file-input-output/lua) -- [File Input Output in Mathematica](/projects/file-input-output/mathematica) -- [File Input Output in OCaml](/projects/file-input-output/ocaml) -- [File Input Output in Objective-C](/projects/file-input-output/objective-c) -- [File Input Output in Octave](/projects/file-input-output/octave) -- [File Input Output in Odin](/projects/file-input-output/odin) -- [File Input Output in PHP](/projects/file-input-output/php) -- [File Input Output in Pascal](/projects/file-input-output/pascal) -- [File Input Output in Perl](/projects/file-input-output/perl) -- [File Input Output in PowerShell](/projects/file-input-output/powershell) -- [File Input Output in Python](/projects/file-input-output/python) -- [File Input Output in R](/projects/file-input-output/r) -- [File Input Output in Ruby](/projects/file-input-output/ruby) -- [File Input Output in Rust](/projects/file-input-output/rust) -- [File Input Output in Scala](/projects/file-input-output/scala) -- [File Input Output in Swift](/projects/file-input-output/swift) -- [File Input Output in Tcl](/projects/file-input-output/tcl) -- [File Input Output in TypeScript](/projects/file-input-output/typescript) -- [File Input Output in Visual Basic](/projects/file-input-output/visual-basic) -- [File Input Output in Wren](/projects/file-input-output/wren) - -*** - - \ No newline at end of file diff --git a/docs/projects/file-input-output/java/index.md b/docs/projects/file-input-output/java/index.md deleted file mode 100644 index bde38eadc0..0000000000 --- a/docs/projects/file-input-output/java/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Shubham Raj -date: 2019-10-13 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- file-input-output -- java -title: File Input Output in Java -title1: File Input -title2: Output in Java ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; - -public class FileInputOutput { - - public static void main(String[] args) { - File file = new File("output.txt"); - writeToFile(file); - readFile(file); - } - - public static void readFile(File file) { - - try { - - BufferedReader buffer = new BufferedReader(new FileReader(file)); - try { - String nextLine = buffer.readLine(); - while (nextLine != null) { - System.out.println(nextLine); - nextLine = buffer.readLine(); - } - buffer.close(); - } catch (IOException e) { - - System.out.println("Error occurred while reading the file"); - } - - } catch (FileNotFoundException e) { - - System.out.println("Error occurred while opening the file!"); - } - - } - - public static void writeToFile(File file) { - - String content = "We wish you a Merry Christmas\n" + - "We wish you a Merry Christmas\n" + - "We wish you a Merry Christmas\n" + - "And a happy New Year."; - try { - FileWriter writer = new FileWriter(file); - writer.write(content); - writer.close(); - } catch (IOException e) { - - System.out.println("Error occurred while writing contents to file!"); - } - - } - -} - -``` - -{% endraw %} - -File Input Output in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Shubham Raj - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/javascript/index.md b/docs/projects/file-input-output/javascript/index.md deleted file mode 100644 index 3c2f7dd4a0..0000000000 --- a/docs/projects/file-input-output/javascript/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Manan Gill -date: 2019-10-10 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2019-10-11 -layout: default -tags: -- file-input-output -- javascript -title: File Input Output in JavaScript -title1: File Input Output -title2: in JavaScript ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -//Written with node 10.16.3 -//fs.promises API is still experimental in Node at this time, but it should be preferred over callbacks when is fully developed -fs = require('fs'); - -const filepath = './output.txt'; //create tempfile.txt in this directory - -const text = `The quick brown fox jumped over the lazy pupper -The quick brown fox jumped over the lazy dog -The quick brown fox jumped over the lazy doggo -The quick brown fox jumped over the lazy floof`; - -function writeFile(){ - fs.writeFile(filepath,text, readFile); //passes writing errors to the callback function, readFile -} - -function readFile(err){ - if(err) return console.log(err); - //fs.readFile is called with 'utf8' option, so the output is a string instead of a buffer - fs.readFile(filepath,'utf8',printString); //passes (err, string) to the callback function, printString -} - -function printString(err, data){ - if(err) return console.log(err); - console.log(data); -} - -writeFile(); - -``` - -{% endraw %} - -File Input Output in [JavaScript](/languages/javascript) was written by: - -- Jeremy Grifski -- Manan Gill - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/julia/index.md b/docs/projects/file-input-output/julia/index.md deleted file mode 100644 index de27267642..0000000000 --- a/docs/projects/file-input-output/julia/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- nallovint -date: 2024-07-25 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2024-07-25 -layout: default -tags: -- file-input-output -- julia -title: File Input Output in Julia -title1: File Input -title2: Output in Julia ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -function readfile(file) - open(file) do f - read(f, String) - end -end - -function writefile(file, text) - open(file, "w") do f - write(f, text) - end -end - -function main() - writefile("output.txt", "Hello, world!") - println(readfile("output.txt")) -end - -main() -``` - -{% endraw %} - -File Input Output in [Julia](/languages/julia) was written by: - -- nallovint - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/kotlin/index.md b/docs/projects/file-input-output/kotlin/index.md deleted file mode 100644 index 06f45b02ff..0000000000 --- a/docs/projects/file-input-output/kotlin/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Tim Lange -date: 2019-10-16 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2019-10-16 -layout: default -tags: -- file-input-output -- kotlin -title: File Input Output in Kotlin -title1: File Input -title2: Output in Kotlin ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -import java.io.File -import java.nio.charset.Charset - -fun main(args: Array) { - - val fileName = "output.txt" - - val file = File(fileName) - - if(file.exists()){ - val output = file.readText(Charset.defaultCharset()) - println(output) - } else{ - try { - file.createNewFile() - file.writeText("Hello, World!") - val output = file.readText(Charset.defaultCharset()) - println(output) - }catch (e :Exception){ - println("File could not be created!") - } - } -} - -``` - -{% endraw %} - -File Input Output in [Kotlin](/languages/kotlin) was written by: - -- Tim Lange - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/lua/index.md b/docs/projects/file-input-output/lua/index.md deleted file mode 100644 index 0b3d2ee0f3..0000000000 --- a/docs/projects/file-input-output/lua/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- bhaskar_datta -- Jeremy Grifski -date: 2019-10-31 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- file-input-output -- lua -title: File Input Output in Lua -title1: File Input -title2: Output in Lua ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -function writer() - file_to_be_written = io.open("output.txt","w+") - io.output(file_to_be_written) - io.write("text to be written into output.txt") - io.close(file_to_be_written) -end - - -function reader() - file_to_be_read = io.open("output.txt","r") - io.input(file_to_be_read) - print(io.read()) - io.close(file_to_be_read) -end - -writer() -reader() - -``` - -{% endraw %} - -File Input Output in [Lua](/languages/lua) was written by: - -- bhaskar_datta -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/mathematica/index.md b/docs/projects/file-input-output/mathematica/index.md deleted file mode 100644 index 1f767af150..0000000000 --- a/docs/projects/file-input-output/mathematica/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- file-input-output -- mathematica -title: File Input Output in Mathematica -title1: File Input Output -title2: in Mathematica ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -Module[{file = CreateFile["output.txt"]}, - (* open the file, write by line, close *) - Module[{write = OpenWrite[file]}, - WriteLine[write, #] & /@ { "A line of text", "Another line of text"}; - Close[write]]; - - (* open the file, read all at once, print, close *) - Module[{read = OpenRead[file]}, - Print[ReadString[read]]; - Close[read]]] (* return path to file as result *) - - -(* Valid Tests *) - - -(* Invalid Tests *) - -``` - -{% endraw %} - -File Input Output in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/objective-c/index.md b/docs/projects/file-input-output/objective-c/index.md deleted file mode 100644 index c7b7c976bc..0000000000 --- a/docs/projects/file-input-output/objective-c/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- Cristiano Lopes -- Ștefan-Iulian Alecu -date: 2020-10-04 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- file-input-output -- objective-c -title: File Input Output in Objective-C -title1: File Input Output -title2: in Objective-C ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import -#include - -@interface NSString (FileIO) -- (BOOL)writeToDefaultPath:(NSString*)path error:(NSError**)error; -+ (nullable instancetype)stringWithDefaultPath:(NSString*)path - error:(NSError**)error; -@end - -@implementation NSString (FileIO) - -- (BOOL)writeToDefaultPath:(NSString*)path error:(NSError**)error { - NSURL* url = [NSURL fileURLWithPath:path]; - return [self writeToURL:url - atomically:YES - encoding:NSUTF8StringEncoding - error:error]; -} - -+ (instancetype)stringWithDefaultPath:(NSString*)path error:(NSError**)error { - NSURL* url = [NSURL fileURLWithPath:path]; - return [self stringWithContentsOfURL:url - encoding:NSUTF8StringEncoding - error:error]; -} - -@end - -int main(int argc, const char* argv[]) { - @autoreleasepool { - NSString* path = @"output.txt"; - NSString* content = @"Hello!\nGoodbye!\n"; - NSError* error = nil; - - if (![content writeToDefaultPath:path error:&error]) { - fprintf(stderr, "Write Error: %s\n", - error.localizedDescription.UTF8String); - return EXIT_FAILURE; - } - - NSString* result = [NSString stringWithDefaultPath:path error:&error]; - if (!result) { - fprintf(stderr, "Read Error: %s\n", - error.localizedDescription.UTF8String); - return EXIT_FAILURE; - } - - printf("%s", result.UTF8String); - } - return EXIT_SUCCESS; -} -``` - -{% endraw %} - -File Input Output in [Objective-C](/languages/objective-c) was written by: - -- Cristiano Lopes -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/ocaml/index.md b/docs/projects/file-input-output/ocaml/index.md deleted file mode 100644 index d973d3a3db..0000000000 --- a/docs/projects/file-input-output/ocaml/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-18 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-18 -layout: default -tags: -- file-input-output -- ocaml -title: File Input Output in OCaml -title1: File Input -title2: Output in OCaml ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let filename = "output.txt" - -let sample_text = - {|Some mundane sample text -Some sample text that is mundane -Another line of mundane sample text -|} - -let () = - (try - Out_channel.with_open_text filename (fun oc -> - Out_channel.output_string oc sample_text) - with Sys_error msg -> - Printf.eprintf "Failed to write to '%s': %s\n" filename msg; - exit 1); - - (try In_channel.with_open_text filename (fun ic -> In_channel.input_lines ic) - with Sys_error msg -> - Printf.eprintf "Failed to read from '%s': %s\n" filename msg; - exit 1) - |> List.iter print_endline - -``` - -{% endraw %} - -File Input Output in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/octave/index.md b/docs/projects/file-input-output/octave/index.md deleted file mode 100644 index 6060212214..0000000000 --- a/docs/projects/file-input-output/octave/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- iwishiwasaneagle -- rzuckerm -date: 2020-10-02 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- file-input-output -- octave -title: File Input Output in Octave -title1: File Input -title2: Output in Octave ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -path = "output.txt"; - -% Write content to file -file = fopen(path,'w'); -if file == -1 - fprintf(strcat(path, " does not exist\n")); - return; -end -fprintf(file, "Hello, World!\n"); -fprintf(file, "Goodbye!\n"); -fclose(file); - -% Read content from file -file = fopen(path,'r'); -if file == -1 - fprintf(strcat(path, " does not exist\n")); - return; -end -a = fgetl(file); -while ischar(a) - disp(a); - a = fgetl(file); -end -fclose(file); - -``` - -{% endraw %} - -File Input Output in [Octave](/languages/octave) was written by: - -- iwishiwasaneagle -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/odin/index.md b/docs/projects/file-input-output/odin/index.md deleted file mode 100644 index 3361f0faf1..0000000000 --- a/docs/projects/file-input-output/odin/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- nallovint -date: 2024-07-11 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2024-07-11 -layout: default -tags: -- file-input-output -- odin -title: File Input Output in Odin -title1: File Input -title2: Output in Odin ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main - -import "core:os" -import "core:fmt" -import "core:strings" - -read_file :: proc(filepath: string) { - data, ok := os.read_entire_file(filepath, context.allocator) // context.allocator will track the memory held by this data - if !ok { - fmt.println("Error reading file") - } - defer delete(data, context.allocator) // we're using the allocator to delete the memory. defer means 'execute this code when the function returns' - it := string(data) - for line in strings.split_lines_iterator(&it) { // run through all the lines - fmt.println(line) - } -} - -write_file :: proc(filepath: string) { - data_as_string := "Odin is great!" - data_as_bytes := transmute([]byte)(data_as_string) // 'transmute' casts our string to a byte array - ok := os.write_entire_file(filepath, data_as_bytes) - if !ok { - fmt.println("Error writing file") - } -} - -main :: proc() { - - write_file("output.txt") - read_file("output.txt") -} -``` - -{% endraw %} - -File Input Output in [Odin](/languages/odin) was written by: - -- nallovint - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/pascal/index.md b/docs/projects/file-input-output/pascal/index.md deleted file mode 100644 index f80ecc152b..0000000000 --- a/docs/projects/file-input-output/pascal/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- file-input-output -- pascal -title: File Input Output in Pascal -title1: File Input -title2: Output in Pascal ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program FileIO; - -{$mode objfpc}{$H+} - -uses - SysUtils; - -const - DefaultFileName = 'output.txt'; - -function WriteToFile(const FileName: string): integer; -var - F: TextFile; -begin - Result := 1; // failure by default - try - AssignFile(F, FileName); - Rewrite(F); - - try - Writeln(F, 'A line of text'); - Writeln(F, 'Another line of text'); - Result := 0; // success - finally - CloseFile(F); - end; - except - on E: Exception do - begin - Writeln('Error writing to file "', FileName, '": ', E.Message); - end; - end; -end; - -function ReadFromFile(const FileName: string): integer; -var - F: TextFile; - Line: string; - LinesRead: integer; -begin - Result := 1; // failure by default - LinesRead := 0; - try - AssignFile(F, FileName); - Reset(F); - - try - while not EOF(F) do - begin - ReadLn(F, Line); - Writeln(Line); - Inc(LinesRead); - end; - if LinesRead = 0 then - Writeln('(File "', FileName, '" is empty)'); - Result := 0; // success - finally - CloseFile(F); - end; - except - on E: Exception do - begin - Writeln('Error reading from file "', FileName, '": ', E.Message); - end; - end; -end; - -var - FileName: string; -begin - FileName := DefaultFileName; - - if WriteToFile(FileName) <> 0 then - begin - ExitCode := 1; - Exit; - end; - - if ReadFromFile(FileName) <> 0 then - begin - ExitCode := 1; - Exit; - end; - - ExitCode := 0; -end. - - -``` - -{% endraw %} - -File Input Output in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/perl/index.md b/docs/projects/file-input-output/perl/index.md deleted file mode 100644 index e1479447f7..0000000000 --- a/docs/projects/file-input-output/perl/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Ewerton Queiroz -- Ștefan-Iulian Alecu -date: 2019-10-15 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- file-input-output -- perl -title: File Input Output in Perl -title1: File Input -title2: Output in Perl ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; -use IO::File; - -my $file = "output.txt"; -my $content = <<'EOF'; -Perl is cool! -There's more than one way to do it. -EOF - -# Write to file - -my $w = IO::File->new(">$file") or die "Cannot open $file for writing: $!"; -$w->print($content) or die "Write failed: $!"; -$w->close or die "Cannot close after write: $!"; - -# Read from file - -my $r = IO::File->new("<$file") or die "Cannot open $file for reading: $!"; -print while <$r>; -$r->close or die "Cannot close after read: $!"; - -``` - -{% endraw %} - -File Input Output in [Perl](/languages/perl) was written by: - -- Ewerton Queiroz -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/php/index.md b/docs/projects/file-input-output/php/index.md deleted file mode 100644 index bc2ec425fe..0000000000 --- a/docs/projects/file-input-output/php/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Juan D Frias -- Parker Johansen -date: 2019-10-14 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- file-input-output -- php -title: File Input Output in PHP -title1: File Input -title2: Output in PHP ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [File Input Output](/projects/file-input-output) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Set-File([string]$Filename) { - try { - $StreamWriter = [IO.StreamWriter]::new($FileName) - $StreamWriter.WriteLine("Hello, PowerShell!") - $StreamWriter.WriteLine("A line here") - $StreamWriter.WriteLine("A line there") - $StreamWriter.WriteLine("Goodbye, PowerShell!") - $true - } catch { - Write-Host "Cannot write to file ${Filename}: $($_.Exception.Message)" - $false - } finally { - if ($StreamWriter) { - $StreamWriter.Close() - $StreamWriter.Dispose() - } - } -} - -function Get-File([string]$Filename) { - try { - foreach ($Line in Get-Content -Path $Filename -ErrorAction Stop) { - Write-Host $Line - } - $true - } catch { - Write-Host "Cannot read from file ${Filename}: $($_.Exception.Message)" - $false - } -} - -$Filename = "output.txt" -if (-not (Set-File($Filename))) { - Exit 1 -} - -if (-not (Get-File($Filename))) { - Exit 1 -} - -``` - -{% endraw %} - -File Input Output in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/python/index.md b/docs/projects/file-input-output/python/index.md deleted file mode 100644 index 603acf978a..0000000000 --- a/docs/projects/file-input-output/python/index.md +++ /dev/null @@ -1,201 +0,0 @@ ---- -authors: -- Ganesh Naik -- Jeremy Grifski -- Noah Nichols -- rzuckerm -date: 2018-09-12 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- file-input-output -- python -title: File Input Output in Python -title1: File Input -title2: Output in Python ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -def write_file(): - try: - with open("output.txt", "w") as out: - out.write("Hi! I'm a line of text in this file!\n") - out.write("Me, too!\n") - except OSError as e: - print(f"Cannot open file: {e}") - return - - -def read_file(): - try: - with open("output.txt", "r") as in_file: - for line in in_file: - print(line.strip()) - except OSError as e: - print(f"Cannot open file to read: {e}") - return - - -if __name__ == '__main__': - write_file() - read_file() - -``` - -{% endraw %} - -File Input Output in [Python](/languages/python) was written by: - -- Ganesh Naik -- Jeremy Grifski -- Noah Nichols - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -We'll first present the solution in its entirety. Then, we'll go over the code -line by line. - -Afterward, we'll take a look at how to run the solution. - -### Writing to a File - -As you may have noticed above, our file writing procedure has been broken out -into its own function: - -```python -def write_file(): - try: - with open("output.txt", "w") as out: - out.write("Hi! I'm a line of text in this file!\n") - out.write("Me, too!\n") - except OSError as e: - print(f"Cannot open file: {e}") - return -``` - -First, we setup up a `try/except` block to catch any exceptions that might occur -when we want to open a file: - -```python -try: - with open("output.txt", "w") as out: - ... -except OSError as e: - print("Cannot open file: {}", e) -``` - -The Python documentation tells us if `open()` fails to create a new file, it will -raise an `OSError` exception. If we do get an exception, we will exit the method. - -Next, if no exceptions occurred, we can now write to the file using the `write()` -method: - -```python -out.write("Hi! I'm a line of text in this file!\n") -out.write("Me, too!\n") -``` - -As we can see, we attempt to output a couple of lines to the text file. The -[with][1] statement sets up a context that will automatically close the file -when the context is exited. - -### Reading From a File - -After we write to a file, we can read back from that file. Naturally, we've -broken the reading procedure into its own function: - -```python - try: - with open("output.txt", "r") as in_file: - for line in in_file: - print(line.strip()) - except OSError as e: - print(f"Cannot open file to read: {e}") - return -``` - -Just like when we were opening the file for writing purposes, we surround the -code that could potentially raise exceptions in a `try/except` block: - -```python -try: - with open("output.txt", "r") as in_file: - ... -except OSError as e: - print(f"Cannot open file to read: {e}") - return -``` - -If an exception occurs, we report the error and exit the function. - -Next, we have a while loop that iterates over each line in the file: - -```python -for line in in_file: - print(line.strip()) -``` - -As we can see, the loop performs some basic processing before we print the line -out onto the screen. When we get a line from the file, we also get the newline. -If we print it with the newline we print an extra empty line because print -automatically adds a newline by default. To fix this problem we use `strip()` to -strip away any newlines at the end of the line. This loop will end when we reach -EOF (end of file). - -The [with][1] statement sets up a context that will automatically close the file -when the context is exited. - -### The Main Function - -All of this code would be useless if we didn't execute it somewhere. Thankfully, -we can drop everything into the main function: - -```python -if __name__ == '__main__': - write_file() - read_file() -``` - -And, that's it! We've conquered File IO in Python. - -[1]: https://docs.python.org/3/reference/compound_stmts.html#with - - -## How to Run the Solution - -As usual, you're free to use an online Python interpreter such as the one on -Repl and run the solution there. Alternatively, if you have a Python interpreter -installed on your machine, you can use the following command: - -```console -python file-input-output.py -``` - -After you execute this command, you should be able to find a nearby `output.txt` -file containing the arbitrary text we used earlier. If so, you've successfully -run the program. diff --git a/docs/projects/file-input-output/r/index.md b/docs/projects/file-input-output/r/index.md deleted file mode 100644 index 49b4ff2b6f..0000000000 --- a/docs/projects/file-input-output/r/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- manasmithamn -date: 2020-10-25 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2020-10-25 -layout: default -tags: -- file-input-output -- r -title: File Input Output in R -title1: File Input -title2: Output in R ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r - -file_create_result = tryCatch({ -#Open and write 2 lines to the file. - fileConn<-file("output.txt") - writeLines(c("Hello","World\n"), fileConn) - writeLines(c("Writing this file using R"), fileConn) - close(fileConn) -}, - warning = function( w ) - { - cat("Warning while opening the file") - }, - error = function( w ) - { - cat("Error while opening the file") - } -) -# Catch File Open Error -if(file.exists("output.txt")){ - f_open = readLines("output.txt") - singleString <- paste(readLines("output.txt"), collapse=" ") - cat(singleString) -} else{ - cat("File doesn't exist") -} - -``` - -{% endraw %} - -File Input Output in [R](/languages/r) was written by: - -- manasmithamn - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/ruby/index.md b/docs/projects/file-input-output/ruby/index.md deleted file mode 100644 index 75e70ab731..0000000000 --- a/docs/projects/file-input-output/ruby/index.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Noah -- rzuckerm -- Ștefan-Iulian Alecu -date: 2018-09-13 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- file-input-output -- ruby -title: File Input Output in Ruby -title1: File Input -title2: Output in Ruby ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -content = <<~TEXT - This is a line written by a Ruby program - This line also -TEXT - -File.write("output.txt", content) - -File.foreach("output.txt") do |line| - puts line -end - -``` - -{% endraw %} - -File Input Output in [Ruby](/languages/ruby) was written by: - -- Noah -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of May 07 2026 19:26:56. The solution was first committed on Sep 13 2018 20:31:06. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Before reading on, why not try to figure out how it works? - -### Writing - -For modularity and readability, we have extracted the file writing code into -its own function: - -```ruby -def write_file - out = File.new("output.txt", "w") - - out << "This is a line written by a Ruby program\n" - out << "This line also" - - out.flush() - out.close() -end -``` - -On the first line we call the function File.new(): - -```ruby -out = File.new("output.txt", "w") -``` - -It takes an argument to the path of the file and a mode. A mode is how we want -the file to be opened. By default, it opens for reading. We want to write -abilities so we specify `"w"` for writing. - -For the next two lines we write arbitrary text to the file: - -```ruby -out << "This is a line written by a Ruby program\n" -out << "This line also" -``` - -In this sample code we used the bitshift left operators to write the text. We -could have used the `write()` method to write text instead of using the operators. - -Next, we flush the file: - -```ruby -out.flush() -``` - -Sometimes when we make calls to write not everything may get written down to -disk. Only a fraction could be in the file and the rest is in memory waiting -to get written to the file. To ensure everything is written, we call the method -`flush()`. - -Lastly, we close the file to free up its resources: - -```ruby -out.close() -``` - -This is something you should always do with resources when you're done with them. - -### Reading - -Like with the `write_file()` function, we put the code for reading the file in -its own function: - -```ruby -def read_file - in_file = File.open("output.txt", "r") - - in_file.each_line do |line| - puts line - end - - in_file.close() -end -``` - -To begin, we open a file on the first line: - -```ruby -in_file = File.open("output.txt", "r") -``` - -`File.open()` takes an argument to the path of the file and a mode. By default, -it opens the file for reading purposes, but for the sake of being explicit, I -passed `"r"` for the mode. - -The next three lines loop through the file and print out each line: - -```ruby -in_file.each_line do |line| - puts line -end -``` - -Finally, we close the file: - -```ruby -in_file.close() -``` - -And, that's it for reading. - -### Scripting - -Since Ruby is a scripting language, we can call the two functions we've just -defined back-to-back at the end of our file: - -```ruby -write_file() -read_file() -``` - -And, that'll do it! - - -## How to Run the Solution - -Websites like Repl allow you to write and run code of different programming -languages in the browser. Feel free to drop our solution into one of your -favorite online editors. - -If you have Ruby installed on your computer/mac, you can run the following command: - -```console -ruby file-io.rb -``` - -To verify everything has worked correctly, you should see the contents of the -file printed to the screen. In addition, the dummy file should be located -alongside your script now. Feel free to check that out and let us know. diff --git a/docs/projects/file-input-output/rust/index.md b/docs/projects/file-input-output/rust/index.md deleted file mode 100644 index 476fce258f..0000000000 --- a/docs/projects/file-input-output/rust/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Noah -date: 2018-09-13 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2018-09-13 -layout: default -tags: -- file-input-output -- rust -title: File Input Output in Rust -title1: File Input -title2: Output in Rust ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::fs::File; -use std::io::prelude::*; -use std::io::Result; - -fn write_file() -> Result<()> { - let mut out = File::create("output.txt")?; - - let bytes_written = out.write(b"A line of text written to this file in Rust!\n").unwrap_or(0); - let bytes_written2 = out.write(b"Another line also written by a Rust program!\n").unwrap_or(0); - - if bytes_written == 0 || bytes_written2 == 0 { - () - } - - out.flush()?; - - Ok(()) -} - -fn read_file() -> Result<()> { - let mut in_file = File::open("output.txt")?; - - let mut line = String::new(); - match in_file.read_to_string(&mut line) { - Ok(_) => println!("{}", line), - Err(_) => panic!("Could not read contents into string!") - } - - Ok(()) -} - -fn main() -> Result<()> { - write_file()?; - Ok(read_file()?) -} -``` - -{% endraw %} - -File Input Output in [Rust](/languages/rust) was written by: - -- Noah - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/scala/index.md b/docs/projects/file-input-output/scala/index.md deleted file mode 100644 index 256467fd56..0000000000 --- a/docs/projects/file-input-output/scala/index.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Vee Ng -- Ștefan-Iulian Alecu -date: 2019-04-05 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- file-input-output -- scala -title: File Input Output in Scala -title1: File Input -title2: Output in Scala ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -import java.nio.charset.StandardCharsets -import java.nio.file.{Files, Path, Paths} -import scala.jdk.CollectionConverters.* -import scala.util.Try - -extension (p: Path) - def readLines: Try[List[String]] = - Try(Files.readAllLines(p, StandardCharsets.UTF_8).asScala.toList) - - def writeString(content: String): Try[Unit] = - Try(Files.writeString(p, content, StandardCharsets.UTF_8)).map(_ => ()) - -object FileInputOutput: - private val path = Paths.get("output.txt") - private val content = - """I am a string. - |I am also a string. - |Scala is fun!""".stripMargin - - def main(args: Array[String]): Unit = - val program = - for - _ <- path.writeString(content) - lines <- path.readLines - yield lines - - program.fold( - err => System.err.println(s"File operation failed: ${err.getMessage}"), - res => res.foreach(println) - ) -``` - -{% endraw %} - -File Input Output in [Scala](/languages/scala) was written by: - -- rzuckerm -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Vee Ng - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Apr 11 2026 13:25:12. The solution was first committed on May 15 2023 16:11:44. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -First of all let's look at the read / write functions as a whole, and their usages. - -### Read from a file - -In many real world scenario, your program usually takes one of the two approaches when dealing with undeterministic I/O -(also called side-effects): fail loudly or fail silently. - -We want to fail loudly, i.e. throw exception, stop execution flow or output error as results, when the I/O is critical -for the program to proceed. - -```scala - // reading file then write to stdout - // write exception when fail - def readFromFile(filename: String) { - try { - val buffer = Source.fromFile(filename) - val lines = buffer.getLines - - lines.foreach(println) - buffer.close - } catch { - case e: FileNotFoundException => println(s"File ${filename} does not exist.") - case e: IOException => println(s"I/O Exception when reading from ${filename}.") - case e: Throwable => println(s"Error ${e.getMessage} when reading from ${filename}.") - } - } -``` - -Similar to many other language, `scala.io.Source` provides the ability to get a file into a buffer-like instance, -in our case `BufferedSource`, using `fromFile`. `Source` is built-in with `Java` exceptions to let us know what -causes the failure in opening / reading the file. - -Since we are dealing with a text file, we can simply use `getLines` to convert `BufferedSource` to a `Iterator[String]`. -We can also convert `Iterator[String]` to a `List[String]` or `Array[String]` using `.toList` and `.toArray` -respectively. - -`Iterator` interface allows us to traverse each line, using `foreach`. The syntactic sugar `lines.foreach(println)` -you see here is short-hand for: - -```scala -lines.foreach(line => println(line)) -``` - -or - -```scala -for (line <- lines) { - println(line) -} -``` - -After extracting the buffer, we close it with `buffer.close`. - -`catch` block here demonstrate Scala's pattern matching feature. By default, all exceptions can be caught -as a `Throwable`. -However we have the option to deal with specific exception (`FileNotFoundException` or `IOException`) separately. - -Usage is simple: - -```scala -readFromFile("output.txt") -``` - -### Write to a file - -Similar pattern for writing to files. Unlike read, which is usually at the beginning of some logic and having -the input type determined gains us benefits, write is usually a void function with no return types, and called -at the end of execution (result, log, etc.). - -```scala -// write to file -// stdout exception when fail -def writeToFile(filename: String, contents: String) { - try { - val writer = new PrintWriter(new File(filename)) - writer.write(contents) - writer.close - } catch { - case e: FileNotFoundException => println(s"Cannot write into file ${filename}.") - case e: Throwable => println(s"Error ${e.getMessage} when writing to file ${filename}.") - } -} - -Usage is straightforward, simply call the function: - -```scala -writeToFile("output.txt", "I am a string.\nI am also a string.\nScala is fun!\n") -``` - - -## How to Run the Solution - -The source requires standard scala compiler and runtime: `scalac` and `scala`. Before running the program, make sure -the files are in the same directory as the compiled `.class`. - -```console -$ scalac FileInputOutput.scala -$ scala FileInputOutput -``` diff --git a/docs/projects/file-input-output/swift/index.md b/docs/projects/file-input-output/swift/index.md deleted file mode 100644 index e7523bbf5d..0000000000 --- a/docs/projects/file-input-output/swift/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- file-input-output -- swift -title: File Input Output in Swift -title1: File Input -title2: Output in Swift ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let url = URL(fileURLWithPath: "output.txt") -let text = "Line 1\nLine 2\nLine 3" - -// Write: Create file and write content -try? text.write(to: url, atomically: true, encoding: .utf8) - -// Read: Print file content directly -if let content = try? String(contentsOf: url, encoding: .utf8) { - print(content) -} - -``` - -{% endraw %} - -File Input Output in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/tcl/index.md b/docs/projects/file-input-output/tcl/index.md deleted file mode 100644 index 030877a1fa..0000000000 --- a/docs/projects/file-input-output/tcl/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-08 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2025-10-08 -layout: default -tags: -- file-input-output -- tcl -title: File Input Output in Tcl -title1: File Input -title2: Output in Tcl ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -#!/usr/bin/env tclsh - -proc writeToFile {filename} { - if {[catch {set fh [open $filename w]} err]} { - puts "Error opening file for writing \"$filename\": $err" - return 1 - } - - if {[catch { - puts $fh "A line of text" - puts $fh "Another line of text" - flush $fh - } err]} { - puts "Error writing to file \"$filename\": $err" - close $fh - return 1 - } - - close $fh - return 0 -} - -proc readFromFile {filename} { - if {[catch {set fh [open $filename r]} err]} { - puts "Error reading from file \"$filename\": $err" - return 1 - } - - set linesRead 0 - if {[catch { - while {[gets $fh line] >= 0} { - puts $line - incr linesRead - } - } err]} { - puts "Error reading from file \"$filename\": $err" - close $fh - return 1 - } - - if {$linesRead == 0} { - puts "(File \"$filename\" is empty)" - } - - close $fh - return 0 -} - -set filename "output.txt" -if {[ writeToFile $filename] != 0} { exit 1 } -if {[readFromFile $filename] != 0} { exit 1 } - -exit 0 - - -``` - -{% endraw %} - -File Input Output in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/typescript/index.md b/docs/projects/file-input-output/typescript/index.md deleted file mode 100644 index 5dfa725f7b..0000000000 --- a/docs/projects/file-input-output/typescript/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Antonino Bertulla -date: 2023-10-04 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2023-10-04 -layout: default -tags: -- file-input-output -- typescript -title: File Input Output in TypeScript -title1: File Input Output -title2: in TypeScript ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -import { Readable } from "stream"; -import * as fs from 'fs' - -const filepath = './output.txt'; //create tempfile.txt in this directory -const write$ = fs.createWriteStream(filepath); -write$.on('finish', () => fs.createReadStream(filepath).on('error', console.error).pipe(process.stdout)); -write$.on('error', console.error); - -const readableStream = new Readable(); -const texts = [ - 'The quick brown fox jumped over the lazy pupper\n', - 'The quick brown fox jumped over the lazy dog\n', - 'The quick brown fox jumped over the lazy doggo\n', - 'The quick brown fox jumped over the lazy floof' -]; - -for (const text of texts) { - readableStream.push(text); -} -readableStream.push(null); - -readableStream.pipe(write$) - -``` - -{% endraw %} - -File Input Output in [TypeScript](/languages/typescript) was written by: - -- Antonino Bertulla - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/visual-basic/index.md b/docs/projects/file-input-output/visual-basic/index.md deleted file mode 100644 index 6f1cec345b..0000000000 --- a/docs/projects/file-input-output/visual-basic/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- file-input-output -- visual-basic -title: File Input Output in Visual Basic -title1: File Input Output -title2: in Visual Basic ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System.IO - -Module FileInputOutput - - Private Const FileName As String = "output.txt" - Private Const Content As String = "Hello from VB.NET!" - - Public Sub WriteFile() - File.WriteAllText(FileName, Content) - End Sub - - Public Function ReadFile() As String - Return File.ReadAllText(FileName) - End Function - - Public Sub Main() - - Try - WriteFile() - Console.WriteLine(ReadFile()) - Catch ex As Exception - Console.WriteLine($"File operation failed: {ex.Message}") - End Try - - End Sub - -End Module -``` - -{% endraw %} - -File Input Output in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/file-input-output/wren/index.md b/docs/projects/file-input-output/wren/index.md deleted file mode 100644 index 979b032797..0000000000 --- a/docs/projects/file-input-output/wren/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-21 -featured-image: file-input-output-in-every-language.jpg -last-modified: 2025-01-21 -layout: default -tags: -- file-input-output -- wren -title: File Input Output in Wren -title1: File Input -title2: Output in Wren ---- - - - -Welcome to the [File Input Output](/projects/file-input-output) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -import "io" for File - -File.create("output.txt") {|f| - f.writeBytes("My brain has too many tabs open.") -} - -System.print(File.read("output.txt")) - -``` - -{% endraw %} - -File Input Output in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/ada/index.md b/docs/projects/fizz-buzz/ada/index.md deleted file mode 100644 index b572c7a6b4..0000000000 --- a/docs/projects/fizz-buzz/ada/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Rebecca Riffle -date: 2024-11-08 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-11-08 -layout: default -tags: -- ada -- fizz-buzz -title: Fizz Buzz in Ada -title1: Fizz Buzz -title2: in Ada ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Text_IO; use Text_IO; - -procedure Fizz_Buzz is - Counter : Integer := 1; -begin - while Counter < 101 - loop - if Counter mod 3 = 0 and Counter mod 5 = 0 then - Put_Line("FizzBuzz"); - elsif Counter mod 3 = 0 then - Put_Line("Fizz"); - elsif Counter mod 5 = 0 then - Put_Line("Buzz"); - else - Put_Line(Integer'Image(Counter)); - end if; - Counter := Counter + 1; - end loop; -end Fizz_Buzz; -``` - -{% endraw %} - -Fizz Buzz in [Ada](/languages/ada) was written by: - -- Rebecca Riffle - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/algol60/index.md b/docs/projects/fizz-buzz/algol60/index.md deleted file mode 100644 index d1d98b0edf..0000000000 --- a/docs/projects/fizz-buzz/algol60/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-17 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-03-17 -layout: default -tags: -- algol60 -- fizz-buzz -title: Fizz Buzz in ALGOL 60 -title1: Fizz Buzz -title2: in ALGOL 60 ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - integer procedure mod(x, n); - value x, n; - integer x, n; - begin - mod := x - n * (x % n) - end mod; - - integer i; - for i := 1 step 1 until 100 do - begin - if mod(i, 15) = 0 then outstring(1, "FizzBuzz") - else if mod(i, 3) = 0 then outstring(1, "Fizz") - else if mod(i, 5) = 0 then outstring(1, "Buzz") - else outinteger(1, i); - outstring(1, "\n") - end -end - -``` - -{% endraw %} - -Fizz Buzz in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/algol68/index.md b/docs/projects/fizz-buzz/algol68/index.md deleted file mode 100644 index 76d33058ec..0000000000 --- a/docs/projects/fizz-buzz/algol68/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-18 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-01-21 -layout: default -tags: -- algol68 -- fizz-buzz -title: Fizz Buzz in ALGOL 68 -title1: Fizz Buzz -title2: in ALGOL 68 ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -FOR n FROM 1 TO 100 -DO - STRING s := (n MOD 3 = 0 | "Fizz" | ""); - s +:= (n MOD 5 = 0 | "Buzz" | ""); - printf(($gl$, (s /= "" | s | whole(n, 0)))) -OD - -``` - -{% endraw %} - -Fizz Buzz in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/arkscript/index.md b/docs/projects/fizz-buzz/arkscript/index.md deleted file mode 100644 index f9260b449f..0000000000 --- a/docs/projects/fizz-buzz/arkscript/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- arkscript -- fizz-buzz -title: Fizz Buzz in ArkScript -title1: Fizz Buzz in -title2: ArkScript ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [ArkScript](/languages/arkscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```arkscript -(mut i 1) -( - while (<= i 100) { - ( - if (= 0 (mod i 15)) (print "FizzBuzz") ( - if (= 0 (mod i 5)) (print "Buzz") - (if (= 0 (mod i 3)) (print "Fizz") - (print i)))) - (set i (+ i 1)) - } -) - -``` - -{% endraw %} - -Fizz Buzz in [ArkScript](/languages/arkscript) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/awk/index.md b/docs/projects/fizz-buzz/awk/index.md deleted file mode 100644 index 70484a4df4..0000000000 --- a/docs/projects/fizz-buzz/awk/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-07 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-04-07 -layout: default -tags: -- awk -- fizz-buzz -title: Fizz Buzz in AWK -title1: Fizz Buzz -title2: in AWK ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -BEGIN { - for (i = 1; i <= 100; i++) { - result = "" - if (i % 3 == 0) { - result = result "Fizz" - } - - if (i % 5 == 0) { - result = result "Buzz" - } - - if (!result) { - result = result sprintf("%d", i) - } - - print result - } -} - -``` - -{% endraw %} - -Fizz Buzz in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/ballerina/index.md b/docs/projects/fizz-buzz/ballerina/index.md deleted file mode 100644 index d064472068..0000000000 --- a/docs/projects/fizz-buzz/ballerina/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- ballerina -- fizz-buzz -title: Fizz Buzz in Ballerina -title1: Fizz Buzz in -title2: Ballerina ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Ballerina](/languages/ballerina) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ballerina -import ballerina/io; - -public function main() { - foreach int i in int:range(1, 101, 1) { - if i % 15 == 0 { - io:println("FizzBuzz"); - } else if i % 5 == 0 { - io:println("Buzz"); - } else if i % 3 == 0 { - io:println("Fizz"); - } else { - io:println(i); - } - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Ballerina](/languages/ballerina) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/bash/index.md b/docs/projects/fizz-buzz/bash/index.md deleted file mode 100644 index 20d3ac3ccf..0000000000 --- a/docs/projects/fizz-buzz/bash/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -date: 2018-08-31 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2018-08-31 -layout: default -tags: -- bash -- fizz-buzz -title: Fizz Buzz in Bash -title1: Fizz Buzz -title2: in Bash ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -for i in {1..100}; do - if (( $i % 15 == 0 )); then - echo "FizzBuzz" - elif (( $i % 5 == 0 )); then - echo "Buzz" - elif (( $i % 3 == 0 )); then - echo "Fizz" - else - echo $i - fi -done - -``` - -{% endraw %} - -Fizz Buzz in [Bash](/languages/bash) was written by: - -- Christoph Böhmwalder - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/batch/index.md b/docs/projects/fizz-buzz/batch/index.md deleted file mode 100644 index df483d252d..0000000000 --- a/docs/projects/fizz-buzz/batch/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-20 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-20 -layout: default -tags: -- batch -- fizz-buzz -title: Fizz Buzz in Batch -title1: Fizz Buzz -title2: in Batch ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Batch](/languages/batch) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```batch -@ECHO OFF -SETLOCAL ENABLEDELAYEDEXPANSION - -for /l %%i in (1,1,100) do ( - set /A "m3=%%i %% 3" - set /A "m5=%%i %% 5" - set /A "m15=%%i %% 15" - - if !m15! equ 0 ( - echo FizzBuzz - ) else if !m3! equ 0 ( - echo Fizz - ) else if !m5! equ 0 ( - echo Buzz - ) else ( - echo %%i - ) -) - -ENDLOCAL - -``` - -{% endraw %} - -Fizz Buzz in [Batch](/languages/batch) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/beef/index.md b/docs/projects/fizz-buzz/beef/index.md deleted file mode 100644 index 1e945010cb..0000000000 --- a/docs/projects/fizz-buzz/beef/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-14 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-01-14 -layout: default -tags: -- beef -- fizz-buzz -title: Fizz Buzz in Beef -title1: Fizz Buzz -title2: in Beef ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace FizzBuzz; - -class Program -{ - public static int Main(String[] args) - { - for (int i in 1...100) - { - String line = scope String(); - if ((i % 3) == 0) - { - line.Append("Fizz"); - } - - if ((i % 5) == 0) - { - line.Append("Buzz"); - } - - if (line.Length == 0) - { - i.ToString(line); - } - - Console.WriteLine(line); - } - return 0; - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/befunge/index.md b/docs/projects/fizz-buzz/befunge/index.md deleted file mode 100644 index 4a04912bea..0000000000 --- a/docs/projects/fizz-buzz/befunge/index.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Stuart -- Stuart Irwin -date: 2018-10-22 -featured-image: fizz-buzz-in-befunge.jpg -last-modified: 2023-05-15 -layout: default -tags: -- befunge -- fizz-buzz -title: Fizz Buzz in Befunge -title1: Fizz Buzz -title2: in Befunge ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Befunge](/languages/befunge) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```befunge -1 > :3% v - v \0 _ "zziF",,,,v - v \1 < - > :5% v - v _v#\ _ "zzuB",,,,v - v >:. v $\ < - v < @ - > :25* ::, *1-` | - ^ +1 < - - -``` - -{% endraw %} - -Fizz Buzz in [Befunge](/languages/befunge) was written by: - -- Stuart - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Befunge, like many other esoteric languages, has a very unique look to it, and is very complex at first glance. Each operation is denoted by a single character, and the file can be traversed in four directions. If you have not read about it before, do that first, starting here: [The Befunge Programming Language][1]. - -The Fizz-Buzz problem itself is here: - - If a number is divisible by 3, print the word 'Fizz' instead of the number. - If the number is divisible by 5, print the word 'Buzz' instead of the number. - Finally, if the number is divisible by both 3 and 5, print 'FizzBuzz' instead - of the number. Otherwise, just print the number. - -Don't worry if the code looks confusing, we will break it down and go over the different sections. - -### First set - -The first section to look at will handle the Fizz statement, and adds a boolean value to the stack for use later. - -``` -1 > :3% v - v \0 _ "zziF",,,,v - v \1 < -``` - -The program starts at the top left corner, meaning that the stack will start with a 1, and then cross over the top line, running the characters `:3%`. - -- `:` will make a copy of the top value, which will count the current iteration. -- `3` will push a 3 on top of the stack. -- `%` will run modulus on the top two values, returning the remainder of x / 3. - -The pointer then moves down onto the `_`, which will run as an if statement, moving right if the top or the stack is 0, and left if it is anything else. Combined with the previous statements, it will move right whenever the initial value is divisible by 3, pushing `zziF` to the stack and printing it out in the proper order. - -In both cases, the instruction pointer then returns to the left, adding either a 1 to the stack after printing Fizz, or a 0 if nothing was printed. Each `\` then swaps the top two values, putting this indicator value below the current run count. - -### Second set - -The second section of code is very similar, intended to handle the Buzz part of the program. - -``` - > :5% v - v _v#\ _ "zzuB",,,,v - v >:. v $\ < - v < -``` - -Like the previous section, `:5%` will calculate the remainder of x / 5, and the `_` will send the pointer left or right accordingly. - -- If the value is divisible by 5, the program will print out `Buzz` and head to the downward arrow at the center, `\$` deleting the 0 or 1 value that was stored earlier. -- If the current iteration is not divisible, `\` will switch that number with the binary value stored in the first set, and `#` will jump straight to the `_` statement at the start of the second line. This checks the previous boolean, and in the case that nothing has been printed out so far, directs the instruction pointer to `:.`, printing out the run count as a numerical value. - -### Cleanup - -The final section handles the new line and sets up the next loop of the program. - -``` - v @ - > :25* ::, *1-` | - ^ +1 < -``` - -The middle line has three main statements. `:25*` copies the current value and pushes 2 * 5 to the stack. `::,` makes 2 more copies of 10, then prints out one of them as a newline. Finally, `*1-'` multiplies the 10s together, subtracts 1 from it to get 99, then pushes 1 if the current iteration is larger. - -At the end, `|` checks for a zero on top of the stack, sending the pointer downward if it is found. If there is a 1 and the current iteration is > 99, then the `@` symbol is activated instead, ending the program. - -If the counter has not yet reached 100, `1+` adds 1 to it, and the pointer is sent back to the beginning of the loop. - -[1]: https://esolangs.org/wiki/Befunge - - -## How to Run the Solution - -Because of the particular design of the language, it is recommended to use a Befunge interpreter. It is a lot easier to learn and play around with when you can step through and see what the pointer is doing. - -- [Befunge Playground][2] -- [jsFunge IDE][3] -- [Befunge-93 Interpreter][4] - -If you do want to use a compiler, here is another option: - -- [BefunUtils][6] - -[2]: https://www.bedroomlan.org/tools/befunge-playground/#prog=hello,mode=edit -[3]: https://befunge.flogisoft.com/ -[4]: http://qiao.github.io/javascript-playground/visual-befunge93-interpreter/ -[6]: https://github.com/Mikescher/BefunUtils diff --git a/docs/projects/fizz-buzz/boo/index.md b/docs/projects/fizz-buzz/boo/index.md deleted file mode 100644 index 0378bd5b19..0000000000 --- a/docs/projects/fizz-buzz/boo/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-17 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-04-17 -layout: default -tags: -- boo -- fizz-buzz -title: Fizz Buzz in Boo -title1: Fizz Buzz -title2: in Boo ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Boo](/languages/boo) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```boo -for n in range(1, 101): - s = "" - s += "Fizz" if n % 3 == 0 - s += "Buzz" if n % 5 == 0 - s += "$(n)" if not s - print s - -``` - -{% endraw %} - -Fizz Buzz in [Boo](/languages/boo) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/brainfuck/index.md b/docs/projects/fizz-buzz/brainfuck/index.md deleted file mode 100644 index 4ab08c515b..0000000000 --- a/docs/projects/fizz-buzz/brainfuck/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -date: 2018-08-24 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2018-08-24 -layout: default -tags: -- brainfuck -- fizz-buzz -title: Fizz Buzz in Brainfuck -title1: Fizz Buzz in -title2: Brainfuck ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Brainfuck](/languages/brainfuck) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```brainfuck -++++++++++>>++++++++++[<++++++++++>-]<[>>+>>+++>>>>+>+>+<<<<<<<<[>+>->+<[>]>[<+> --]<<[<]>-]>>>[>>>-<<<[-]][-]<[-]+++++<[<+>-]<[>+>->+<[>]>[<+>-]<<[<]>-]>>>[>>>>- -<<<<[-]]>>>[>>>-[------->+<]>---.[-->+++<]>.-[--->+<]>++..[-]<<<<[-]<<[-]]>[>>++ -++[++++>---<]>-.++[----->+<]>+.+++++..[-]<<<[-]<[-]]>[<<<<<<<[>>>>>>>>+>>>>>>>>+ -<<<<<<<<<<<<<<<<-]>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>-]<<<<<<++++ -++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[-<+>]> -+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++<]>.[ --]]<<++++++[-<++++++++>]<.[-]<<[-<+>]<[-]<[-]]<<<<<[-]<[-]<[<+>-]<<<<.>-] - -``` - -{% endraw %} - -Fizz Buzz in [Brainfuck](/languages/brainfuck) was written by: - -- Christoph Böhmwalder - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/c-plus-plus/index.md b/docs/projects/fizz-buzz/c-plus-plus/index.md deleted file mode 100644 index cdd6d03e61..0000000000 --- a/docs/projects/fizz-buzz/c-plus-plus/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Ford Smith -- Ștefan-Iulian Alecu -date: 2019-10-09 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- fizz-buzz -title: Fizz Buzz in C++ -title1: Fizz Buzz -title2: in C++ ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include - -int main() { - for (int i = 1; i <= 100; ++i) { - const bool fizz = (i % 3 == 0); - const bool buzz = (i % 5 == 0); - - if (fizz && buzz) { - std::cout << "FizzBuzz\n"; - } else if (fizz) { - std::cout << "Fizz\n"; - } else if (buzz) { - std::cout << "Buzz\n"; - } else { - std::cout << i << '\n'; - } - } - - return 0; -} - -``` - -{% endraw %} - -Fizz Buzz in [C++](/languages/c-plus-plus) was written by: - -- Ford Smith -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/c-sharp/index.md b/docs/projects/fizz-buzz/c-sharp/index.md deleted file mode 100644 index 5abcc024e8..0000000000 --- a/docs/projects/fizz-buzz/c-sharp/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2018-08-14 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- fizz-buzz -title: Fizz Buzz in C# -title1: Fizz Buzz -title2: in C# ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -for (int i = 1; i <= 100; i++) -{ - string s = ""; - - if (i % 3 == 0) s += "Fizz"; - if (i % 5 == 0) s += "Buzz"; - - Console.WriteLine(s.Length > 0 ? s : i); -} -``` - -{% endraw %} - -Fizz Buzz in [C#](/languages/c-sharp) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/c-star/index.md b/docs/projects/fizz-buzz/c-star/index.md deleted file mode 100644 index bff76621a1..0000000000 --- a/docs/projects/fizz-buzz/c-star/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- samkosal -date: 2025-10-28 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-28 -layout: default -tags: -- c-star -- fizz-buzz -title: Fizz Buzz in C* -title1: Fizz Buzz -title2: in C* ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [C\*](/languages/c-star) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c\* -void main() -{ - for (int i = 1; i <= 100; i++) { - if (i % 15 == 0) - println("FizzBuzz"); - else if (i % 3 == 0) - println("Fizz"); - else if (i % 5 == 0) - println("Buzz"); - else - println(i); - } -} - -``` - -{% endraw %} - -Fizz Buzz in [C\*](/languages/c-star) was written by: - -- samkosal - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/c/index.md b/docs/projects/fizz-buzz/c/index.md deleted file mode 100644 index 59a1c3f735..0000000000 --- a/docs/projects/fizz-buzz/c/index.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- shubhragupta-code -- Ștefan-Iulian Alecu -date: 2018-08-16 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-04-15 -layout: default -tags: -- c -- fizz-buzz -title: Fizz Buzz in C -title1: Fizz Buzz -title2: in C ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include - -int main(void) -{ - for (unsigned int i = 1; i <= 100; i++) - if (i % 15 == 0) - puts("FizzBuzz"); - else if (i % 3 == 0) - puts("Fizz"); - else if (i % 5 == 0) - puts("Buzz"); - else - printf("%u\n", i); - return 0; -} - -``` - -{% endraw %} - -Fizz Buzz in [C](/languages/c) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Apr 15 2026 00:50:56. The solution was first committed on Aug 16 2018 16:34:06. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -> Write a program that prints the numbers 1 to 100. However, for multiples of three, -> print "Fizz" instead of the number. Meanwhile, for multiples of five, print "Buzz" -> instead of the number. For numbers which are multiples of both three and five, -> print "FizzBuzz" - -Now, let us take a look at the code for FizzBuzz in C. - -Let's understand this code block by block. - -### Main Function - -```c -#include -``` - -Here, we are including Standard Input/Output header file (`.h` files) using [include directive][1] in order to use **printf()** and **puts()** function later in the program. - -```c -int main(void) -{ -``` - -In C, we declare a function using general form: - -``` -return_type function_name(parameter){ - ... -} -``` - -So, here we are declaring **main** function with return type integer and void as a parameter, i.e., no input from the user. - -### For Loop - -```c -for (unsigned int i = 1; i <= 100; i++) { - ... -} -``` - -In this block, we first created a **for** loop initializing *i* as an unsigned integer(non-negative integers) as 1 and increasing it by 1 every time the *for loop* iterates. This **for** loop will iterate until the value of *i* is equal to 100. - -Before moving onto *if-elseif* statements, we should consider **puts()** and **printf()** functions. **puts()** writes null-terminated string into stdout(standard output - a file descriptor where a process can write output) and adding a newline at the end. **printf()** prints formatted string. In this program, we are using **%u** as a format specifier for unsigned integers. - -### Control flow - -```c -if (i % 15 == 0) { - puts("FizzBuzz"); -} else if (i % 3 == 0) { - puts("Fizz"); -} else if (i % 5 == 0) { - puts("Buzz"); -} else { - printf("%u\n", i); -} -``` - -Now, variable *i* which we initialized in for loop, will check for following conditions: -- If *i* is divisible by 15, **FizzBuzz** is printed. Otherwise, -- if *i* is divisible by 3, **Fizz** is printed.Otherwise, -- If *i* is divisible by 5, **Buzz** is printed. Otherwise, -- That number, i.e., *i* gets printed. - -Finally, `return 0;` returns 0 to main program, which indicates zero errors. - -[1]: https://en.wikipedia.org/wiki/Include_directive - - -## How to Run the Solution - -```console -gcc -o fizz-buzz fizz-buzz.c -./fizz-buzz -``` -Another handy option is to compile and run using online C Compiler such as [OnlineGDB][2], [Repl][3] - -[2]: https://www.onlinegdb.com/ -[3]: https://replit.com/languages/c diff --git a/docs/projects/fizz-buzz/chapel/index.md b/docs/projects/fizz-buzz/chapel/index.md deleted file mode 100644 index fa567c2a20..0000000000 --- a/docs/projects/fizz-buzz/chapel/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- chapel -- fizz-buzz -title: Fizz Buzz in Chapel -title1: Fizz Buzz -title2: in Chapel ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Chapel](/languages/chapel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```chapel -for i in 1..100 do - if (i % 15 == 0) { - writeln("FizzBuzz"); - } else if (i % 5 == 0) { - writeln("Buzz"); - } else if (i % 3 == 0) { - writeln("Fizz"); - } else { - writeln(i); - } - -``` - -{% endraw %} - -Fizz Buzz in [Chapel](/languages/chapel) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/clojure/index.md b/docs/projects/fizz-buzz/clojure/index.md deleted file mode 100644 index 90934f254f..0000000000 --- a/docs/projects/fizz-buzz/clojure/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Cristiano Lopes -date: 2020-10-04 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2020-10-04 -layout: default -tags: -- clojure -- fizz-buzz -title: Fizz Buzz in Clojure -title1: Fizz Buzz -title2: in Clojure ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Clojure](/languages/clojure) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```clojure -(ns fizzbuzz - (:gen-class) - (:require [clojure.string :refer [join]])) - -(defn- is-multiple-of-3 [n] - (= (mod n 3) 0)) - -(defn- is-multiple-of-5 [n] - (= (mod n 5) 0)) - -(defn- n-to-str [n] - (def fizz-str (if (is-multiple-of-3 n) "Fizz" "")) - (def buzz-str (if (is-multiple-of-5 n) "Buzz" "")) - (def fizz-buzz-str (str fizz-str buzz-str)) - (def n-str (if (= fizz-buzz-str "") (str n) "")) - (str fizz-buzz-str n-str)) - -(defn- fizzbuzz [n] - (join "\n" (map n-to-str (range 1 (+ n 1))))) - -(println (fizzbuzz 100)) - -``` - -{% endraw %} - -Fizz Buzz in [Clojure](/languages/clojure) was written by: - -- Cristiano Lopes - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/cobol/index.md b/docs/projects/fizz-buzz/cobol/index.md deleted file mode 100644 index b6c5a540bb..0000000000 --- a/docs/projects/fizz-buzz/cobol/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-04-19 -layout: default -tags: -- cobol -- fizz-buzz -title: Fizz Buzz in COBOL -title1: Fizz Buzz -title2: in COBOL ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. fizz-buzz. - -data division. -working-storage section. - -01 counter pic 9(3). -01 counter-out pic z(3). - -procedure division. - -main. - perform varying counter from 1 by 1 until counter > 100 - - evaluate true - when function mod(counter, 15) = 0 - display "FizzBuzz" - - when function mod(counter, 3) = 0 - display "Fizz" - - when function mod(counter, 5) = 0 - display "Buzz" - - when other - move counter to counter-out - display function trim(counter-out) - end-evaluate - - end-perform - - stop run. - -``` - -{% endraw %} - -Fizz Buzz in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/coffeescript/index.md b/docs/projects/fizz-buzz/coffeescript/index.md deleted file mode 100644 index cf6fefccf6..0000000000 --- a/docs/projects/fizz-buzz/coffeescript/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- darkpanda08 -date: 2020-10-01 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2020-10-01 -layout: default -tags: -- coffeescript -- fizz-buzz -title: Fizz Buzz in CoffeeScript -title1: Fizz Buzz in -title2: CoffeeScript ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -for i in [1..100] - if i % 15 is 0 - console.log "FizzBuzz" - else if i % 3 is 0 - console.log "Fizz" - else if i % 5 is 0 - console.log "Buzz" - else - console.log i -``` - -{% endraw %} - -Fizz Buzz in [CoffeeScript](/languages/coffeescript) was written by: - -- darkpanda08 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/commodore-basic/index.md b/docs/projects/fizz-buzz/commodore-basic/index.md deleted file mode 100644 index 59f015e084..0000000000 --- a/docs/projects/fizz-buzz/commodore-basic/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-13 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-09-13 -layout: default -tags: -- commodore-basic -- fizz-buzz -title: Fizz Buzz in Commodore BASIC -title1: Fizz Buzz in -title2: Commodore BASIC ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 FOR I = 1 TO 100 -20 S$ = "" -30 IF (I - INT(I / 3) * 3) = 0 THEN S$ = S$ + "Fizz" -40 IF (I - INT(I / 5) * 5) = 0 THEN S$ = S$ + "Buzz" -45 REM STR$(I) prepends a space for positive numbers. MID$ removes it -50 IF S$ = "" THEN S$ = S$ + MID$(STR$(I), 2) -60 PRINT S$ -70 NEXT I - -``` - -{% endraw %} - -Fizz Buzz in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/crystal/index.md b/docs/projects/fizz-buzz/crystal/index.md deleted file mode 100644 index 7dd73aea7b..0000000000 --- a/docs/projects/fizz-buzz/crystal/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Noah Nichols -date: 2018-09-26 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2018-09-26 -layout: default -tags: -- crystal -- fizz-buzz -title: Fizz Buzz in Crystal -title1: Fizz Buzz -title2: in Crystal ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Crystal](/languages/crystal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```crystal -i = 1 -while i < 101 - if i % 3 == 0 && i % 5 == 0 - puts "FizzBuzz" - elsif i % 3 == 0 - puts "Fizz" - elsif i % 5 == 0 - puts "Buzz" - else - puts i - end - i = i + 1 -end -``` - -{% endraw %} - -Fizz Buzz in [Crystal](/languages/crystal) was written by: - -- Noah Nichols - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/cython/index.md b/docs/projects/fizz-buzz/cython/index.md deleted file mode 100644 index 0bed463288..0000000000 --- a/docs/projects/fizz-buzz/cython/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-31 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-31 -layout: default -tags: -- cython -- fizz-buzz -title: Fizz Buzz in Cython -title1: Fizz Buzz -title2: in Cython ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Cython](/languages/cython) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cython -from libc.stdio cimport printf - - -cdef main(): - cdef int n - cdef bytes buffer - for n in range(1, 101): - buffer = b"" - buffer += b"Fizz" if n % 3 == 0 else b"" - buffer += b"Buzz" if n % 5 == 0 else b"" - buffer += bytes(str(n).encode("ascii")) if not buffer else b"" - printf("%s\n", buffer) - -if __name__ == "__main__": - main() - -``` - -{% endraw %} - -Fizz Buzz in [Cython](/languages/cython) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/d/index.md b/docs/projects/fizz-buzz/d/index.md deleted file mode 100644 index 3a28e0030b..0000000000 --- a/docs/projects/fizz-buzz/d/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- d -- fizz-buzz -title: Fizz Buzz in D -title1: Fizz Buzz -title2: in D ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [D](/languages/d) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```d -import std.stdio; - -void main() -{ - for (int i = 1; i <= 100; i++) { - if (i % 15 == 0) writeln("FizzBuzz"); - else if (i % 5 == 0) writeln("Buzz"); - else if (i % 3 == 0) writeln("Fizz"); - else writeln(i); - } -} - -``` - -{% endraw %} - -Fizz Buzz in [D](/languages/d) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/dart/index.md b/docs/projects/fizz-buzz/dart/index.md deleted file mode 100644 index d08cdcd730..0000000000 --- a/docs/projects/fizz-buzz/dart/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Sanchit Sahay -date: 2020-10-02 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2020-10-02 -layout: default -tags: -- dart -- fizz-buzz -title: Fizz Buzz in Dart -title1: Fizz Buzz -title2: in Dart ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -void fizzBuzz(int maxNumber){ - for(int i=1;i<=maxNumber;i++){ - String output = ""; - if(i%3 == 0){ - output += "Fizz"; - } - if(i%5 == 0){ - output += "Buzz"; - } - if(output == ""){ - output = "$i"; - } - print(output); - } -} - -void main() { - fizzBuzz(100); -} - -``` - -{% endraw %} - -Fizz Buzz in [Dart](/languages/dart) was written by: - -- Sanchit Sahay - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/dg/index.md b/docs/projects/fizz-buzz/dg/index.md deleted file mode 100644 index 6a3be43b1b..0000000000 --- a/docs/projects/fizz-buzz/dg/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Riley Martine -date: 2018-10-03 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2018-10-03 -layout: default -tags: -- dg -- fizz-buzz -title: Fizz Buzz in Dg -title1: Fizz Buzz -title2: in Dg ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Dg](/languages/dg) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dg -fizz_buzz = n -> if - n % 15 == 0 => "FizzBuzz" - n % 3 == 0 => "Fizz" - n % 5 == 0 => "Buzz" - otherwise => n - -main = start end ruleset -> - for i in range start (end + 1) => - print <| ruleset i - -main 1 100 fizz_buzz - -``` - -{% endraw %} - -Fizz Buzz in [Dg](/languages/dg) was written by: - -- Riley Martine - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/eiffel/index.md b/docs/projects/fizz-buzz/eiffel/index.md deleted file mode 100644 index 13527cf1e3..0000000000 --- a/docs/projects/fizz-buzz/eiffel/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- eiffel -- fizz-buzz -title: Fizz Buzz in Eiffel -title1: Fizz Buzz -title2: in Eiffel ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Eiffel](/languages/eiffel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```eiffel -class - fizz_buzz - -create - make - -feature - make - do - across 1 |..| 100 as i - loop - if i.item \\ 15 = 0 then io.put_string("FizzBuzz") - elseif i.item \\ 5 = 0 then io.put_string("Buzz") - elseif i.item \\ 3 = 0 then io.put_string("Fizz") - else io.put_integer(i.item) - end - - io.put_new_line - end - end - end - -``` - -{% endraw %} - -Fizz Buzz in [Eiffel](/languages/eiffel) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/elixir/index.md b/docs/projects/fizz-buzz/elixir/index.md deleted file mode 100644 index 3975eb1dd4..0000000000 --- a/docs/projects/fizz-buzz/elixir/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2019-04-25 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2019-04-25 -layout: default -tags: -- elixir -- fizz-buzz -title: Fizz Buzz in Elixir -title1: Fizz Buzz -title2: in Elixir ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Elixir](/languages/elixir) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elixir -1..100 -|> Enum.map(fn - n when rem(n, 3) == 0 and rem(n, 5) == 0 -> "FizzBuzz" - n when rem(n, 3) == 0 -> "Fizz" - n when rem(n, 5) == 0 -> "Buzz" - n -> Integer.to_string(n) -end) -|> Enum.each(&IO.puts/1) - -``` - -{% endraw %} - -Fizz Buzz in [Elixir](/languages/elixir) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/elvish/index.md b/docs/projects/fizz-buzz/elvish/index.md deleted file mode 100644 index 6f99a0b092..0000000000 --- a/docs/projects/fizz-buzz/elvish/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-08 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-08 -layout: default -tags: -- elvish -- fizz-buzz -title: Fizz Buzz in Elvish -title1: Fizz Buzz -title2: in Elvish ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -for i [(range 1 101)] { - if (== (% $i 15) 0) { - echo FizzBuzz - } elif (== (% $i 5) 0) { - echo Buzz - } elif (== (% $i 3) 0) { - echo Fizz - } else { - echo $i - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/erlang/index.md b/docs/projects/fizz-buzz/erlang/index.md deleted file mode 100644 index 69b11c7c5e..0000000000 --- a/docs/projects/fizz-buzz/erlang/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Caio Ariede -- rzuckerm -date: 2019-10-04 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-11-21 -layout: default -tags: -- erlang -- fizz-buzz -title: Fizz Buzz in Erlang -title1: Fizz Buzz -title2: in Erlang ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Erlang](/languages/erlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```erlang --module(fizz_buzz). --export([main/1]). - -% Run with: escript fizz_buzz.erl - -main(_) -> - fizz_buzz(1, 100). - -fizz_buzz(N, Max) when N > Max -> []; -fizz_buzz(N, Max) when N rem 15 == 0 -> io:format("FizzBuzz~n", []), fizz_buzz(N+1, Max); -fizz_buzz(N, Max) when N rem 5 == 0 -> io:format("Buzz~n", []), fizz_buzz(N+1, Max); -fizz_buzz(N, Max) when N rem 3 == 0 -> io:format("Fizz~n", []), fizz_buzz(N+1, Max); -fizz_buzz(N, Max) -> io:format("~p~n", [N]), fizz_buzz(N+1, Max). - -``` - -{% endraw %} - -Fizz Buzz in [Erlang](/languages/erlang) was written by: - -- Caio Ariede -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/euphoria/index.md b/docs/projects/fizz-buzz/euphoria/index.md deleted file mode 100644 index 4a9f0d0169..0000000000 --- a/docs/projects/fizz-buzz/euphoria/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- fizz-buzz -title: Fizz Buzz in Euphoria -title1: Fizz Buzz -title2: in Euphoria ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/math.e -include std/utils.e - -for n = 1 to 100 -do - sequence s = "" - s &= iif(mod(n, 3) = 0, "Fizz", "") - s &= iif(mod(n, 5) = 0, "Buzz", "") - s &= iif(length(s) = 0, sprintf("%d", n), "") - printf(STDOUT, "%s\n", {s}) -end for - -``` - -{% endraw %} - -Fizz Buzz in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/f-sharp/index.md b/docs/projects/fizz-buzz/f-sharp/index.md deleted file mode 100644 index fde49b484a..0000000000 --- a/docs/projects/fizz-buzz/f-sharp/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- fizz-buzz -title: Fizz Buzz in F# -title1: Fizz Buzz -title2: in F# ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -module FizzBuzz = - let (|DivisibleBy|_|) divisor number = - if number % divisor = 0 then Some() else None - - let fizzBuzzOf number = - match number with - | DivisibleBy 3 & DivisibleBy 5 -> "FizzBuzz" - | DivisibleBy 3 -> "Fizz" - | DivisibleBy 5 -> "Buzz" - | _ -> string number - - let printUpTo n = - Seq.init n (fun i -> i + 1) |> Seq.map fizzBuzzOf |> Seq.iter (printfn "%s") - -[] -let main _ = - FizzBuzz.printUpTo 100 - 0 - -``` - -{% endraw %} - -Fizz Buzz in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/fennel/index.md b/docs/projects/fizz-buzz/fennel/index.md deleted file mode 100644 index 18b55af1fa..0000000000 --- a/docs/projects/fizz-buzz/fennel/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fennel -- fizz-buzz -title: Fizz Buzz in Fennel -title1: Fizz Buzz -title2: in Fennel ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Fennel](/languages/fennel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fennel -(for [i 1 100] - (if (= 0 (% i 15)) - (print "FizzBuzz") - (if (= 0 (% i 5)) - (print "Buzz") - (if (= 0 (% i 3)) - (print "Fizz") - (print i))))) - -``` - -{% endraw %} - -Fizz Buzz in [Fennel](/languages/fennel) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/fetlang/index.md b/docs/projects/fizz-buzz/fetlang/index.md deleted file mode 100644 index d7c32b5cca..0000000000 --- a/docs/projects/fizz-buzz/fetlang/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-13 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-13 -layout: default -tags: -- fetlang -- fizz-buzz -title: Fizz Buzz in Fetlang -title1: Fizz Buzz -title2: in Fetlang ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Fetlang](/languages/fetlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fetlang -lick Nora (0 + 1) -lick Hunter one hundred and one times (0 + 101) -lick Power10 -lick NextPower10 ten times - -(Set up single-digit numbers) -worship Number0 (0 * 1) -lick Number1 -lick Number2 two times -lick Number3 three times -lick Number4 four times -lick Number5 five times -lick Number6 six times -lick Number7 seven times -lick Number8 eight times -lick Number9 nine times - -(while Nora < 101) -while Nora is submissive to Hunter - (OutputCounter = 0) - have OutputCounter spank itself - - (if Nora % 3 == 0, output "Fizz" and increment OutputCounter) - have Remy spank himself (Remy = 0) - have Nora lick Remy (Remy = Nora) - tickle Remy three times (Remy = Nora % 3) - if Remy is Number0 - make slave moan "Fizz" - lick OutputCounter - - (if Nora % 5 == 0, output "Buzz" and increment OutputCounter) - have Remy spank himself (Remy = 0) - have Nora lick Remy (Remy = Nora) - tickle Remy five times (Remy = Nora % 5) - if Remy is Number0 - make slave moan "Buzz" - lick OutputCounter - - (if OutputCounter == 0, output Nora as a number) - if OutputCounter is Number0 - (Fetlang outputs numbers as words, so need to output each digit as an ASCII digit) - - (CurrentPower10 = Power10) - have CurrentPower10 spank itself - have Power10 lick CurrentPower10 - - (while CurrentPower10 > 0) - while CurrentPower10 is dominant towards Number0 - (Didi = Nora) - have Didi spank herself - have Nora lick Didi - - (Mona = Nora % CurrentPower10) - have Mona spank herself - have Nora lick Mona - have CurrentPower10 tickle Mona - - (Didi = (Didi - Mona) / CurrentPower10 = floor(Nora / CurrentPower10)) - have Mona spank Didi - have CurrentPower10 flog Didi - - (Output Didi % 10 as ASCII) - tickle Didi ten times (Didi % 10) - if Didi is Number0 - make slave moan "0" - - if Didi is Number1 - make slave moan "1" - - if Didi is Number2 - make slave moan "2" - - if Didi is Number3 - make slave moan "3" - - if Didi is Number4 - make slave moan "4" - - if Didi is Number5 - make slave moan "5" - - if Didi is Number6 - make slave moan "6" - - if Didi is Number7 - make slave moan "7" - - if Didi is Number8 - make slave moan "8" - - if Didi is Number9 - make slave moan "9" - - (CurrentPower10 = floor(CurrentPower10 / 10)) - if CurrentPower10 is not Number1 - flog CurrentPower10 ten times - otherwise - have CurrentPower10 spank itself - - (Output newline) - make slave scream - - (Increment Nora) - lick Nora - - (If Nora == NextPower10,) - if Nora is NextPower10 - (Power10 = Power10 * 10) - worship Power10 ten times - - (NextPower10 = NextPower10 * 10) - worship NextPower10 ten times - -``` - -{% endraw %} - -Fizz Buzz in [Fetlang](/languages/fetlang) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/forth/index.md b/docs/projects/fizz-buzz/forth/index.md deleted file mode 100644 index 317c48ebca..0000000000 --- a/docs/projects/fizz-buzz/forth/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- forth -title: Fizz Buzz in Forth -title1: Fizz Buzz -title2: in Forth ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Forth](/languages/forth) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```forth -: divisible - mod 0= -; - -: fizz-buzz - dup 15 divisible if - drop - ." FizzBuzz" - else - dup 5 divisible if - drop - ." Buzz" - else - dup 3 divisible if - drop - ." Fizz" - else - . - endif - endif - endif -; - -: fizz-buzz-loop - 101 1 do i fizz-buzz cr loop -; - -fizz-buzz-loop -bye - -``` - -{% endraw %} - -Fizz Buzz in [Forth](/languages/forth) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/fortran/index.md b/docs/projects/fizz-buzz/fortran/index.md deleted file mode 100644 index f696eb88b9..0000000000 --- a/docs/projects/fizz-buzz/fortran/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- sniklas142 -- Ștefan-Iulian Alecu -date: 2020-10-01 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-15 -layout: default -tags: -- fizz-buzz -- fortran -title: Fizz Buzz in Fortran -title1: Fizz Buzz -title2: in Fortran ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program fizzbuzz - implicit none - integer, parameter :: n = 100 - integer :: i - - do i = 1, n - write(*,'(A)') fizzbuzz_string(i) - end do - -contains - - pure function fizzbuzz_string(x) result(str) - integer, intent(in) :: x - character(len=8) :: str - - str = '' - - if (mod(x,3) == 0) str = 'Fizz' - if (mod(x,5) == 0) str = trim(str)//'Buzz' - if (len_trim(str) == 0) write(str,'(I0)') x - end function fizzbuzz_string - -end program fizzbuzz - -``` - -{% endraw %} - -Fizz Buzz in [Fortran](/languages/fortran) was written by: - -- sniklas142 -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/gnu-make/index.md b/docs/projects/fizz-buzz/gnu-make/index.md deleted file mode 100644 index 26e75aa1d5..0000000000 --- a/docs/projects/fizz-buzz/gnu-make/index.md +++ /dev/null @@ -1,530 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-07-17 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-08-12 -layout: default -tags: -- fizz-buzz -- gnu-make -title: Fizz Buzz in GNU Make -title1: Fizz Buzz -title2: in GNU Make ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -# Numbers are represented as x's so that they can be manipulated with text functions. -# This idea is based on how the GNU Make Standard Library (https://github.com/jgrahamc/gmsl) -# handles numbers. -ZERO := -ONE := x -TWO := x x -THREE := x x x -FIVE := $(THREE) $(TWO) -TEN := $(FIVE) $(FIVE) -FIFTEEN := $(TEN) $(FIVE) -HUNDRED := $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) - -# Is divisible function -# Arg 1: Number encoded as x's -# Arg 2: Divisor encoded as x's -# Return: $(ONE) if divisible, $(ZERO) otherwise -IS_DIVISIBLE = $(if $(strip $(subst $(2),,$(1))),$(ZERO),$(ONE)) - -# Is less than function -# Arg 1: Number 1 encoded as x's -# Arg 2: Number 2 encoded as x's -# Return: $(ONE) if Number 1 < Number 2, $(ZERO) otherwise -IS_LESS_THAN = $(if $(wordlist $(words $(call INC,$(1))),$(words $(2)),$(2)),$(ONE),$(ZERO)) - -# Increment function -# Arg 1: Number encoded as x's -# Return: Number + 1 encoded as x's -INC = $(strip $(1) $(ONE)) - -# Fizz Buzz function -# Arg 1: Number encoded as x's -# Return: One of the following: -# - FizzBuzz if Number is divisible by 15 -# - Fizz if Number is divisible by 3 -# - Buzz if Number if divisible 5 -# - Otherwise, Number converted to decimal representation -FIZZ_BUZZ = $(strip \ - $(if $(call IS_DIVISIBLE,$(1),$(FIFTEEN)),FizzBuzz,\ - $(if $(call IS_DIVISIBLE,$(1),$(THREE)),Fizz,\ - $(if $(call IS_DIVISIBLE,$(1),$(FIVE)),Buzz,$(words $(1)))\ - ) \ - ) \ -) - -# Fizz Buzz loop -# -# Outputs result of Fizz Buzz function starting at starting number and ending -# at the ending number -# -# Arg 1: Starting number encoded as x's -# Arg 2: Ending number encoded as x's -define FIZZ_BUZZ_LOOP -$(info $(call FIZZ_BUZZ,$(1))) -$(if $(call IS_LESS_THAN,$(1),$(2)),$(call FIZZ_BUZZ_LOOP,$(call INC,$(1)),$(2))) -endef - -# Run Fizz Buzz loop from 1 to 100 -$(call FIZZ_BUZZ_LOOP,$(ONE),$(HUNDRED)) - -.PHONY: all -all: ;@: - -``` - -{% endraw %} - -Fizz Buzz in [GNU Make](/languages/gnu-make) was written by: - -- rzuckerm - -This article was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -### Introduction - -GNU Make has very few functions that accept or return numbers, so doing -anything that requires math is challenging. After doing some Google searches, -I discovered the [GNU Make Standard Library][1]. This library does some -amazing things with the functions available in GNU Make. I studied the code, -and the way they handle numbers is to convert them with a sequence of `x`'s -separated by spaces. In other words, the number `n` is represented as -`n` `x`'s separated by spaces. For `0`, an empty string is used. For example, -`5` would be represented like this: - -``` -x x x x x -``` - -Before we start digging into the code, let's explain some concepts and -built-in functions that will be used in this code sample. - -### Immediate vs. Deferred Assignment - -Throughout the code, there are [two types of assignment][2]: - -* `:=` means immediate assignment. -* `=` means deferred assignment. - -As the name implies, immediate assignment means the value of the variable -is assigned immediately, and any variables referenced are immediately -expanded. For example: - -```make -HELLO := hello -WORLD := world -HELLO_WORLD := $(HELLO) $(WORLD) -``` - -For the above, the value of `HELLO` is the string `hello`, the value of -`WORLD` is the string `world`. The variable `HELLO_WORLD` is the value -of `HELLO`, a space, and then the value of `WORLD` -- i.e., the string -`hello world`. - -### User-Defined Functions - -A user-defined function is set up as a variable with a deferred assignment. -Function arguments are represented as the one-based argument number enclosed -in `$()` -- e.g., `$(2)` is the second argument. The [call][3] function is -used to invoked these functions. For example. let's set up this function: - -```make -GREET = $(1), $(2). How are you? -``` - -This function takes two argument: a greeting and a name. It returns a value -that is equal to the first argument, a comma, a space, the second argument, -and `. How are you?`. - -We would call this function like this: - -```make -GREETING := $(call GREET,Hello,Joe Smith) -``` - -The first argument is `Hello`, and the second argument is `Joe Smith`. This -would set the variable `GREETING` to the value of -`Hello, Joe Smith. How are you?`. - -### Built-In Numeric Functions - -There are a few functions in GNU Make that handle numbers. Of those, only -the following are used: - -* [wordlist][5] -* [words][6] - -### wordlist Function - -First, let's take a look at the [wordlist][5] function. This function takes -three arguments: - -1. The one-based starting index. Let's call this `s`. -2. The one-based ending index. Let's call this `e`. -3. A space-separated list. - -It returns a space-separated list that contains elements `s` through `e` -(inclusive) of the original list. These values are constrained to the length -of the list. For the case where `s` is greater than `e`, an empty string is -returned. - -For example, let's create a variable called `SOME_LIST` with 5 elements: - -```make -SOME_LIST := first second third fourth fifth -``` - -If you did this: - -```make -ANSWER1 := $(wordlist 2,4,$(SOME_LIST)) -``` - -Then, `ANSWER1` would equal `two three four`, which is the 2nd through 4th -element. - -If you did this: - -```make -ANSWER2 := $(wordlist 4,1000,$(SOME_LIST)) -``` - -Then, `ANSWER2` would equal `four five`, which is the 4th and 5th element -since the value returned by `wordlist` stops at the last element. - -If you did any of these: - -```make -ANSWER3A := $(wordlist 6,7,$(SOME_LIST)) -ANSWER3B := $(wordlist 5,4,$(SOME_LIST)) -``` - -Then, you would get an empty string because: - -* For `ANSWER3A`, there is no 6th element. -* For `ANSWER3B`, `5` is greater than `4`. - -#### words Function - -The [words][6] function accepts a single argument: a space-separated list. The -function returns the number of elements in that list. For example: - -* `$(words a b c)` returns `3` -* `$(words)` returns `0` - -### Built-In Conditional Function - -The [if][7] function is a conditional function that returns one of two -values: one for the "true" case, one for the "false" case. It take three -arguments: - -1. The value to compare -2. The value to return if "true" -3. The value to return if "false" - -A value is considered "true" if it is non-empty. For example: - -```make -$(if $(SOME_VALUE),It's True,It's False) -``` - -If that value of the variable `SOME_VALUE` is non-empty, then `It's True` is -returned. Otherwise, `It's False` is returned. - -### Numbers - -This code sets up the numbers that are used in the Fizz Buzz algorithm: - -```make -ZERO := -ONE := x -TWO := x x -THREE := x x x -FIVE := $(THREE) $(TWO) -TEN := $(FIVE) $(FIVE) -FIFTEEN := $(TEN) $(FIVE) -HUNDRED := $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) $(TEN) -``` - -From the names, it's obvious as to which number each variable represents -- -e.g., `FIVE` (which is effectively `THREE` plus `TWO`) is 5 `x`'s separated by -spaces. - -### Math Functions - -A number of math functions are needed in order to support the Fizz Buzz -algorithm: - -* Increment (`INC`) -* Is less than (`IS_LESS_THAN`) -* Is divisible by (`IS_DIVISIBLE_BY`) - -#### INC Function - -Let's look at the `INC` function first since it is the simplest, and it is -used elsewhere. It takes a single argument which is a number represented as -`x`'s and returns the number plus one represented as `x`'s. Here the function: - -```make -INC = $(strip $(1) $(ONE)) -``` - -Incrementing just involves append a space and a single `x` (the value of -`ONE`) to the passed in argument. The [strip][4] function removes leading -and trailing whitespace. This is needed for the case whether the argument has -the value of zero, which is an empty string. Without this, ` x` would be -returned instead of just `x`. - -#### IS_LESS_THAN Function - -The `IS_LESS_THAN` function takes a two arguments which are numbers -represented as `x`'s and returns a `$(ONE)` (which is `x`) as a true value, -and `$(ZERO)` (which is empty) as a false value. Here is the function: - -```make -IS_LESS_THAN = $(if $(wordlist $(words $(call INC,$(1))),$(words $(2)),$(2)),$(ONE),$(ZERO)) -``` - -Whoa! That's a lot to digest here! Let's break it down. Effectively, the way -this works if to remove each item in the first argument from the second until -the first or second argument is exhausted, whichever comes first. When the -first argument is less than the second, a non-empty list will remain, and -`$(ONE)` is returned. Otherwise, it will be an empty list, and `$(ZERO)` is -returned. - -Let's work through a couple of examples. Let `ARG1` be `3` and `ARG2` be `5`, -each represented as `x`'s: - -```make -ARG1 := x x x -ARG2 := x x x x x -RESULT := $(call IS_LESS_THAN,$(ARG1),$(ARG2)) -``` - -For this case `$(words $(call INC,$(ARG1)))` is `4` (`3 + 1`), and -`$(words $(ARG2))` is `5`, so `$(wordlist 4,5,$(ARG2))` can be visualized as -the right-hand side of this: - -``` -1 2 3 | 4 5 -x x x | x x -``` - -Since the result is non-empty, `$(ONE)` is returned. - -Let's work through the reverse of the previous example: - -```make -ARG1 := x x x x x -ARG2 := x x x -RESULT := $(call IS_LESS_THAN,$(ARG1),$(ARG2)) -``` - -For this case `$(words $(call INC,$(ARG1)))` is `6`, and `$(words $(ARG2))` is -`3`, so `$(wordlist 6,3,$(ARG2))` can be visualized as the right-hand side of -this: - -``` -1 2 3 | 4 5 6 -x x x | -``` - -Since the result is empty, `$(ZERO)` is returned. - -#### IS_DIVISIBLE_BY Function - -The `IS_DIVISIBLE_BY` function take two arguments: - -* Dividend represented as `x`'s -* Divisor represented as `x`'s - -If the dividend is divisible by the divisor, `$(ONE)` is returned. Otherwise, -`$(ZERO)` is returned. Here is the function: - -```make -IS_DIVISIBLE_BY = $(if $(strip $(subst $(2),,$(1))),$(ZERO),$(ONE)) -``` - -While this isn't as scary as the `IS_LESS_THAN` function, there is an -interesting trick at work here. The [subst][8] take three arguments: - -1. The search string -2. The replace string -3. The string to modify - -This is used to remove all instances of the divisor from the dividend. If the -result is non-empty, then the dividend is not divisible by the divisor. -Otherwise, it is divisible. - -Let's work through a couple of examples. Let `ARG1` be `8` and `ARG2` be `3`, -each represented as `x`'s: - -``` -ARG1 := x x x x x x x x -ARG2 := x x x -RESULT := $(call IS_DIVISIBLE_BY,$(ARG1),$(ARG2)) -``` - -The `subst` function would look like this: - -```make -$(subst x x x,,x x x x x x x x) -``` - -In other words, substitute 3 `x`'s with nothing. The return value of `subst` -would be the right-most side of this: - -``` -1 2 3 | 4 5 6 | 7 8 -x x x | x x x | x x -``` - -Since this is non-empty (`x x`), the return value of `IS_DIVISIBLE_BY` is -`$(ZERO)`. - -Let's change `ARG1` to `9` represented as `x`'s: - -```make -ARG1 := x x x x x x x x x -ARG2 := x x x -RESULT := $(call IS_DIVISIBLE_BY,$(ARG1),$(ARG2)) -``` - -For this case, the right-most side of `subst` would be this: - -``` -1 2 3 | 4 5 6 | 7 8 9 | -x x x | x x x | x x x | -``` - -Since this is empty, the return value of `IS_DIVISIBLE_BY` is `$(ONE)`. - -### The Fizz Buzz Algorithm - -Finally, we're at the meat of the matter! Thanks for sticking with me so far. - -#### FIZZ_BUZZ Function - -The `FIZZ_BUZZ` function takes a single argument that is a number represented -as `x`'s. Let's call this argument `n`. This function returns on of the following: - -* If `n` is divisible by 3 and 5 (i.e., 15), return `FizzBuzz`. -* Else if `n` is divisible by 3, return `Fizz`. -* Else if `n` is divisible by 5, return `Buzz`. -* Else return `n` represented as a regular number. - -Here is the implementation: - -```make -FIZZ_BUZZ = $(strip \ - $(if $(call IS_DIVISIBLE,$(1),$(FIFTEEN)),FizzBuzz,\ - $(if $(call IS_DIVISIBLE,$(1),$(THREE)),Fizz,\ - $(if $(call IS_DIVISIBLE,$(1),$(FIVE)),Buzz,$(words $(1)))\ - ) \ - ) \ -) -``` - -The `strip` function is needed to remove any extraneous spaces that are added -by the formatting of the code, which is done for readability. The `words` -function is needed to convert the argument into a regular number. - -#### FIZZ_BUZZ_LOOP Function - -The `FIZZ_BUZZ_LOOP` function has two arguments: the starting and end numbers -represented as `x`'s. Here is the function: - -```make -define FIZZ_BUZZ_LOOP -$(info $(call FIZZ_BUZZ,$(1))) -$(if $(call IS_LESS_THAN,$(1),$(2)),$(call FIZZ_BUZZ_LOOP,$(call INC,$(1)),$(2))) -endef -``` - -The [define][10] keyword assigns a multi-line value to a variable. The value -is terminated with an `endef` keyword. The [info][9] function takes a single -value: the value to be displayed. - -Here is what this function would look like in pseudocode: - -``` -function FIZZ_BUZZ_LOOP(start, end) - display FIZZ_BUZZ(start) - if start < end: - call FIZZ_BUZZ_LOOP(start + 1, end) -``` - -You'll notice that this is using recursion. That is the only way to implement -loops in GNU Make. - -#### The Final Step - -In order to make all this run the Fizz Buzz algorithm and display results, one -final piece is needed, and that is to call `FIZZ_BUZZ_LOOP` with a starting -value of 1 (`$(ONE)`) and ending value of 100 (`$(HUNDRED)`): - -```make -$(call FIZZ_BUZZ_LOOP,$(ONE),$(HUNDRED)) -``` - -And that's it! Wow, that was exhausting! I think I'll take a nap now. - -[1]: https://github.com/jgrahamc/gmsl -[2]: https://www.gnu.org/software/make/manual/html_node/Reading-Makefiles.html -[3]: https://www.gnu.org/software/make/manual/html_node/Call-Function.html -[4]: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-stripping-whitespace -[5]: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-wordlist -[6]: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-words -[7]: https://www.gnu.org/software/make/manual/html_node/Conditional-Functions.html#index-if-1 -[8]: https://www.gnu.org/software/make/manual/html_node/Text-Functions.html#index-subst-1 -[9]: https://www.gnu.org/software/make/manual/html_node/Make-Control-Functions.html#index-info -[10]: https://www.gnu.org/software/make/manual/html_node/Multi_002dLine.html - - -## How to Run the Solution - -To run this program, download and install the latest GNU Make using these -instructions: - -* [Windows][11] -* For [Linux][12], see "How to Download" section -* [Mac][13] - -Download a copy of [Fizz Buzz in GNU Make][14], and run this command: - -``` -make -sf fizz-buzz.mk -``` - -[11]: https://leangaurav.medium.com/how-to-setup-install-gnu-make-on-windows-324480f1da69 -[12]: https://www.incredibuild.com/integrations/gnu-make -[13]: https://formulae.brew.sh/formula/make -[14]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/g/gnu-make/fizz-buzz.mk diff --git a/docs/projects/fizz-buzz/go/index.md b/docs/projects/fizz-buzz/go/index.md deleted file mode 100644 index c0c0c623d6..0000000000 --- a/docs/projects/fizz-buzz/go/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -date: 2018-08-13 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2019-04-01 -layout: default -tags: -- fizz-buzz -- go -title: Fizz Buzz in Go -title1: Fizz Buzz -title2: in Go ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import "fmt" - -func main() { - for i := 1; i <= 100; i++ { - if i%15 == 0 { - fmt.Println("FizzBuzz") - } else if i%3 == 0 { - fmt.Println("Fizz") - } else if i%5 == 0 { - fmt.Println("Buzz") - } else { - fmt.Println(i) - } - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Go](/languages/go) was written by: - -- Jeremy Grifski -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/goby/index.md b/docs/projects/fizz-buzz/goby/index.md deleted file mode 100644 index 6a1b8ec37c..0000000000 --- a/docs/projects/fizz-buzz/goby/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- f00d -date: 2025-10-30 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-30 -layout: default -tags: -- fizz-buzz -- goby -title: Fizz Buzz in Goby -title1: Fizz Buzz -title2: in Goby ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Goby](/languages/goby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```goby -i = 1 -while i do - if i > 100 - break - end - result = "" - if i % 3 == 0 - result += "Fizz" - end - if i % 5 == 0 - result += "Buzz" - end - if result == "" - result = i.to_s + "" - end - puts(result) - i += 1 -end - -``` - -{% endraw %} - -Fizz Buzz in [Goby](/languages/goby) was written by: - -- f00d - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/gosu/index.md b/docs/projects/fizz-buzz/gosu/index.md deleted file mode 100644 index b5bf597b32..0000000000 --- a/docs/projects/fizz-buzz/gosu/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- KevinSandoval12 -date: 2025-10-30 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-30 -layout: default -tags: -- fizz-buzz -- gosu -title: Fizz Buzz in Gosu -title1: Fizz Buzz -title2: in Gosu ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Gosu](/languages/gosu) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gosu -for (n in 1..100) { - if (n % 15 == 0) { - print("FizzBuzz"); - } - else if (n % 3 == 0) { - print("Fizz"); - } - else if (n % 5 == 0) { - print("Buzz"); - } - else { - print(n); - } -} -``` - -{% endraw %} - -Fizz Buzz in [Gosu](/languages/gosu) was written by: - -- KevinSandoval12 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/gravity/index.md b/docs/projects/fizz-buzz/gravity/index.md deleted file mode 100644 index 3088718798..0000000000 --- a/docs/projects/fizz-buzz/gravity/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- gravity -title: Fizz Buzz in Gravity -title1: Fizz Buzz -title2: in Gravity ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Gravity](/languages/gravity) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gravity -func main() { - for (var i in 1...100) { - if (i % 15 == 0) { - System.print("FizzBuzz") - } else if (i % 5 == 0) { - System.print("Buzz") - } else if (i % 3 == 0) { - System.print("Fizz") - } else { - System.print(i) - } - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Gravity](/languages/gravity) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/groovy/index.md b/docs/projects/fizz-buzz/groovy/index.md deleted file mode 100644 index 137cf89403..0000000000 --- a/docs/projects/fizz-buzz/groovy/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- groovy -title: Fizz Buzz in Groovy -title1: Fizz Buzz -title2: in Groovy ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -1.upto(100) { - if (it % 15 == 0) { - println("FizzBuzz") - } else if (it % 5 == 0) { - println("Buzz") - } else if (it % 3 == 0){ - println("Fizz") - } else { - println(it) - } -}; - -``` - -{% endraw %} - -Fizz Buzz in [Groovy](/languages/groovy) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/haskell/index.md b/docs/projects/fizz-buzz/haskell/index.md deleted file mode 100644 index fe86244d4e..0000000000 --- a/docs/projects/fizz-buzz/haskell/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-08-13 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2018-08-13 -layout: default -tags: -- fizz-buzz -- haskell -title: Fizz Buzz in Haskell -title1: Fizz Buzz -title2: in Haskell ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -fizzbuzz :: Int -> String -fizzbuzz x - | x `mod` 15 == 0 = "FizzBuzz" - | x `mod` 3 == 0 = "Fizz" - | x `mod` 5 == 0 = "Buzz" - | otherwise = show x - -main = mapM (putStrLn . fizzbuzz) [1..100] - -``` - -{% endraw %} - -Fizz Buzz in [Haskell](/languages/haskell) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/haxe/index.md b/docs/projects/fizz-buzz/haxe/index.md deleted file mode 100644 index 5fe7bc94dd..0000000000 --- a/docs/projects/fizz-buzz/haxe/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-18 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-18 -layout: default -tags: -- fizz-buzz -- haxe -title: Fizz Buzz in Haxe -title1: Fizz Buzz -title2: in Haxe ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Haxe](/languages/haxe) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haxe -class FizzBuzz { - static public function main():Void { - for (i in 1...101) { - var div3 = (i % 3 == 0); - var div5 = (i % 5 == 0); - Sys.println(div3 ? (div5 ? "FizzBuzz" : "Fizz") : (div5 ? "Buzz" : '$i')); - } - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Haxe](/languages/haxe) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/index.md b/docs/projects/fizz-buzz/index.md deleted file mode 100644 index 994067c11f..0000000000 --- a/docs/projects/fizz-buzz/index.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -date: 2018-07-27 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-05-14 -layout: default -tags: -- fizz-buzz -title: Fizz Buzz -title1: Fizz -title2: Buzz ---- - - - -Welcome to the Fizz Buzz page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -## Description - -Fizz Buzz is a typical interview question which tests the developers knowledge -of flow control and operators. The goal of the problem is to output the -numbers 1 through 100 but with special cases for various intervals--traditionally -3 (Fizz) and 5 (Buzz). - - -## Requirements - -For the purposes of this repository, the following rules apply: - -> Write a program that prints the numbers 1 to 100. However, for multiples of three, -> print "Fizz" instead of the number. Meanwhile, for multiples of five, print "Buzz" -> instead of the number. For numbers which are multiples of both three and five, -> print "FizzBuzz" - -To be even more specific, please output each value on its own line. The first 15 -lines of output should look something like: - -```console -1 -2 -Fizz -4 -Buzz -Fizz -7 -8 -Fizz -Buzz -11 -Fizz -13 -14 -FizzBuzz -``` - -The program should then be saved in a file called fizz buzz using the proper -naming conventions of your choice language. - - -## Testing - -Verify that the actual output matches the expected output -(see [Requirements](#requirements)). - - -## Articles - -There are 98 articles: - -- [Fizz Buzz in ALGOL 60](/projects/fizz-buzz/algol60) -- [Fizz Buzz in ALGOL 68](/projects/fizz-buzz/algol68) -- [Fizz Buzz in AWK](/projects/fizz-buzz/awk) -- [Fizz Buzz in Ada](/projects/fizz-buzz/ada) -- [Fizz Buzz in ArkScript](/projects/fizz-buzz/arkscript) -- [Fizz Buzz in Ballerina](/projects/fizz-buzz/ballerina) -- [Fizz Buzz in Bash](/projects/fizz-buzz/bash) -- [Fizz Buzz in Batch](/projects/fizz-buzz/batch) -- [Fizz Buzz in Beef](/projects/fizz-buzz/beef) -- [Fizz Buzz in Befunge](/projects/fizz-buzz/befunge) -- [Fizz Buzz in Boo](/projects/fizz-buzz/boo) -- [Fizz Buzz in Brainfuck](/projects/fizz-buzz/brainfuck) -- [Fizz Buzz in C](/projects/fizz-buzz/c) -- [Fizz Buzz in C#](/projects/fizz-buzz/c-sharp) -- [Fizz Buzz in C\*](/projects/fizz-buzz/c-star) -- [Fizz Buzz in C++](/projects/fizz-buzz/c-plus-plus) -- [Fizz Buzz in COBOL](/projects/fizz-buzz/cobol) -- [Fizz Buzz in Chapel](/projects/fizz-buzz/chapel) -- [Fizz Buzz in Clojure](/projects/fizz-buzz/clojure) -- [Fizz Buzz in CoffeeScript](/projects/fizz-buzz/coffeescript) -- [Fizz Buzz in Commodore BASIC](/projects/fizz-buzz/commodore-basic) -- [Fizz Buzz in Crystal](/projects/fizz-buzz/crystal) -- [Fizz Buzz in Cython](/projects/fizz-buzz/cython) -- [Fizz Buzz in D](/projects/fizz-buzz/d) -- [Fizz Buzz in Dart](/projects/fizz-buzz/dart) -- [Fizz Buzz in Dg](/projects/fizz-buzz/dg) -- [Fizz Buzz in Eiffel](/projects/fizz-buzz/eiffel) -- [Fizz Buzz in Elixir](/projects/fizz-buzz/elixir) -- [Fizz Buzz in Elvish](/projects/fizz-buzz/elvish) -- [Fizz Buzz in Erlang](/projects/fizz-buzz/erlang) -- [Fizz Buzz in Euphoria](/projects/fizz-buzz/euphoria) -- [Fizz Buzz in F#](/projects/fizz-buzz/f-sharp) -- [Fizz Buzz in Fennel](/projects/fizz-buzz/fennel) -- [Fizz Buzz in Fetlang](/projects/fizz-buzz/fetlang) -- [Fizz Buzz in Forth](/projects/fizz-buzz/forth) -- [Fizz Buzz in Fortran](/projects/fizz-buzz/fortran) -- [Fizz Buzz in GNU Make](/projects/fizz-buzz/gnu-make) -- [Fizz Buzz in Go](/projects/fizz-buzz/go) -- [Fizz Buzz in Goby](/projects/fizz-buzz/goby) -- [Fizz Buzz in Gosu](/projects/fizz-buzz/gosu) -- [Fizz Buzz in Gravity](/projects/fizz-buzz/gravity) -- [Fizz Buzz in Groovy](/projects/fizz-buzz/groovy) -- [Fizz Buzz in Haskell](/projects/fizz-buzz/haskell) -- [Fizz Buzz in Haxe](/projects/fizz-buzz/haxe) -- [Fizz Buzz in Io](/projects/fizz-buzz/io) -- [Fizz Buzz in Janet](/projects/fizz-buzz/janet) -- [Fizz Buzz in Java](/projects/fizz-buzz/java) -- [Fizz Buzz in JavaScript](/projects/fizz-buzz/javascript) -- [Fizz Buzz in Julia](/projects/fizz-buzz/julia) -- [Fizz Buzz in Kotlin](/projects/fizz-buzz/kotlin) -- [Fizz Buzz in LOLCODE](/projects/fizz-buzz/lolcode) -- [Fizz Buzz in Lisp](/projects/fizz-buzz/lisp) -- [Fizz Buzz in LiveScript](/projects/fizz-buzz/livescript) -- [Fizz Buzz in Lobster](/projects/fizz-buzz/lobster) -- [Fizz Buzz in Lua](/projects/fizz-buzz/lua) -- [Fizz Buzz in Mathematica](/projects/fizz-buzz/mathematica) -- [Fizz Buzz in MoonScript](/projects/fizz-buzz/moonscript) -- [Fizz Buzz in Nim](/projects/fizz-buzz/nim) -- [Fizz Buzz in OCaml](/projects/fizz-buzz/ocaml) -- [Fizz Buzz in Objective-C](/projects/fizz-buzz/objective-c) -- [Fizz Buzz in Octave](/projects/fizz-buzz/octave) -- [Fizz Buzz in Odin](/projects/fizz-buzz/odin) -- [Fizz Buzz in PHP](/projects/fizz-buzz/php) -- [Fizz Buzz in Pascal](/projects/fizz-buzz/pascal) -- [Fizz Buzz in Perl](/projects/fizz-buzz/perl) -- [Fizz Buzz in Pineapple](/projects/fizz-buzz/pineapple) -- [Fizz Buzz in Pinecone](/projects/fizz-buzz/pinecone) -- [Fizz Buzz in Pony](/projects/fizz-buzz/pony) -- [Fizz Buzz in PowerShell](/projects/fizz-buzz/powershell) -- [Fizz Buzz in Prolog](/projects/fizz-buzz/prolog) -- [Fizz Buzz in Pyret](/projects/fizz-buzz/pyret) -- [Fizz Buzz in Python](/projects/fizz-buzz/python) -- [Fizz Buzz in R](/projects/fizz-buzz/r) -- [Fizz Buzz in Racket](/projects/fizz-buzz/racket) -- [Fizz Buzz in Raku](/projects/fizz-buzz/raku) -- [Fizz Buzz in Red](/projects/fizz-buzz/red) -- [Fizz Buzz in Rexx](/projects/fizz-buzz/rexx) -- [Fizz Buzz in Ruby](/projects/fizz-buzz/ruby) -- [Fizz Buzz in Rust](/projects/fizz-buzz/rust) -- [Fizz Buzz in Scala](/projects/fizz-buzz/scala) -- [Fizz Buzz in Smalltalk](/projects/fizz-buzz/smalltalk) -- [Fizz Buzz in Solisp](/projects/fizz-buzz/solisp) -- [Fizz Buzz in Swift](/projects/fizz-buzz/swift) -- [Fizz Buzz in TI-BASIC](/projects/fizz-buzz/ti-basic) -- [Fizz Buzz in Tcl](/projects/fizz-buzz/tcl) -- [Fizz Buzz in TeX](/projects/fizz-buzz/tex) -- [Fizz Buzz in TypeScript](/projects/fizz-buzz/typescript) -- [Fizz Buzz in Unicat](/projects/fizz-buzz/unicat) -- [Fizz Buzz in V](/projects/fizz-buzz/v) -- [Fizz Buzz in Verve](/projects/fizz-buzz/verve) -- [Fizz Buzz in Vimscript](/projects/fizz-buzz/vimscript) -- [Fizz Buzz in Visual Basic](/projects/fizz-buzz/visual-basic) -- [Fizz Buzz in Whitespace](/projects/fizz-buzz/whitespace) -- [Fizz Buzz in Wren](/projects/fizz-buzz/wren) -- [Fizz Buzz in Wu](/projects/fizz-buzz/wu) -- [Fizz Buzz in Zig](/projects/fizz-buzz/zig) -- [Fizz Buzz in m4](/projects/fizz-buzz/m4) -- [Fizz Buzz in x86-64](/projects/fizz-buzz/x86-64) - -*** - - \ No newline at end of file diff --git a/docs/projects/fizz-buzz/io/index.md b/docs/projects/fizz-buzz/io/index.md deleted file mode 100644 index 6862213d18..0000000000 --- a/docs/projects/fizz-buzz/io/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-12 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-12 -layout: default -tags: -- fizz-buzz -- io -title: Fizz Buzz in Io -title1: Fizz Buzz -title2: in Io ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Io](/languages/io) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```io -for (a, 1, 100, - if ((a % 3) != 0 and (a % 5) != 0, - a print - ) - - if ((a % 3) == 0, - "Fizz" print - ) - - if ((a % 5) == 0, - "Buzz" print - ) - - "\n" print -) - -``` - -{% endraw %} - -Fizz Buzz in [Io](/languages/io) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/janet/index.md b/docs/projects/fizz-buzz/janet/index.md deleted file mode 100644 index 283f229525..0000000000 --- a/docs/projects/fizz-buzz/janet/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- janet -title: Fizz Buzz in Janet -title1: Fizz Buzz -title2: in Janet ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Janet](/languages/janet) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```janet -(loop [n :range [1 101]] - (print (cond - (zero? (% n 15)) "FizzBuzz" - (zero? (% n 5)) "Buzz" - (zero? (% n 3)) "Fizz" - n))) - -``` - -{% endraw %} - -Fizz Buzz in [Janet](/languages/janet) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/java/index.md b/docs/projects/fizz-buzz/java/index.md deleted file mode 100644 index e66c51a73a..0000000000 --- a/docs/projects/fizz-buzz/java/index.md +++ /dev/null @@ -1,169 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- shubhragupta-code -- Stuart -date: 2018-09-08 -featured-image: fizz-buzz-in-java.jpg -last-modified: 2023-05-15 -layout: default -tags: -- fizz-buzz -- java -title: Fizz Buzz in Java -title1: Fizz Buzz -title2: in Java ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class FizzBuzz { - public static void main(String[] args) { - for (int i = 1; i < 101; i++) { - String output = ""; - if (i % 3 == 0) { - output += "Fizz"; - } - if (i % 5 == 0) { - output += "Buzz"; - } - if (output.isEmpty()) { - output += i; - } - System.out.println(output); - } - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Java](/languages/java) was written by: - -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code -- Stuart - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Java is a very standard looking programming language, so this code may look quite familiar. - -The rules of the problem are quite straightforward: - - If a number is divisible by 3, print the word 'Fizz' instead of the number. - If the number is divisible by 5, print the word 'Buzz' instead of the number. - Finally, if the number is divisible by both 3 and 5, print 'FizzBuzz' instead - of the number. Otherwise, just print the number. - -The modulo operator will let us easily check for divisibility, as it returns the remainder -from a division. When `i` is divisible by 3, `i % 3` will just be 0. - -### The Function - -As with any Java program, we start out with a `public class`, (named the same as the -FizzBuzz.java file). Then inside that we set up a `main` function, with a array of string arguments. - -```java -public class FizzBuzz { - public static void main(String[] args) { - ... - } -} -``` - -The program is within that one function, so we do not need to pay any more attention to that. - -### The Loop - -Next we will set up the required loop, going from 1 to 100. We can use a simple for -loop to achieve that. - -```java -for (int i = 1; i < 101; i++) { - ... -} -``` - -The first part of it is a variable, int `i` stores a number and is started at 1. -The loop is then set to run repeatedly until `i` is greater than 100. Finally `i++ `means -that every time the loop is run, `i` will increase by 1. - -### Control Flow - -Each time the loop runs, it will first create a blank String to hold the output -(This just stores a list of characters for later display). - -```java -String output = ""; -``` - -Each if statement will then check for divisibility and add to the output variable. - -```java -if (i % 3 == 0) { - output += "Fizz"; -} -if (i % 5 == 0) { - output += "Buzz"; -} -if (output.isEmpty()) { - output += i; -} -``` - -If `i` is divisible by 3, add `"Fizz"`, then if `i` is divisible by 5, add `"Buzz"`. Notice -that there is no else statement, so both of them can run consecutively. This -also uses Java's handy ability to just add two strings together and attach one -to the end of the other. If the output is still blank after the first if -statements, then put the number there instead. - -### The Output - -Finally we have a long statement to put that output onto the screen. - -```java -System.out.println(output); -``` - -This references a standard library function, and can be used at any time to output -text. The `ln` at the end means that after the output variable is printed it will -be followed by a newline, allowing the next loop to follow. - - -## How to Run the Solution - -First we will need to grab the latest version of Java, particularly the Java -Development Kit (JDK). Next we need to save the code into a file named -`FizzBuzz.java`. Finally, in the folder with the code, we shall run the commands: - -```console -javac FizzBuzz.java -java FizzBuzz -``` - -There are plenty of online compilers available as well. diff --git a/docs/projects/fizz-buzz/javascript/index.md b/docs/projects/fizz-buzz/javascript/index.md deleted file mode 100644 index a2503ef6ff..0000000000 --- a/docs/projects/fizz-buzz/javascript/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Juan F Gonzalez -- Pascal Spiesz -- rzuckerm -date: 2018-07-27 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-05-15 -layout: default -tags: -- fizz-buzz -- javascript -title: Fizz Buzz in JavaScript -title1: Fizz Buzz in -title2: JavaScript ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -function fizzbuzz(num){ - for(let i=1; i <= num; i++){ - if(i % 15 == 0){ - console.log("FizzBuzz"); - } - else if(i % 5 == 0){ - console.log("Buzz"); - } - else if(i % 3 == 0){ - console.log("Fizz"); - } - else console.log(i); - } - } - -fizzbuzz(100); - -``` - -{% endraw %} - -Fizz Buzz in [JavaScript](/languages/javascript) was written by: - -- Jeremy Grifski -- Juan F Gonzalez - -This article was written by: - -- Jeremy Grifski -- Pascal Spiesz -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -FizzBuzz is quite a simple program. -In line 1 the `fizzbuzz` function gets declared. It takes a parameter `num` that determines how far the program should count. -The counting logic takes place in a for-loop in line 2. It starts counting at 1, increases the counter `i` by 1 in every iteration and stops once it reaches `num`. - -To understand the main logic of this programm you need to know. - -## The modulo (remainder) operator % - ->> The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend. ([Mozilla][1]) - -The trick here is to create a _truthy_ value for the if statements. This is why you can see the `i % 3 == 0` etc. conditionals. If a number is divisible by 3 there will be no remainder, in other words the remainder is true and thus i % 3 == 0 (% 5, % 15) is true in these cases. - -Hint: The order of the conditionals matters. If you'd check for example in reverse order, you would print all 3 strings, if the number is divisible by 3 _and_ 5! - -Hint: Instead of `i % 15 == 0` you could also write `i % 3 && i % 5`. - -Last, but not least, it prints the number via the else clause `else console.log(i);` if none of the conditionals were true. - -Extra mile: If you want you can move the conditionals into variables and move them up the scope, right after the second line between the for loop and the first if statement. -For example: `const divisibleBy3 = i % 3`. This way you'd remove the use of [magic numbers][2]. - -Fun Fact: Despite being a simple programming exercise there is a controversal article about the question [Why can't programmers program?](https://blog.codinghorror.com/why-cant-programmers-program/) that even led to an ["enterprise-class"](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition) version of this game. - -[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder -[2]: https://en.wikipedia.org/wiki/Magic_number_(programming) - - -## How to Run the Solution - -### In the Browser - -To try out this script just copy it, open the dev tools of your Browser (F12 by default in most cases), head to the `console` tab, paste in the script and press enter to run it. - -### Node.js - -Download and install `Node.js`. -Save the script in, for example, `index.js` and from the same directory open a console of your choice (cmd, powershell, bash, etc.) and run `node index.js`. -Hint: Depending on your operating system the node binary might be called slightly different for example on some linux distributions, you'd need to type `nodejs index.js` instead. diff --git a/docs/projects/fizz-buzz/julia/index.md b/docs/projects/fizz-buzz/julia/index.md deleted file mode 100644 index 97add1e8bf..0000000000 --- a/docs/projects/fizz-buzz/julia/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Michael King -date: 2018-10-12 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2018-10-12 -layout: default -tags: -- fizz-buzz -- julia -title: Fizz Buzz in Julia -title1: Fizz Buzz -title2: in Julia ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -#!/usr/bin/julia - -for i = 1:100 - str = i % 3 == 0 ? "Fizz" : "" - str *= i % 5 == 0 ? "Buzz" : "" - if isempty(str) - str = i - end - println(str) -end - -``` - -{% endraw %} - -Fizz Buzz in [Julia](/languages/julia) was written by: - -- Michael King - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/kotlin/index.md b/docs/projects/fizz-buzz/kotlin/index.md deleted file mode 100644 index 451943b63c..0000000000 --- a/docs/projects/fizz-buzz/kotlin/index.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -authors: -- ali-abdullah -- Jeremy Grifski -- rzuckerm -- Stuart Irwin -date: 2018-10-11 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-05-15 -layout: default -tags: -- fizz-buzz -- kotlin -title: Fizz Buzz in Kotlin -title1: Fizz Buzz -title2: in Kotlin ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array){ - for (i in 1..100){ - when { - (i % 3 == 0 && i % 5 == 0) -> println("FizzBuzz") - i % 3 == 0 -> println("Fizz") - i % 5 == 0 -> println("Buzz") - else -> println("$i") - } - } -} -``` - -{% endraw %} - -Fizz Buzz in [Kotlin](/languages/kotlin) was written by: - -- ali-abdullah - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Kotlin is structured very similarly to Java, but there are a lot of nice features in the syntax. - -The rules of the problem are quite straightforward: - - If a number is divisible by 3, print the word 'Fizz' instead of the number. - If the number is divisible by 5, print the word 'Buzz' instead of the number. - Finally, if the number is divisible by both 3 and 5, print 'FizzBuzz' instead - of the number. Otherwise, just print the number. - -### The Function - -The main function of the program is the same as always, just a single line to start. - -```kotlin -fun main(args: Array){ -``` - -This creates a simple function to contain all the other code. - -### The Loop - -Next we will set up the required loop, going from 1 to 100. Kotlin makes this very easy. - -```kotlin -for (i in 1..100){ -``` - -Now we get into less familiar territory, with a `when` statement. This is similar to a `switch` statement in other languages, but it is much more flexible. - -```kotlin -when { - (i % 3 == 0 && i % 5 == 0) -> println("FizzBuzz") - i % 3 == 0 -> println("Fizz") - i % 5 == 0 -> println("Buzz") - else -> println("$i") -} -``` - -For each line, the condition to the left of the arrow will be checked, and when a line returns `true`, the code on the right of the arrow will be executed. -It is worth mentioning that Kotlin has optional semicolons, but a newline works fine in most cases. - -The first three lines are then pretty standard -1. if i is divisible by 3 and 5, print `"FizzBuzz"` -2. if i is only divisible by 3, print `"Fizz"` -3. if i is only divisible by 5, print `"Buzz"` - -The only thing left to mention is the last line, - -```kotlin -else -> println("$i") -``` - -If none of the other conditions are `true`, this default statement is run which prints out the value of `i`. -The fact that `i` is contained inside a string is completely unnesesary, but does demonstrate one of the nice features of Kotlin. - -Variables can be inserted into a string at any point, and code can be executed if neccesary. -For example, `"2 + 2 = ${2 + 2}"` would in fact calculate the simple string `"2 + 2 = 4"`. - - -## How to Run the Solution - -Online compilers such as [Kotlin Playground][2] or this [Online Kotlin Compiler][3] are a good way to get started. - -To run on a personal computer, the ideal environment is [IntelliJ IDEA][4], as it and kotlin were both created by JetBrains. -If you have installed the command line version however, save the program to FizzBuzz.kt and run with these commands. -```bash -kotlinc FizzBuzz.kt -include-runtime -d FizzBuzz.jar -java -jar FizzBuzz.jar -``` - -[2]: https://play.kotlinlang.org/ -[3]: https://www.tutorialspoint.com/compile_kotlin_online.php -[4]: https://www.jetbrains.com/idea/ diff --git a/docs/projects/fizz-buzz/lisp/index.md b/docs/projects/fizz-buzz/lisp/index.md deleted file mode 100644 index 607634e683..0000000000 --- a/docs/projects/fizz-buzz/lisp/index.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -- rzuckerm -- shubhragupta-code -- Stuart Irwin -date: 2019-10-18 -featured-image: fizz-buzz-in-lisp.jpg -last-modified: 2023-05-15 -layout: default -tags: -- fizz-buzz -- lisp -title: Fizz Buzz in Lisp -title1: Fizz Buzz -title2: in Lisp ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(defun divides-by (num divisor) - (= (mod num divisor) 0)) - -(dotimes (num 100) - (write-line - (cond - ((and (divides-by (+ num 1) 3) (divides-by (+ num 1) 5)) "FizzBuzz") - ((divides-by (+ num 1) 3) "Fizz") - ((divides-by (+ num 1) 5) "Buzz") - (t (write-to-string (+ num 1)))))) -``` - -{% endraw %} - -Fizz Buzz in [Lisp](/languages/lisp) was written by: - -- Parker Johansen - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Lisp has many flavors and variations, so we will be using Clisp, the most common and general form. -The code follows a pre-fix format, where a function or operator is followed by its arguments, even in the case of `+` or `=`. -Every set of parenthesis is its own function. - -As a quick note, here are the rules to the problem: - - If a number is divisible by 3, print the word 'Fizz' instead of the number. - If the number is divisible by 5, print the word 'Buzz' instead of the number. - Finally, if the number is divisible by both 3 and 5, print 'FizzBuzz' instead - of the number. Otherwise, just print the number. - -### The Loop - -The first line of code sets up the loop, running the functions inside 100 times, with an index variable named `run`. - -```lisp -(dotimes (run 100) ...) -``` - -The dots show where more lines of code will be placed, such as `setq` which creates a new integer variable. - -```lisp -(dotimes (run 100) (setq num (+ run 1)) ...) -``` - -The new variable is named `num`, and set to the current `run` value + 1. - -### The output - -The next lines are used to print out the actual ouput, but only one of those is a print statement. -`write-line` will take a string input and print it out as a line to console. Inside it is `cond`, which creates essentially a list of if-else statements, expecting pairs of boolean + executable. - -```lisp -(write-line (cond - ... -)) -``` - -Each following line is one possible output, starting with the `"FizzBuzz"` phrase. - -```lisp -((and (= (mod num 3) 0) (= (mod num 5) 0)) "FizzBuzz") -``` - -To restate this in a more traditional format, - -```c -if(num % 3 == 0 && num % 5 == 0) then "FizzBuzz" -``` - -The next two checks are simaler, just testing for each option. - -```lisp -((= (mod num 3) 0) "Fizz") -((= (mod num 5) 0) "Buzz") -``` - -Finally, the last line in the set has no if statement, and is the default alternative, just writing the `num` variable to a string. - -```lisp -(t (write-to-string num)) -``` - -The code will run through each if statement until one of them is true, then use the connected string as an argument for `write-line`, printing it out to the console. - - -## How to Run the Solution - -There are many options for running the code, though make sure to be using a CLisp based tool. - -To run on a local machine, we can download a copy of [Steel Bank Common Lisp][1] -as well as a copy of the solution. Assuming SBCL is in the path, -we can run a lisp file like a script as follows: - -``` -sbcl --script fizz-buzz.lsp -``` - -For an easy online interpreter, here are some options: - -- [CompileOnline CLISP][2] -- [Jdoodle CLISP][3] - -[1]: https://www.sbcl.org/ -[2]: https://ideone.com/l/clips -[3]: https://www.jdoodle.com/execute-clisp-online/ diff --git a/docs/projects/fizz-buzz/livescript/index.md b/docs/projects/fizz-buzz/livescript/index.md deleted file mode 100644 index 5c3c9e08a6..0000000000 --- a/docs/projects/fizz-buzz/livescript/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- JonusClapshaw -date: 2025-10-29 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-29 -layout: default -tags: -- fizz-buzz -- livescript -title: Fizz Buzz in LiveScript -title1: Fizz Buzz in -title2: LiveScript ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [LiveScript](/languages/livescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```livescript -for i from 1 to 100 - word = '' - word += 'Fizz' if i % 3 is 0 - word += 'Buzz' if i % 5 is 0 - console.log(word or i) -``` - -{% endraw %} - -Fizz Buzz in [LiveScript](/languages/livescript) was written by: - -- JonusClapshaw - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/lobster/index.md b/docs/projects/fizz-buzz/lobster/index.md deleted file mode 100644 index e361e0a78a..0000000000 --- a/docs/projects/fizz-buzz/lobster/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Kravcant -date: 2025-10-24 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-24 -layout: default -tags: -- fizz-buzz -- lobster -title: Fizz Buzz in Lobster -title1: Fizz Buzz -title2: in Lobster ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Lobster](/languages/lobster) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lobster -for (100) i: - let n = i + 1 - if (n % 3 == 0 and n % 5 == 0): - print("FizzBuzz") - elif (n % 3 == 0): - print("Fizz") - elif (n % 5 == 0): - print("Buzz") - else: - print(n) - -``` - -{% endraw %} - -Fizz Buzz in [Lobster](/languages/lobster) was written by: - -- Kravcant - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/lolcode/index.md b/docs/projects/fizz-buzz/lolcode/index.md deleted file mode 100644 index e5be095738..0000000000 --- a/docs/projects/fizz-buzz/lolcode/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- sayashraaj -date: 2020-10-01 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2020-10-01 -layout: default -tags: -- fizz-buzz -- lolcode -title: Fizz Buzz in LOLCODE -title1: Fizz Buzz -title2: in LOLCODE ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [LOLCODE](/languages/lolcode) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lolcode -HAI 1.2 - -IM IN YR loop UPPIN YR var TIL BOTH SAEM var AN 101 - - DIFFRINT 0 AN var - O RLY? - YA RLY - I HAS A by3 ITZ BOTH SAEM 0 AN MOD OF var AN 3 - I HAS A by5 ITZ BOTH SAEM 0 AN MOD OF var AN 5 - - BOTH OF by3 AN by5 - O RLY? - YA RLY - VISIBLE "FizzBuzz" - NO WAI - by3 - O RLY? - YA RLY - VISIBLE "Fizz" - NO WAI - by5 - O RLY? - YA RLY - VISIBLE "Buzz" - NO WAI - VISIBLE var - OIC - OIC - OIC - OIC - -IM OUTTA YR loop -KTHXBYE -``` - -{% endraw %} - -Fizz Buzz in [LOLCODE](/languages/lolcode) was written by: - -- sayashraaj - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/lua/index.md b/docs/projects/fizz-buzz/lua/index.md deleted file mode 100644 index 65a6012efb..0000000000 --- a/docs/projects/fizz-buzz/lua/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-09-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2018-09-19 -layout: default -tags: -- fizz-buzz -- lua -title: Fizz Buzz in Lua -title1: Fizz Buzz -title2: in Lua ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -for i = 1, 100 do - output = "" - - if i % 3 == 0 then - output = output .. "Fizz" - end - - if i % 5 == 0 then - output = output .. "Buzz" - end - - if output == "" then - output = i - end - - print(output) -end - -``` - -{% endraw %} - -Fizz Buzz in [Lua](/languages/lua) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/m4/index.md b/docs/projects/fizz-buzz/m4/index.md deleted file mode 100644 index 06dc66f00f..0000000000 --- a/docs/projects/fizz-buzz/m4/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-09 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-08-09 -layout: default -tags: -- fizz-buzz -- m4 -title: Fizz Buzz in m4 -title1: Fizz Buzz -title2: in m4 ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`fizzbuzz', -`ifelse(eval($1 <= $2), 1, -`ifelse(eval($1 % 15), 0, FizzBuzz, -`ifelse(eval($1 % 3), 0, Fizz, -`ifelse(eval($1 % 5), 0, Buzz, $1)')')' -`fizzbuzz(eval($1 + 1), $2)', )'dnl -) -divert(0)dnl -fizzbuzz(1, 100)dnl - -``` - -{% endraw %} - -Fizz Buzz in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/mathematica/index.md b/docs/projects/fizz-buzz/mathematica/index.md deleted file mode 100644 index cb9a9ae056..0000000000 --- a/docs/projects/fizz-buzz/mathematica/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-01-21 -layout: default -tags: -- fizz-buzz -- mathematica -title: Fizz Buzz in Mathematica -title1: Fizz Buzz in -title2: Mathematica ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* It would be easy to simply print these out in a loop; however, in the spirit -of keeping the mathematical operation separate from its presentation I opted -to return the result as a list explicitly: *) - -fizzBuzz = Function[{n}, - Table[ - Which[ - Divisible[i, 15], "FizzBuzz", - Divisible[i, 5], "Buzz", - Divisible[i, 3], "Fizz", - True, i], {i, n}]]; - -(* This can be presented trivially: *) - -Column[fizzBuzz[100]] - - -(* Valid Tests *) - - -(* Invalid Tests *) - -``` - -{% endraw %} - -Fizz Buzz in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/moonscript/index.md b/docs/projects/fizz-buzz/moonscript/index.md deleted file mode 100644 index 3568c7ce3c..0000000000 --- a/docs/projects/fizz-buzz/moonscript/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Kimberly Mageary -date: 2024-11-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-11-19 -layout: default -tags: -- fizz-buzz -- moonscript -title: Fizz Buzz in MoonScript -title1: Fizz Buzz in -title2: MoonScript ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [MoonScript](/languages/moonscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```moonscript -for i = 1, 100 - if i % 3 == 0 and i % 5 == 0 - print "FizzBuzz" - continue - if i % 3 == 0 - print "Fizz" - continue - if i % 5 == 0 - print "Buzz" - continue - else - print i -``` - -{% endraw %} - -Fizz Buzz in [MoonScript](/languages/moonscript) was written by: - -- Kimberly Mageary - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/nim/index.md b/docs/projects/fizz-buzz/nim/index.md deleted file mode 100644 index 91d19903c8..0000000000 --- a/docs/projects/fizz-buzz/nim/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- nim -title: Fizz Buzz in Nim -title1: Fizz Buzz -title2: in Nim ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Nim](/languages/nim) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nim -for i in 1..100: - if i mod 15 == 0: - echo "FizzBuzz" - elif i mod 5 == 0: - echo "Buzz" - elif i mod 3 == 0: - echo "Fizz" - else: - echo i - -``` - -{% endraw %} - -Fizz Buzz in [Nim](/languages/nim) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/objective-c/index.md b/docs/projects/fizz-buzz/objective-c/index.md deleted file mode 100644 index 8c3a4e0d6c..0000000000 --- a/docs/projects/fizz-buzz/objective-c/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Juan D Frias -- Ștefan-Iulian Alecu -date: 2019-10-16 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-04-30 -layout: default -tags: -- fizz-buzz -- objective-c -title: Fizz Buzz in Objective-C -title1: Fizz Buzz in -title2: Objective-C ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -int main(int argc, const char* argv[]) { - @autoreleasepool { - NSMutableString* output = [NSMutableString stringWithCapacity:8]; - - for (NSInteger i = 1; i <= 100; i++) { - [output setString:@""]; - - if (i % 3 == 0) [output appendString:@"Fizz"]; - if (i % 5 == 0) [output appendString:@"Buzz"]; - - if (output.length > 0) { - printf("%s\n", output.UTF8String); - } else { - printf("%ld\n", (long)i); - } - } - } - return 0; -} - -``` - -{% endraw %} - -Fizz Buzz in [Objective-C](/languages/objective-c) was written by: - -- Juan D Frias -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/ocaml/index.md b/docs/projects/fizz-buzz/ocaml/index.md deleted file mode 100644 index 355516fec4..0000000000 --- a/docs/projects/fizz-buzz/ocaml/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- ocaml -title: Fizz Buzz in OCaml -title1: Fizz Buzz -title2: in OCaml ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let fizzbuzz i = - if i mod 15 == 0 - then "FizzBuzz" - else if i mod 5 == 0 - then "Buzz" - else if i mod 3 == 0 - then "Fizz" - else string_of_int i -;; - -for i = 1 to 100 do - print_string (fizzbuzz(i) ^ "\n") -done;; - -``` - -{% endraw %} - -Fizz Buzz in [OCaml](/languages/ocaml) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/octave/index.md b/docs/projects/fizz-buzz/octave/index.md deleted file mode 100644 index 55d40bd440..0000000000 --- a/docs/projects/fizz-buzz/octave/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- darkpanda08 -- rzuckerm -date: 2020-10-01 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-12-09 -layout: default -tags: -- fizz-buzz -- octave -title: Fizz Buzz in Octave -title1: Fizz Buzz -title2: in Octave ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function fizz_buzz() - - % Loop from 1 to 100 - for i = 1:100 - fizzbuzz = ''; - - % Check if i is divisible by 3 - if mod(i,3) == 0 - fizzbuzz = [fizzbuzz 'Fizz']; - end - - % Check if i is divisible by 5 - if mod(i,5) == 0 - fizzbuzz = [fizzbuzz 'Buzz']; - end - - % If fizzbuzz variable is empty,print i - if isempty(fizzbuzz) - disp(i); - else - % If fizzbuzz variable is not empty, print the variable - disp(fizzbuzz); - end - end -end - -``` - -{% endraw %} - -Fizz Buzz in [Octave](/languages/octave) was written by: - -- darkpanda08 -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/odin/index.md b/docs/projects/fizz-buzz/odin/index.md deleted file mode 100644 index 1296592b24..0000000000 --- a/docs/projects/fizz-buzz/odin/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- odin -title: Fizz Buzz in Odin -title1: Fizz Buzz -title2: in Odin ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main - -import "core:fmt" - -main :: proc() { - for i in 1..=100 { - if i % 15 == 0 { - fmt.println("FizzBuzz") - } else if i % 5 == 0 { - fmt.println("Buzz") - } else if i % 3 == 0 { - fmt.println("Fizz") - } else { - fmt.println(i) - } - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Odin](/languages/odin) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/pascal/index.md b/docs/projects/fizz-buzz/pascal/index.md deleted file mode 100644 index 8cbe53f9cb..0000000000 --- a/docs/projects/fizz-buzz/pascal/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Eduardo Rodríguez -date: 2018-10-11 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2018-10-11 -layout: default -tags: -- fizz-buzz -- pascal -title: Fizz Buzz in Pascal -title1: Fizz Buzz -title2: in Pascal ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program FizzBuzz(output); -var - i : integer; -begin - for i := 1 to 100 do - if i mod 15 = 0 then - writeln('FizzBuzz') - else if i mod 3 = 0 then - writeln('Fizz') - else if i mod 5 = 0 then - writeln('Buzz') - else - writeln(i) -end. - -``` - -{% endraw %} - -Fizz Buzz in [Pascal](/languages/pascal) was written by: - -- Eduardo Rodríguez - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/perl/index.md b/docs/projects/fizz-buzz/perl/index.md deleted file mode 100644 index 62a545f1e2..0000000000 --- a/docs/projects/fizz-buzz/perl/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2019-03-25 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-05-14 -layout: default -tags: -- fizz-buzz -- perl -title: Fizz Buzz in Perl -title1: Fizz Buzz -title2: in Perl ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -sub fizzbuzz ($n) { - my $s = ''; - - $s .= "Fizz" if $n % 3 == 0; - $s .= "Buzz" if $n % 5 == 0; - - return $s || $n; -} - -say fizzbuzz($_) for 1 .. 100; - -``` - -{% endraw %} - -Fizz Buzz in [Perl](/languages/perl) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/php/index.md b/docs/projects/fizz-buzz/php/index.md deleted file mode 100644 index 2d6e55a405..0000000000 --- a/docs/projects/fizz-buzz/php/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-09-09 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2022-05-09 -layout: default -tags: -- fizz-buzz -- php -title: Fizz Buzz in PHP -title1: Fizz Buzz -title2: in PHP ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Pineapple](/languages/pineapple) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pineapple -def .main - let i mutable = 1 - while i <= 100 - if i % 15 == 0 - "FizzBuzz".show - elif i % 3 == 0 - "Fizz".show - elif i % 5 == 0 - "Buzz".show - else - i.show - - i = i + 1 - -``` - -{% endraw %} - -Fizz Buzz in [Pineapple](/languages/pineapple) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/pinecone/index.md b/docs/projects/fizz-buzz/pinecone/index.md deleted file mode 100644 index 867801976b..0000000000 --- a/docs/projects/fizz-buzz/pinecone/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-02 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-12-02 -layout: default -tags: -- fizz-buzz -- pinecone -title: Fizz Buzz in Pinecone -title1: Fizz Buzz -title2: in Pinecone ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Pinecone](/languages/pinecone) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pinecone -i: 1 | i <= 100 | i: i + 1 @ ( - i % 15 = 0 ? ( - print: "FizzBuzz" - ) | - i % 3 = 0 ? ( - print: "Fizz" - ) | - i % 5 = 0 ? ( - print: "Buzz" - ) | ( - print: i - ) -) - -``` - -{% endraw %} - -Fizz Buzz in [Pinecone](/languages/pinecone) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/pony/index.md b/docs/projects/fizz-buzz/pony/index.md deleted file mode 100644 index 2350685be2..0000000000 --- a/docs/projects/fizz-buzz/pony/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- pony -title: Fizz Buzz in Pony -title1: Fizz Buzz -title2: in Pony ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Pony](/languages/pony) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pony -use "collections" - -actor Main - new create(env: Env) => - for i in Range[I32](1, 101) do - env.out.print(fizzbuzz(i)) - end - - fun fizzbuzz(n: I32): String => - if (n % 15) == 0 then - "FizzBuzz" - elseif (n % 5) == 0 then - "Buzz" - elseif (n % 3) == 0 then - "Fizz" - else - n.string() - end - -``` - -{% endraw %} - -Fizz Buzz in [Pony](/languages/pony) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/powershell/index.md b/docs/projects/fizz-buzz/powershell/index.md deleted file mode 100644 index 8db2ae0dc1..0000000000 --- a/docs/projects/fizz-buzz/powershell/index.md +++ /dev/null @@ -1,386 +0,0 @@ ---- -authors: -- Devin Leaman -- Jeremy Grifski -- rzuckerm -date: 2018-08-04 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-05-15 -layout: default -tags: -- fizz-buzz -- powershell -title: Fizz Buzz in PowerShell -title1: Fizz Buzz in -title2: PowerShell ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -<# -.SYNOPSIS - A simple script that solves the standard FizzBuzz interview problem. - -.DESCRIPTION - A simple script that solves the FizzBuzz interview problem to illustrate flow -control within a PowerShell script. - -.PARAMETER Min - The minimium value to start counting at (inclusive). Defaults to 1. - -.PARAMETER Max - The maximum value to count to (inclusive). Defaults to 100. - -.EXAMPLE - .\FizzBuzz.ps1 -1 -2 -Fizz -4 -Buzz -Fizz -... - -.EXAMPLE - .\FizzBuzz.ps1 -Min 0 -Max 75 -FizzBuzz -1 -2 -Fizz -4 -... - -.NOTES - For reference, here's a copy of the FizzBuzz problem that this script solves, -the only difference between the requested solution and this script is the script -will let you determine the minimum and maximum values if you desire: - -"Write a program that prints the numbers 1 to 100. However, for multiples of -three, print "Fizz" instead of the number. Meanwhile, for multiples of five, -print "Buzz" instead of the number. For numbers which are multiples of both, -print "FizzBuzz" -#> -[CmdletBinding()] -param ( - [Parameter(Mandatory = $false, Position = 0)] - [int]$Min = 1, - - [Parameter(Mandatory = $false, Position = 1)] - [int]$Max = 100 -) - -for ($X = $Min; $X -le $Max; $X++) { - $Output = "" - - if ($X % 3 -eq 0) { $Output += "Fizz" } - if ($X % 5 -eq 0) { $Output += "Buzz" } - if ($Output -eq "") { $Output = $X } - - Write-Output $Output -} - -``` - -{% endraw %} - -Fizz Buzz in [PowerShell](/languages/powershell) was written by: - -- Devin Leaman -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -I'm going to start with a little anecdote before getting started on the meaty -portion of this article, so feel free to skip ahead to [No More Anecdote](#no-more-anecdote) -if you're just not that interested 😅, I completely understand. - -I realized about two weeks ago that I hadn't written anything in a while and had -a bit of a desire to write, with nothing coming to mind on what to write. I was -also dealing with a nagging feeling in my brain of "Should I really write another -article?", and if I did, "Who really cares if I write another article? There are -countless others writing about the same stuff", among other negative thoughts. - -I went to a get together with some of my best friends to eat tacos, drink some -tequila, and just enjoy each others company. While I was there, one of my more -technically oriented friends came up to me and we began talking about my work, -playing Overwatch, and other nerdy things, when he mentions to me that he enjoyed -reading my past articles. While he may not be a currently active developer and -that some of the stuff goes over his head, I've "got a knack for it" as he said. - -> Tron that are heavily requested by the user base. It was enough to remind me the -> whole reason I started writing these is for the off-chance that someone like that -> would enjoy my writing and possibly get them more interested in programming, learn -> something new, or simply enjoy the read for the sake of reading something interesting. - -In the end, I'd like to say thank you again to that friend of mine for the -encouraging words, as I probably wouldn't have had the motivation to start on -this without them 💗. - -### No More Anecdote - -And now we're off to the juicy bits of the article! 🤤 If you're unfamiliar with -the Fizz Buzz interview problem, it's a relatively simple problem that is adept -at testing your knowledge and fundamental understanding of a given programming -language as well as showing the interviewer what kind of developer you are. - -For example, do you prefer to toss a bunch of things at the wall and see what -works and whittle away the excess? Or do you prefer to lay out a plan for the -program before you even write some code? If you'd like more information on the -things interviewers can glean from a Fizz Buzz solution, feel free to check out -this article from Lionell Pack on Forbes. - -### What's The Problem? - -The actual problem was (from what I can tell, please correct me if I'm wrong) -initially put forth by Imron Ghory over on his blog and it was based on a "group -word game for children to teach them about division." While there's a number of -different ways to word this problem, here's the wording we're going to be working -with: - -> Write a program that prints the numbers 1 to 100. However, for multiples of -> three, print "Fizz" instead of the number. Meanwhile, for multiples of five, -> print "Buzz" instead of the number. For numbers which are multiples of both, -> print "FizzBuzz." - -This means there are a few things we need to keep in mind or consider: - -* The minimum value of 1. -* The maximum value of 100. -* Determine which order to check for multiples to avoid missing edge cases. -* Write the output to the console. - -Where to Start? - -Well, this is where it varies for everyone. Depending on how you tend to work -as a developer, your entry point will vary. Personally, I'll be starting by -creating the for loop that will iterate through all the numbers we need to analyze. -This starts us off with something like the following for PowerShell: - -```powershell -for ($x = 1; $x -le 100; $x++) { - Write-Output $x -} -``` - -This will get us a starting point of outputting every number from 1 to 100. Now -we should start putting in some if statements to determine if $x is a multiple -of 3, 5, or both. As is the case with most modern programming languages, PowerShell -has a modulus operator that will return the remainder of the division between two -numbers. - -For example, doing `Write-Output (25 % 5)` would output `0`, since 25 divided by 5 -has no remainder. This also happens to mean the first value is a multiple of -the second, which we can use to determine the multiples of `$x`. When I first -wrote this script, my solution looked like so: - -```powershell -for($x = 1; $x -le 100; $x++) { - $Threes = $x%3 - $Fives = $x%5 - if (($Threes -eq 0) -and ($Fives -eq 0)) { - Write-Output "FizzBuzz" - } else if ($Threes -eq 0) { - Write-Output "Fizz" - } else if ($Fives -eq 0) { - Write-Output "Buzz" - } else { - Write-Output $x - } -} -``` - -### Cleaning Up Our First Draft - -While this works, it's a bit clunky and doesn't allow for us to easily modify it -in the future if we want to add cases other than being a multiple of 3 or 5. I -hadn't quite realized this until I went looking for more information on this -problem and found a video by Tom Scott. He pointed out that you could easily -account for future adjustments by combining the output as a single variable for -each number. - -While he used JavaScript, the solution should be easily understandable and looks -like so: - -```javascript -for (var i = 1; i <= 100; i++) { - var output = "" - if (i % 3 === 0) output += "Fizz" - if (i % 5 === 0) output += "Buzz" - if (output === "") output = i - console.log(output) -} -``` - -As you can see, he creates the output variable for each iteration of `$x` and -depending on the multiples, adds or replaces values to that variable. Then, in -the end, he outputs it to the console using console.log. - -Translating this to PowerShell, we get something like so: - -```powershell -for ($x = 1; $x -le 100; $x++) { - $Output = "" - if ($x%3 -eq 0) { $Output += "Fizz" } - if ($x%5 -eq 0) { $Output += "Buzz" } - if ($Output -eq "") { $Output = $x } - Write-Output $Output -} -``` - -At this point, we have a working solution to the Fizz Buzz problem written in -PowerShell. - -### Finally, A Script! - -Now, since this is PowerShell, it's no fun just having a for loop that we need -to copy paste. No, we need a script! 😈 - -I created a file simply titled FizzBuzz.ps1` and got to work by adding the standard -goodies at the top of a PowerShell script: - -```powershell -[CmdletBinding()] -param () -``` - -Since I was initially writing this script for the sample programs repository I -contribute to, I knew I wanted to support more than going from 1 to 100. Instead, -I wanted users to be able to provide a minimum and maximum parameter that would -let them modify the output. This simply means adding two parameters to the `param()` -field like so: - -```powershell -param ( - [Parameter(Mandatory = $false, Position = 0)] - [int]$Min = 1, - [Parameter(Mandatory = $false, Position = 1)] - [int]$Max = 100 -) -``` - -The Mandatory and Position attributes tell PowerShell that the parameters have -default values and that they aren't mandatory, and the position attribute makes -it possible to do something like .\FizzBuzz.ps1 0 75 to adjust the min and max -without having to specify the parameter names. Then, with some minor changes to -the for loop, we have our finished result! - -```powershell -<# -.SYNOPSIS - A simple script that solves the standard FizzBuzz interview problem. -.DESCRIPTION - A simple script that solves the FizzBuzz interview problem to illustrate flow -control within a PowerShell script. -.PARAMETER Min - The minimium value to start counting at (inclusive). Defaults to 1. -.PARAMETER Max - The maximum value to count to (inclusive). Defaults to 100. -.EXAMPLE - .\FizzBuzz.ps1 -1 -2 -Fizz -4 -Buzz -[[[Fizz][0]][0]][0] -... -.EXAMPLE - .\FizzBuzz.ps1 -Min 10 -Max 75 -Buzz -11 -Fizz -13 -14 -FizzBuzz -16 -... -.NOTES - For reference, here's a copy of the FizzBuzz problem that this script solves, -the only difference between the requested solution and this script is the script -will let you determine the minimum and maximum values if you desire: -"Write a program that prints the numbers 1 to 100. However, for multiples of -three, print "Fizz" instead of the number. Meanwhile, for multiples of five, -print "Buzz" instead of the number. For numbers which are multiples of both, -print "FizzBuzz" -#> -[CmdletBinding()] -param ( - [Parameter(Mandatory = $false, Position = 0)] - [int]$Min = 1, - [Parameter(Mandatory = $false, Position = 1)] - [int]$Max = 100 -) -for ($X = $Min; $X -le $Max; $X++) { - $Output = "" - if ($X % 3 -eq 0) { $Output += "Fizz" } - if ($X % 5 -eq 0) { $Output += "Buzz" } - if ($Output -eq "") { $Output = $X } - Write-Output $Output -} -``` - - -## How to Run the Solution - -To run the Fizz Buzz script, launch a PowerShell console, grab a copy of the -Fizz Buzz script from the repository (or copy/paste the code from above 😉), -and then execute it. - -NOTE: If you have a secure Execution Policy, you'll have to set it to unrestricted -before executing this script. - -```console -$Url = "https://raw.githubusercontent.com/TheRenegadeCoder/sample-programs/main/archive/p/powershell/FizzBuzz.ps1" -$CurrPath = (Get-Location).Path -$FilePath = "$CurrPath\FizzBuzz.ps1" -$WebClient = New-Object System.Net.WebClient -$WebClient.DownloadFile($Url, $FilePath) -# Only use option 2 if you're unable to execute the script due to an ExecutionPolicy restriction. -# Afterward, reconfigure your policy to something more secure, such as options 2 or 3. -# -# Option 1: -# Set-ExecutionPolicy Unrestricted -# -# Option 2: -# Set-ExecutionPolicy AllSigned -# -# Option 3: -# Set-ExecutionPolicy RemoteSigned -.\FizzBuzz.ps1 -# Output: -# 1 -# 2 -# Fizz -# 4 -# Buzz -# Fizz -# 7 -# 8 -# Fizz -# Buzz -# 11 -# Fizz -``` diff --git a/docs/projects/fizz-buzz/prolog/index.md b/docs/projects/fizz-buzz/prolog/index.md deleted file mode 100644 index 61ef773582..0000000000 --- a/docs/projects/fizz-buzz/prolog/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- sabrinahuwang -date: 2023-06-10 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-06-10 -layout: default -tags: -- fizz-buzz -- prolog -title: Fizz Buzz in Prolog -title1: Fizz Buzz -title2: in Prolog ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Prolog](/languages/prolog) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```prolog -% Portions of this solution were derived through the assistance of ChatGPT. -:- initialization(main). - -fizzbuzz(N) :- - fizzbuzz_helper(1, N). - -fizzbuzz_helper(X, N) :- - X > N, !. -fizzbuzz_helper(X, N) :- - (X mod 15 =:= 0 -> - write('FizzBuzz'), nl - ; X mod 3 =:= 0 -> - write('Fizz'), nl - ; X mod 5 =:= 0 -> - write('Buzz'), nl - ; - write(X), nl - ), - X1 is X + 1, - fizzbuzz_helper(X1, N). - -main() :- - fizzbuzz(100), - halt. -``` - -{% endraw %} - -Fizz Buzz in [Prolog](/languages/prolog) was written by: - -- sabrinahuwang - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/pyret/index.md b/docs/projects/fizz-buzz/pyret/index.md deleted file mode 100644 index 24611ad759..0000000000 --- a/docs/projects/fizz-buzz/pyret/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2023-10-15 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-10-15 -layout: default -tags: -- fizz-buzz -- pyret -title: Fizz Buzz in Pyret -title1: Fizz Buzz -title2: in Pyret ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Pyret](/languages/pyret) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pyret -fun fizzbuzz(n :: Number): - when n > 0 block: - fizzbuzz(n - 1) - var result = "" - when num-modulo(n, 3) == 0: - result := string-append(result, "Fizz") - end - when num-modulo(n, 5) == 0: - result := string-append(result, "Buzz") - end - when string-equal(result, ""): - result := tostring(n) - end - print(string-append(result, "\n")) - end -end - -fizzbuzz(100) - -``` - -{% endraw %} - -Fizz Buzz in [Pyret](/languages/pyret) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/python/index.md b/docs/projects/fizz-buzz/python/index.md deleted file mode 100644 index bf0ae49476..0000000000 --- a/docs/projects/fizz-buzz/python/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- xPolar -date: 2018-12-15 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-05-15 -layout: default -tags: -- fizz-buzz -- python -title: Fizz Buzz in Python -title1: Fizz Buzz -title2: in Python ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -for n in range(1, 101): - if n % 3 == 0: - print("FizzBuzz" if n % 5 == 0 else "Fizz") - continue - print("Buzz" if n % 5 == 0 else n) - -``` - -{% endraw %} - -Fizz Buzz in [Python](/languages/python) was written by: - -- xPolar - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Before we dig into the code too much, let's take a look at the rules: - -If a number is divisible by 3, print the word `'Fizz'` instead of the number. -If the number is divisible by 5, print the word `'Buzz'` instead of the number. -Finally, if the number is divisible by both 3 and 5, print `'FizzBuzz'` instead of -the number. Otherwise, just print the number. - -You can test for divisibility using the modulo operator. The modulo operator -divides two numbers and yields the remainder, so i modulo j is 0 if i is -divisible by j. In Python, this is written as i % j. Then, it's a simple matter -of checking whether i % 3 == 0 or i % 5 == 0. - -### Code Style - -You'll notice first how everything is properly indented. This is not just good -code style, Python actually enforces it. There's no need to declare variables -as Python is what's called a weakly typed language. That means it can figure out -what type a variable should be on the fly. - -### The Loop - -In the very first line, we'll notice a loop: - -```python -for n in range(1, 101): -``` - -Here, we loop through all the numbers from 1 to 100. - -### Control Flow - -From there, we set the variable line to an empty string and begin our testing: - -```python -if n % 3 == 0: - print("FizzBuzz" if n % 5 == 0 else "Fizz") - continue -print("Buzz" if n % 5 == 0 else n) -``` - -If the number is divisible by 3, as explained above, we print the word "Fizz" if the -number is also not divisible by 5; otherwise, we print the word "FizzBuzz". We -skip the rest of the loop with the `continue` statement. - -If it's divisible by 5, we print the word "Buzz"; otherwise, we print the number -(`n`). - - -## How to Run the Solution - -To run the Fizz Buzz in Python program, grab a copy of the Python file from GitHub. -After that, get the latest version of Python. Now, all you have to do is run the -following from the command line: - -```console -python fizz-buzz.py -``` - -Alternatively, you can always copy the source code into an online Python -interpreter and hit run. diff --git a/docs/projects/fizz-buzz/r/index.md b/docs/projects/fizz-buzz/r/index.md deleted file mode 100644 index 670f8b8e06..0000000000 --- a/docs/projects/fizz-buzz/r/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Gabi Herman -- Jeremy Grifski -date: 2019-10-24 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2020-10-18 -layout: default -tags: -- fizz-buzz -- r -title: Fizz Buzz in R -title1: Fizz Buzz -title2: in R ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -fizz_buzz <- function(){ - for (x in 1:100){ - out<-'' - mod3<- x%%3==0 - mod5 <- x%%5==0 - if (!mod3 && !mod5){ - out=x - } - if (mod3){ - out='Fizz' - } - if (mod5){ - out=paste0(out,'Buzz') - } - cat(out, "\n") - } -} - -fizz_buzz() - -``` - -{% endraw %} - -Fizz Buzz in [R](/languages/r) was written by: - -- Gabi Herman -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/racket/index.md b/docs/projects/fizz-buzz/racket/index.md deleted file mode 100644 index 1cfea9a13e..0000000000 --- a/docs/projects/fizz-buzz/racket/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- RubinMathias -date: 2020-10-02 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2020-10-02 -layout: default -tags: -- fizz-buzz -- racket -title: Fizz Buzz in Racket -title1: Fizz Buzz -title2: in Racket ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Racket](/languages/racket) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```racket -;fizzbuzz in racket -;Author: Emblazion - -#lang racket -(for ([i (in-range 1 101)]) - (cond - [(and - (equal? 0 (modulo i 3)) - (equal? 0 (modulo i 5))) - (printf "FizzBuzz\n")] - [(equal? 0 (modulo i 3)) (printf "Fizz\n")] - [(equal? 0 (modulo i 5)) (printf "Buzz\n")] - [else (printf "~a\n" i)])) - -``` - -{% endraw %} - -Fizz Buzz in [Racket](/languages/racket) was written by: - -- RubinMathias - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/raku/index.md b/docs/projects/fizz-buzz/raku/index.md deleted file mode 100644 index 648f304b21..0000000000 --- a/docs/projects/fizz-buzz/raku/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- xavierb117 -date: 2025-02-17 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-02-17 -layout: default -tags: -- fizz-buzz -- raku -title: Fizz Buzz in Raku -title1: Fizz Buzz -title2: in Raku ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Raku](/languages/raku) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```raku -for 1..100 -> $i { - if $i % 3 == 0 && $i % 5 == 0 { - say "FizzBuzz" - } - elsif $i % 5 == 0 { - say "Buzz" - } - elsif $i % 3 == 0 { - say "Fizz" - } - else { - say $i - } -} -``` - -{% endraw %} - -Fizz Buzz in [Raku](/languages/raku) was written by: - -- xavierb117 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/red/index.md b/docs/projects/fizz-buzz/red/index.md deleted file mode 100644 index 3c30bf6350..0000000000 --- a/docs/projects/fizz-buzz/red/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-17 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-10-17 -layout: default -tags: -- fizz-buzz -- red -title: Fizz Buzz in Red -title1: Fizz Buzz -title2: in Red ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Red](/languages/red) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```red -; Source: https://rosettacode.org/wiki/FizzBuzz#Red -Red [Title: "FizzBuzz"] - -repeat i 100 [ - print case [ - i % 15 = 0 ["FizzBuzz"] - i % 5 = 0 ["Buzz"] - i % 3 = 0 ["Fizz"] - true [i] - ] -] - -``` - -{% endraw %} - -Fizz Buzz in [Red](/languages/red) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/rexx/index.md b/docs/projects/fizz-buzz/rexx/index.md deleted file mode 100644 index 110ff434a1..0000000000 --- a/docs/projects/fizz-buzz/rexx/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-11-22 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-11-22 -layout: default -tags: -- fizz-buzz -- rexx -title: Fizz Buzz in Rexx -title1: Fizz Buzz -title2: in Rexx ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Rexx](/languages/rexx) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rexx -do i = 1 to 100 - if i // 15 == 0 then - say "FizzBuzz" - else if i // 3 == 0 then - say "Fizz" - else if i // 5 == 0 then - say "Buzz" - else - say i -end - -``` - -{% endraw %} - -Fizz Buzz in [Rexx](/languages/rexx) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/ruby/index.md b/docs/projects/fizz-buzz/ruby/index.md deleted file mode 100644 index a0f8f34b22..0000000000 --- a/docs/projects/fizz-buzz/ruby/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2018-08-12 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-05-07 -layout: default -tags: -- fizz-buzz -- ruby -title: Fizz Buzz in Ruby -title1: Fizz Buzz -title2: in Ruby ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def fizzbuzz(n) - result = +"" - - result << "Fizz" if n % 3 == 0 - result << "Buzz" if n % 5 == 0 - - puts(result.empty? ? n : result) -end - -(1..100).each { fizzbuzz(it) } - -``` - -{% endraw %} - -Fizz Buzz in [Ruby](/languages/ruby) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/rust/index.md b/docs/projects/fizz-buzz/rust/index.md deleted file mode 100644 index 8707d1aa25..0000000000 --- a/docs/projects/fizz-buzz/rust/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- Bodo Schönfeld -- Jeremy Grifski -- Noah Nichols -- Vincent Caron -date: 2018-09-24 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2022-04-28 -layout: default -tags: -- fizz-buzz -- rust -title: Fizz Buzz in Rust -title1: Fizz Buzz -title2: in Rust ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -fn main() { - for number in 1..101 { - if number % 3 == 0 && number % 5 == 0 { - println!("FizzBuzz"); - } else if number % 3 == 0 { - println!("Fizz"); - } else if number % 5 == 0 { - println!("Buzz"); - } else { - println!("{}", number); - } - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Rust](/languages/rust) was written by: - -- Noah Nichols -- Vincent Caron - -This article was written by: - -- Bodo Schönfeld -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Before we dig into the code too much, let's take a look at the rules: - -* If a number is divisible by 3, print the word 'Fizz' instead of the number. -* If the number is divisible by 5, print the word 'Buzz' instead of the number. -* Finally, if the number is divisible by both 3 and 5, print 'FizzBuzz' instead of the number. -* Otherwise, just print the number. - -You can test for divisibility using the modulo operator `%`. The modulo operator divides two numbers and yields the remainder, so `i` modulo `j` is `0` if `i` is divisible by `j`. In Rust, this is written as `i % j`. Then, it's a simple matter of checking whether `i % 3 == 0` or `i % 5 == 0`. - -### The Loop - -In the very first line, we'll notice a `for`-loop: - -```rust -for number in 1..101 -``` - -Here, we loop through all the numbers from 1 to 100. - -### Control Flow - -From there, we begin our testing using an if statement: - -```rust -if number % 3 == 0 && number % 5 == 0 { - println!("FizzBuzz"); -} else if number % 3 == 0 { - println!("Fizz"); -} else if number % 5 == 0 { - println!("Buzz"); -} else { - println!("{}", number); -} -``` - -* If the number is divisible by 3 and 5, we print the word 'FizzBuzz'. -* If the number is divisible by 3, we print the word 'Fizz'. -* If the number is divisible by 5, we print the word 'Buzz'. -* In all other cases, we print the number itself. - - -## How to Run the Solution - -To run FizzBuzz in Rust, install the latest version of Rust. After that, create a project structure using `cargo`: - -```console -cargo new fizz-buzz -``` - -Copy the code from Github into 'main.rs'. Compile and run the code from the command line using - -```console -cargo run main.rs -``` - -This will create a new 'target' directory containing the executable binary file. diff --git a/docs/projects/fizz-buzz/scala/index.md b/docs/projects/fizz-buzz/scala/index.md deleted file mode 100644 index 928bb5e31e..0000000000 --- a/docs/projects/fizz-buzz/scala/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2026-04-11 -layout: default -tags: -- fizz-buzz -- scala -title: Fizz Buzz in Scala -title1: Fizz Buzz -title2: in Scala ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -object FizzBuzz: - def main(args: Array[String]): Unit = - (1 to 100).map { i => - (i % 3, i % 5) match - case (0, 0) => "FizzBuzz" - case (0, _) => "Fizz" - case (_, 0) => "Buzz" - case _ => i.toString - } foreach println -``` - -{% endraw %} - -Fizz Buzz in [Scala](/languages/scala) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/smalltalk/index.md b/docs/projects/fizz-buzz/smalltalk/index.md deleted file mode 100644 index 17464ff0fb..0000000000 --- a/docs/projects/fizz-buzz/smalltalk/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Augy Markham -date: 2024-11-16 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-11-16 -layout: default -tags: -- fizz-buzz -- smalltalk -title: Fizz Buzz in Smalltalk -title1: Fizz Buzz in -title2: Smalltalk ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Smalltalk](/languages/smalltalk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```smalltalk -"Loop 1 to 100" -1 to: 100 do: [ :i | - - "If the number isn't divisible by 3 or 5, show the number" - i \\ 3 = 0 ifFalse: [i \\ 5 = 0 ifFalse: [Transcript show: (i printString); cr]]. - - "If the number is divisible by 3 AND 5, show 'FizzBuzz'" - i \\ 3 = 0 ifTrue: [i \\ 5 = 0 ifTrue: [Transcript show: 'FizzBuzz' ; cr]]. - - "If the number is only divisible by 3, show 'Fizz'" - i \\ 3 = 0 ifTrue: [i \\ 5 = 0 ifFalse: [Transcript show: 'Fizz' ; cr]]. - - "If the number is only divisible by 5, show 'Buzz" - i \\ 5 = 0 ifTrue: [i \\ 3 = 0 ifFalse: [Transcript show: 'Buzz' ; cr]]. - ]. -``` - -{% endraw %} - -Fizz Buzz in [Smalltalk](/languages/smalltalk) was written by: - -- Augy Markham - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/solisp/index.md b/docs/projects/fizz-buzz/solisp/index.md deleted file mode 100644 index f9a88de9bf..0000000000 --- a/docs/projects/fizz-buzz/solisp/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Stuart Irwin -date: 2020-02-25 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2020-03-23 -layout: default -tags: -- fizz-buzz -- solisp -title: Fizz Buzz in Solisp -title1: Fizz Buzz -title2: in Solisp ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Solisp](/languages/solisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```solisp -(Join (Map num (Seq 1 100) - (Switch - {(== (% num 3) (% num 5) 0) "FizzBuzz"} - {(== (% num 3) 0) "Fizz"} - {(== (% num 5) 0) "Buzz"} - {true num} - ) -) "\n") -``` - -{% endraw %} - -Fizz Buzz in [Solisp](/languages/solisp) was written by: - -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/swift/index.md b/docs/projects/fizz-buzz/swift/index.md deleted file mode 100644 index 1f2c6f747d..0000000000 --- a/docs/projects/fizz-buzz/swift/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Marty Hernandez Avedon -- shubhragupta-code -date: 2018-10-03 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2022-04-28 -layout: default -tags: -- fizz-buzz -- swift -title: Fizz Buzz in Swift -title1: Fizz Buzz -title2: in Swift ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -func fizzBuzz(start: Int = 1, end: Int = 100) -> Void { - let range = start...end - - for number in range { - guard number % 5 == 0 || number % 3 == 0 else { - print(number) - continue - } - - var fizzAndOrBuzz = "" - - if number % 3 == 0 { - fizzAndOrBuzz = "Fizz" - } - - if number % 5 == 0 { - fizzAndOrBuzz += "Buzz" - } - - print(fizzAndOrBuzz) - } -} - -fizzBuzz(); -``` - -{% endraw %} - -Fizz Buzz in [Swift](/languages/swift) was written by: - -- Marty Hernandez Avedon - -This article was written by: - -- Jeremy Grifski -- Marty Hernandez Avedon -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -### The Function Signature - -Here we see a rather long and punctuation-filled function signature. [Swift functions](https://docs.swift.org/swift-book/LanguageGuide/Functions.html) use named parameters, and the type of each parameter must be noted. This is a safety feature, ensuring, for example, that we don't pass in a float when we need an integer. So, in line 1, we see `start: Int` and `end: Int`, meaning that our function takes in two integer values, named `start` and `end`. - -### Default Values - -You might think that the equal signs next to each parameter look like assignments, and you would be (sort of) correct. When writing a Swift function's signature, the equals sign can be used to define a default value. If later, the user chooses to call the function without passing in any arguments, the compiler will be smart enough to look at the defaults, and run the function using those values. Swift functions don't *need* to have default values, but they can be nice to have. They can [save you some headaches when building apps](https://www.natashatherobot.com/swift-default-parameter-values/). - -### The Return Type - -The little arrow after the argument names indicates the return type, which in this case is `Void`. `Void` just means our function doesn't return anything. Our function is only printing out words and numbers, so it isn't returning any values. - -[In Swift, if you function doesn't return anything, you can leave off the return type completely, or use the empty tuple `()` to indicate `Void`](https://developer.apple.com/documentation/swift/void). However, I think it's best to just be explicit about what you're returning and write it out. - -### Ranges - -On line 2, we use the keyword `let` to define a new range of numbers: - -```swift -let range = start...end -``` - -In Swift, [values defined with `let` are immutable](https://stackoverflow.com/a/24048417), and we are encouraged to use them liberally. This keeps us from accidentally changing something when we don't want or need to. - -[Ranges](https://developer.apple.com/documentation/swift/range) are their own type in Swift, and allow us to go over a series of numbers without setting up a list or [array](https://developer.apple.com/documentation/swift/array). Although we could have explicitly named the type here, the Swift compiler is able to [infer](http://www.aidanf.net/learn-swift/types_and_type_inference) that we want a range because we've given it two integer values, separated by an ellipsis. - -We create a [for-loop](https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html) to transverse the range on line 4. [Earlier versions of Swift allowed for C-style loops](https://www.natashatherobot.com/swift-alternatives-to-c-style-for-loops/), but they've since been replaced with this less wordy syntax. - -### Conditionals - -Line 5 presents a [guard statement](https://medium.com/@chris_dus/the-guard-statement-in-swift-fdad41b08798), a kind of conditional that only fires if a condition has *not* been met. Guard statements are frequently used in Swift to handle edge cases that might otherwise cause errors, and to avoid nested conditionals. Here, we use a guard statement to swiftly print any numbers that are not divisible by 3 or 5. Then, we continue on to the next number. - -If a number *is* indeed divisible by 3 or 5, we set up the variable `fizzAndOrBuzz`. This value is defined with [the keyword `var`](https://www.hackingwithswift.com/example-code/language/whats-the-difference-between-let-and-var), which allows us to change it over the course of our function. - -We use two if-statements to test for Fizziness and/or Buzziness. Both statements use [the remainder operator](https://www.quora.com/What-does-the-percent-symbol-mean-in-Swift-language), `%`, which gives us the remainder from any division between one integer and another. If one number is evenly divisible by another, the remainder is always 0. - - In other languages, `%` is used for the modulo operator. [Modulo is similar to remainder when dealing with positive integers, but it gives different results when the integers are negative](https://rob.conery.io/2018/08/21/mod-and-remainder-are-not-the-same/). In Swift, the absolute values of the integers are used, so `3 % 15` gives the same result as `3 % -15`. - -### Wrapping Up - -Line 14 [uses `+=`](https://riptutorial.com/swift/example/1416/concatenate-strings) to add "Buzz" on to the end of our variable, so that if our number is evenly divisible by both 3 and 5, we get the word "FizzBuzz", and not just "Fizz" or just "Buzz". - -Finally, we print whatever is inside `fizzAndOrBuzz` at the end of our loop. - -We exit the loop, we end the function, and we call `fizzBuzz` at the very bottom. Since we've defined some default values, the script knows to go over the numbers 1 through 100 without having to be told to. We could also pass in arguments for the start and end of our range later, if we want. - - -## How to Run the Solution - -Swift is often run via [XCode](https://developer.apple.com/xcode/), Apple's IDE, or by installing [Swift on Linux](https://medium.com/@agavatar/open-source-swift-on-ubuntu-linux-cd00e697dff0). However, XCode in particular is a heavy download, so unless you already have it installed, or are seriously contemplating iOS development, you probably should use [this handy online Swift compiler](https://www.onlinegdb.com/online_swift_compiler). - -Please be aware that Swift updates very frequently, and many online compilers use earlier versions of the language, which may present with incompatibilities and errors when trying to run this code. This code was written in [Swift 4](https://docs.swift.org/swift-book/GuidedTour/Compatibility.html). diff --git a/docs/projects/fizz-buzz/tcl/index.md b/docs/projects/fizz-buzz/tcl/index.md deleted file mode 100644 index 4037fc9910..0000000000 --- a/docs/projects/fizz-buzz/tcl/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-09 -layout: default -tags: -- fizz-buzz -- tcl -title: Fizz Buzz in Tcl -title1: Fizz Buzz -title2: in Tcl ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -# This approach is exclusively to show the capabilities and flexibility of Tcl. -# It doesn't deserve being this overengineered in the normal case. :P - -proc fizzbuzz {rules {limit 100}} { - namespace eval ::fizzbuzz { - namespace export * - namespace ensemble create - } - - foreach {div word} $rules { - proc ::fizzbuzz::$word {n} [format { - expr {($n %% %d) == 0 ? "%s" : ""} - } $div $word] - } - - for {set n 1} {$n <= $limit} {incr n} { - set s "" - foreach {div word} $rules { - append s [::fizzbuzz::$word $n] - } - puts [expr {$s eq "" ? $n : $s}] - } -} - -fizzbuzz {3 Fizz 5 Buzz} - -``` - -{% endraw %} - -Fizz Buzz in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/tex/index.md b/docs/projects/fizz-buzz/tex/index.md deleted file mode 100644 index c7365c0dcc..0000000000 --- a/docs/projects/fizz-buzz/tex/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- rzuckerm -date: 2018-09-04 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-28 -layout: default -tags: -- fizz-buzz -- tex -title: Fizz Buzz in TeX -title1: Fizz Buzz -title2: in TeX ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [TeX](/languages/tex) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tex -% Source: https://rosettacode.org/wiki/String_append#Plain_TeX -\def\addtomacro#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}} - -\newwrite\out -\immediate\openout\out=fizz-buzz.txt - -\countdef\counter=1 -\countdef\threecounter=2 -\countdef\fivecounter=3 -\counter=1 -\threecounter=1 -\fivecounter=1 - -\loop - \def\printnum{1} - \def\result{} - \noindent - \ifnum \threecounter>2 - \addtomacro\result{Fizz} - \threecounter=0 - \def\printnum{0} - \fi - \ifnum \fivecounter>4 - \addtomacro\result{Buzz} - \fivecounter=0 - \def\printnum{0} - \fi - \ifnum\printnum=1 - % print the counter variable - \addtomacro\result{\the\counter} - \fi - \immediate\write\out{\result} - \advance \counter 1 - \advance \threecounter 1 - \advance \fivecounter 1 -\ifnum \counter<101 -\repeat - -\end - -``` - -{% endraw %} - -Fizz Buzz in [TeX](/languages/tex) was written by: - -- Christoph Böhmwalder -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/ti-basic/index.md b/docs/projects/fizz-buzz/ti-basic/index.md deleted file mode 100644 index 63d16266ee..0000000000 --- a/docs/projects/fizz-buzz/ti-basic/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-28 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-10-28 -layout: default -tags: -- fizz-buzz -- ti-basic -title: Fizz Buzz in TI-BASIC -title1: Fizz Buzz -title2: in TI-BASIC ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -For(N,1,100) - If remainder(N,15)=0 Then Disp("FizzBuzz") - Else - If remainder(N,3)=0 Then Disp("Fizz") - Else - If remainder(N,5)=0 Then Disp("Buzz") - Else Disp(N) - End - End - End -End - -``` - -{% endraw %} - -Fizz Buzz in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/typescript/index.md b/docs/projects/fizz-buzz/typescript/index.md deleted file mode 100644 index 81c32ef9a3..0000000000 --- a/docs/projects/fizz-buzz/typescript/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Nadir Fayazov -- rzuckerm -date: 2018-10-11 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-05-15 -layout: default -tags: -- fizz-buzz -- typescript -title: Fizz Buzz in TypeScript -title1: Fizz Buzz in -title2: TypeScript ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -let line: string; - -for (let i = 1; i <= 100; i++) { - if (i % 3 == 0 && i % 5 == 0) { - line = "FizzBuzz"; - } else if (i % 3 == 0) { - line = "Fizz"; - } else if (i % 5 == 0) { - line = "Buzz"; - } else { - line = String(i); - } - console.log(line); -} - -``` - -{% endraw %} - -Fizz Buzz in [TypeScript](/languages/typescript) was written by: - -- Nadir Fayazov -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/unicat/index.md b/docs/projects/fizz-buzz/unicat/index.md deleted file mode 100644 index 1bd26b9f73..0000000000 --- a/docs/projects/fizz-buzz/unicat/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-28 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-08-28 -layout: default -tags: -- fizz-buzz -- unicat -title: Fizz Buzz in Unicat -title1: Fizz Buzz -title2: in Unicat ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Unicat](/languages/unicat) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```unicat -# This program implements the fizz-buzz algorithm. It tests the math -# instructions - -# Set up letters -0o00 😻😹😸🙀🙀😹😸😾🙀🙀 Memory 0 = 0o106 (70 = 'F') -0o01 😻😹😹🙀🙀😹😽😹🙀🙀 Memory 1 = 0o151 (105 = 'i') -0o02 😻😹😺🙀🙀😹😿😺🙀🙀 Memory 2 = 0o172 (122 = 'z') -0o03 😻😹😻🙀🙀😹😸😺🙀🙀 Memory 3 = 0o102 (66 = 'B') -0o04 😻😹😼🙀🙀😹😾😽🙀🙀 Memory 4 = 0o165 (117 = 'u') -0o05 😻😹😽🙀🙀😹😺🙀🙀 Memory 5 = 0o12 (10 = '\n') - -# Set up constants -0o06 😻😹😾🙀🙀😸🙀🙀 Memory 6 = 0 (n) -0o07 😻😹😿🙀🙀😹🙀🙀 Memory 7 = 1 -0o10 😻😹😹😸🙀🙀😻🙀🙀 Memory 8 (0o10) = 3 -0o11 😻😹😹😹🙀🙀😽🙀🙀 Memory 9 (0o11) = 5 - -# Loop start: Increment n. If n > 100, exit -0o12 😿🙀😸😾🙀🙀😿🙀🙀 Memory 6 += Memory 7 (increment n) -0o13 😻😹😹😺🙀🙀😹😼😼🙀😿 Memory 10 (0o12) = -0o144 (-100) -0o14 😿🙀😸😹😺🙀🙀😾🙀🙀 Memory 10 (0o12) += Memory 6 (n - 100) -0o15 😽😿😹😺🙀🙀😽😼🙀🙀 If Memory 10 (0o12) > 0, jump to 0o55 (0o54 + 1) (if n > 100) - -# Indicate no output -0o16 😻😹😹😻🙀🙀😸🙀🙀 Memory 11 (0o13) = 0 - -# If n mod 3 is 0, output "Fizz" and indicate output -0o17 😻😹😹😺🙀🙀😸🙀🙀 Memory 10 (0o12) = 0 -0o20 😿🙀😸😹😺🙀🙀😾🙀🙀 Memory 10 (0o12) += Memory 6 (n) -0o21 😻😹😹😼🙀🙀😸🙀🙀 Memory 12 (0o14) = 0 -0o22 😿🙀😸😹😼🙀🙀😾🙀🙀 Memory 12 (0o14) += Memory 6 (n) -0o23 😿🙀😿😹😼🙀🙀😹😸🙀🙀 Memory 12 (0o14) /= Memory 8 (0o10) (3) -0o24 😿🙀🙀😹😼🙀🙀😹😸🙀🙀 Memory 12 (0o14) *= Memory 8 (0o10) (3) -0o25 😿🙀😺😹😺🙀🙀😹😼🙀🙀 Memory 10 (0o12) -= Memory 12 (0o14) (n - floor(n / 3) * 3) -0o26 😽😿😹😺🙀🙀😻😻🙀🙀 If Memory 10 (0o12) > 0, jump to 0o34 (0o33 + 1) -0o27 😽😼😸🙀🙀 Output Memory 0 ('F') -0o30 😽😼😹🙀🙀 Output Memory 1 ('i') -0o31 😽😼😺🙀🙀 Output Memory 2 ('z') -0o32 😽😼😺🙀🙀 Output Memory 2 ('z') -0o33 😻😹😹😻🙀🙀😹🙀🙀 Memory 11 (0o13) = 1 - -# If n mod 5 is 0, output "Buzz" and indicate output -0o34 😻😹😹😺🙀🙀😸🙀🙀 Memory 10 (0o12) = 0 -0o35 😿🙀😸😹😺🙀🙀😾🙀🙀 Memory 10 (0o12) += Memory 6 (n) -0o36 😻😹😹😼🙀🙀😸🙀🙀 Memory 12 (0o14) = 0 -0o37 😿🙀😸😹😼🙀🙀😾🙀🙀 Memory 12 (0o14) += Memory 6 (n) -0o40 😿🙀😿😹😼🙀🙀😹😹🙀🙀 Memory 12 (0o14) /= Memory 9 (0o11) (floor(n / 5)) -0o41 😿🙀🙀😹😼🙀🙀😹😹🙀🙀Memory 12 (0o14) *= Memory 9 (0o11) (floor(n / 5) * 5) -0o42 😿🙀😺😹😺🙀🙀😹😼🙀🙀 Memory 10 (0o12) -= Memory 12 (0o14) (n - floor(n / 5) * 5) -0o43 😽😿😹😺🙀🙀😽😸🙀🙀 If Memory 10 (0o12) > 0, jump to 0o51 (0o50 + 1) -0o44 😽😼😻🙀🙀 Output Memory 3 ('B') -0o45 😽😼😼🙀🙀 Output Memory 4 ('u') -0o46 😽😼😺🙀🙀 Output Memory 2 ('z') -0o47 😽😼😺🙀🙀 Output Memory 2 ('z') -0o50 😻😹😹😻🙀🙀😹🙀🙀 Memory 11 (0o13) = 1 - -# If no output, output n as value -0o51 😽😿😹😻🙀🙀😽😺🙀🙀 If Memory 11 (0o13) > 0, jump to 0o53 (0o52 + 1) -0o52 😼😼😾🙀🙀 Output Memory 6 (n) as value - -# Output newline -0o53 😽😼😽🙀🙀 Output Memory 5 ('\n') - -# Jump to Loop start -0o54 😻😹😹🙀😿😹😹🙀🙀 Jump to 0o12 (0o11 + 1) - -0o55 🙀🙀 Exit - -``` - -{% endraw %} - -Fizz Buzz in [Unicat](/languages/unicat) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/v/index.md b/docs/projects/fizz-buzz/v/index.md deleted file mode 100644 index 159ab3acea..0000000000 --- a/docs/projects/fizz-buzz/v/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Zia -date: 2024-12-15 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-12-15 -layout: default -tags: -- fizz-buzz -- v -title: Fizz Buzz in V -title1: Fizz Buzz -title2: in V ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [V](/languages/v) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```v -module main - -fn main() { - for i in 1..101 { - println(match true { - i % 15 == 0 { "FizzBuzz" } - i % 5 == 0 { "Buzz" } - i % 3 == 0 { "Fizz" } - else { i.str() } - }) - } -} - -``` - -{% endraw %} - -Fizz Buzz in [V](/languages/v) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/verve/index.md b/docs/projects/fizz-buzz/verve/index.md deleted file mode 100644 index c9179031f4..0000000000 --- a/docs/projects/fizz-buzz/verve/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-21 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-12-21 -layout: default -tags: -- fizz-buzz -- verve -title: Fizz Buzz in Verve -title1: Fizz Buzz -title2: in Verve ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Verve](/languages/verve) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```verve -fn fizz_buzz_line(n: Int) -> String { - match [n % 3, n % 5] { - case [0, 0]: "FizzBuzz" - case [0, _]: "Fizz" - case [_, 0]: "Buzz" - case _: to_string(n) - } -} - -fn fizz_buzz(start: Int, end: Int) { - if not(start > end) { - print(fizz_buzz_line(start)) - fizz_buzz(start + 1, end) - } -} - -fizz_buzz(1, 100) - -``` - -{% endraw %} - -Fizz Buzz in [Verve](/languages/verve) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/vimscript/index.md b/docs/projects/fizz-buzz/vimscript/index.md deleted file mode 100644 index 1f65306f39..0000000000 --- a/docs/projects/fizz-buzz/vimscript/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- rzuckerm -date: 2018-08-28 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-12-21 -layout: default -tags: -- fizz-buzz -- vimscript -title: Fizz Buzz in Vimscript -title1: Fizz Buzz in -title2: Vimscript ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Vimscript](/languages/vimscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```vimscript -func! FizzBuzz() - for l:i in range(1, 100) - if l:i % 15 == 0 - let l:str = 'FizzBuzz' - elseif l:i % 5 == 0 - let l:str = 'Buzz' - elseif l:i % 3 == 0 - let l:str = 'Fizz' - else - let l:str = l:i - endif - - echo l:str - endfor -endfunc - -func! Main() - call FizzBuzz() -endfunc - -``` - -{% endraw %} - -Fizz Buzz in [Vimscript](/languages/vimscript) was written by: - -- Christoph Böhmwalder -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/visual-basic/index.md b/docs/projects/fizz-buzz/visual-basic/index.md deleted file mode 100644 index 66c7332d73..0000000000 --- a/docs/projects/fizz-buzz/visual-basic/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- rzuckerm -- Thomas Braccia -date: 2020-10-01 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-05-16 -layout: default -tags: -- fizz-buzz -- visual-basic -title: Fizz Buzz in Visual Basic -title1: Fizz Buzz in -title2: Visual Basic ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Option Explicit On -Module FizzBuzz - Public Sub Main() - FizzBuzz() - End Sub - Sub FizzBuzz() - Dim i As Integer - For i = 1 To 100 - If i Mod 15 = 0 Then - System.Console.WriteLine("FizzBuzz") - ElseIf i Mod 5 = 0 Then - System.Console.WriteLine("Buzz") - ElseIf i Mod 3 = 0 Then - System.Console.WriteLine("Fizz") - Else - System.Console.WriteLine(i) - End If - Next - End Sub -End Module - -``` - -{% endraw %} - -Fizz Buzz in [Visual Basic](/languages/visual-basic) was written by: - -- rzuckerm -- Thomas Braccia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/whitespace/index.md b/docs/projects/fizz-buzz/whitespace/index.md deleted file mode 100644 index 2b170abadb..0000000000 --- a/docs/projects/fizz-buzz/whitespace/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-10-14 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2024-10-14 -layout: default -tags: -- fizz-buzz -- whitespace -title: Fizz Buzz in Whitespace -title1: Fizz Buzz in -title2: Whitespace ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Whitespace](/languages/whitespace) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```whitespace -S S S T L -L -S S S L -S S S T L -S S S T T S T S S T L -S S S T S S S T T S L -S S S T T L -L -S T T S L -S S S T T T S T S T L -S S S T S S S S T S L -S S S T S T L -L -S T T S L -L -T S T L -S L -S T L -S T L -S S T L -S S S T S T S L -T L -S S S S S T L -T S S S S L -S S S S T T S S T S T L -T S S T L -T T S L -L -L -L -L -S S T S L -S T S S T S S L -S L -T T S T T L -T S T T L -S L -L -S L -L -L -T L -L -S S T T L -T L -S S T L -S S S S S T T T T S T S L -T L -S S S S S T T T T S T S L -T L -S S S L -L -S S S S L -L -T L - -``` - -{% endraw %} - -Fizz Buzz in [Whitespace](/languages/whitespace) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/wren/index.md b/docs/projects/fizz-buzz/wren/index.md deleted file mode 100644 index b54a0504e8..0000000000 --- a/docs/projects/fizz-buzz/wren/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-19 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-19 -layout: default -tags: -- fizz-buzz -- wren -title: Fizz Buzz in Wren -title1: Fizz Buzz -title2: in Wren ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -for (i in (1..100)) { - if (i % 15 == 0) { - System.print("FizzBuzz") - } else if (i % 5 == 0) { - System.print("Buzz") - } else if (i % 3 == 0) { - System.print("Fizz") - } else { - System.print(i) - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/wu/index.md b/docs/projects/fizz-buzz/wu/index.md deleted file mode 100644 index 508c745854..0000000000 --- a/docs/projects/fizz-buzz/wu/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- jmakho01 -date: 2025-10-31 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-10-31 -layout: default -tags: -- fizz-buzz -- wu -title: Fizz Buzz in Wu -title1: Fizz Buzz -title2: in Wu ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Wu](/languages/wu) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wu -i: int = 1 -while i <= 100 { - o: str = "" - if i % 3 == 0 { - o ++= "Fizz" - } - if i % 5 == 0 { - o ++= "Buzz" - } - if i % 3 != 0 and i % 5 != 0 { - o ++= i - } - print(o) - i += 1 -} -``` - -{% endraw %} - -Fizz Buzz in [Wu](/languages/wu) was written by: - -- jmakho01 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/x86-64/index.md b/docs/projects/fizz-buzz/x86-64/index.md deleted file mode 100644 index 2afa2f066f..0000000000 --- a/docs/projects/fizz-buzz/x86-64/index.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -authors: -- alope107 -date: 2023-05-05 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2023-05-05 -layout: default -tags: -- fizz-buzz -- x86-64 -title: Fizz Buzz in x86-64 -title1: Fizz Buzz -title2: in x86-64 ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [x86-64](/languages/x86-64) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```x86-64 -section .data - fizz db "Fizz" - fizz_len equ $-fizz - buzz db "Buzz" - buzz_len equ $-buzz - newline db 10 - -section .bss - ; Used to hold the ascii digits for printing - ; Sufficient size to hold any positive 64 bit number - digits resb 21 - -section .text - global _start - -_start: - mov r12, 1 ; r12 holds current i - mov r13, 101 ; r13 holds loop end (exclusive) - - loop: - ; Break loop once target reached - cmp r12, r13 - je loop_end - - mov rax, r12 - call print_val - - ; Print a newline character - mov rax, 1 - mov rdi, 1 - mov rsi, newline - mov rdx, 1 - syscall - - inc r12 - jmp loop - - loop_end: - ; Exit and return 0 - mov rax, 60 - xor rdi, rdi - syscall - - -; Prints an int. Currently only works for positive values -; rax holds input number -print_num: - mov r8, 20 ; r8 holds the offset from the digits buffer. We start at the back - mov r9, 10 ; We will be repeatedly dividing by 10 - - div_loop: - ; Calculate ASCII value of last decimal digit of rax - xor rdx, rdx - div r9 - add rdx, '0' - - ; Fill ASCII values from the end of the buffer - mov byte [digits + r8], dl - dec r8 - cmp rax, 0 - jne div_loop - - ; Move r8 offest to start of string - inc r8 - - ; Print the string - mov rax, 1 - mov rdi, 1 - lea rsi, [digits + r8] - mov rdx, 21 - sub rdx, r8 - syscall - - ret - - -print_val: - push r12 - push r13 - - xor r12, r12 ; Flag as to whether fizz || buzz was printed - mov r13, rax ; Keep a copy of the input to re-use - - test_fizz: - ; Skip to next label if not divisible by 3 - xor rdx, rdx - mov r8, 3 - div r8 - cmp rdx, 0 - jne test_buzz - - ; Print Fizz - mov rax, 1 - mov rdi, 1 - mov rsi, fizz - mov rdx, fizz_len - syscall - - ; Mark that a wword was printed for this number - inc r12 - - test_buzz: - ; Restore the input value to rax - mov rax, r13 - - ; Skip to the next label if not divisible by 5 - xor rdx, rdx - mov r8, 5 - div r8 - cmp rdx, 0 - jne test_num - - ; Print Buzz - mov rax, 1 - mov rdi, 1 - mov rsi, buzz - mov rdx, buzz_len - syscall - - ; Mark that a wword was printed for this number - inc r12 - - test_num: - ; If fizz and/or buzz was already printed for this number, skip to cleanup - cmp r12, 0 - jne cleanup - - ; Restore the input to rax and print it - mov rax, r13 - call print_num - - cleanup: - pop r13 - pop r12 - ret -``` - -{% endraw %} - -Fizz Buzz in [x86-64](/languages/x86-64) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fizz-buzz/zig/index.md b/docs/projects/fizz-buzz/zig/index.md deleted file mode 100644 index fe3916b6ab..0000000000 --- a/docs/projects/fizz-buzz/zig/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-08 -featured-image: fizz-buzz-in-every-language.png -last-modified: 2025-01-08 -layout: default -tags: -- fizz-buzz -- zig -title: Fizz Buzz in Zig -title1: Fizz Buzz -title2: in Zig ---- - - - -Welcome to the [Fizz Buzz](/projects/fizz-buzz) in [Zig](/languages/zig) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```zig -const std = @import("std"); - -pub fn main() !void { - const stdout = std.io.getStdOut().writer(); - var i: usize = 1; - while (i <= 100) : (i += 1) { - if (i % 15 == 0) { - try stdout.writeAll("FizzBuzz\n"); - } else if (i % 3 == 0) { - try stdout.writeAll("Fizz\n"); - } else if (i % 5 == 0) { - try stdout.writeAll("Buzz\n"); - } else { - try stdout.print("{d}\n", .{i}); - } - } -} - -``` - -{% endraw %} - -Fizz Buzz in [Zig](/languages/zig) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/ada/index.md b/docs/projects/fraction-math/ada/index.md deleted file mode 100644 index 49f2454d6b..0000000000 --- a/docs/projects/fraction-math/ada/index.md +++ /dev/null @@ -1,269 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-10 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-10 -layout: default -tags: -- ada -- fraction-math -title: Fraction Math in Ada -title1: Fraction -title2: Math in Ada ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -pragma Ada_2022; - -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Strings.Text_Buffers; use Ada.Strings.Text_Buffers; - -procedure Fraction_Math is - - package Fractions is - type Fraction is private; - - function Make (N, D : Integer) return Fraction; - function From_String (S : String) return Fraction; - - function "+" (A, B : Fraction) return Fraction; - function "-" (A, B : Fraction) return Fraction; - function "*" (A, B : Fraction) return Fraction; - function "/" (A, B : Fraction) return Fraction; - - function "=" (A, B : Fraction) return Boolean; - function "<" (A, B : Fraction) return Boolean; - function ">" (A, B : Fraction) return Boolean; - function "<=" (A, B : Fraction) return Boolean; - function ">=" (A, B : Fraction) return Boolean; - - private - type Fraction is record - Num : Integer; - Den : Positive; - end record - with Put_Image => Fraction_Put_Image; - - function Normalize (F : Fraction) return Fraction; - function GCD (A, B : Integer) return Positive; - procedure Fraction_Put_Image - (Output : in out Root_Buffer_Type'Class; Value : Fraction); - - end Fractions; - - package body Fractions is - - function GCD (A, B : Integer) return Positive is - X : Integer := abs A; - Y : Integer := abs B; - T : Integer; - begin - if X = 0 and Y = 0 then - return 1; - end if; - - while Y /= 0 loop - T := X mod Y; - X := Y; - Y := T; - end loop; - - return Positive (X); - end GCD; - - function Normalize (F : Fraction) return Fraction is - G : constant Positive := GCD (F.Num, F.Den); - - N : Integer := F.Num / Integer (G); - D : Integer := F.Den / Integer (G); - - R : Fraction; - begin - if D < 0 then - N := -N; - D := -D; - end if; - - R.Num := N; - R.Den := Positive (D); - - return R; - end Normalize; - - function Make (N, D : Integer) return Fraction is - begin - if D = 0 then - raise Constraint_Error with "Denominator cannot be zero"; - end if; - - return Normalize ((Num => N, Den => Positive (abs D))); - end Make; - - function From_String (S : String) return Fraction is - Slash : constant Natural := Index (S, "/"); - N, D : Integer; - begin - if Slash = 0 or else Slash = S'First or else Slash = S'Last then - raise Constraint_Error with "Invalid fraction format (N/D)"; - end if; - - N := Integer'Value (S (S'First .. Slash - 1)); - D := Integer'Value (S (Slash + 1 .. S'Last)); - - return Make (N, D); - end From_String; - - procedure Fraction_Put_Image - (Output : in out Root_Buffer_Type'Class; Value : Fraction) - is - use Ada.Strings.Fixed; - - function Img (X : Integer) return String - is (Trim (Integer'Image (X), Ada.Strings.Left)); - begin - Output.Put (Img (Value.Num)); - Output.Put ("/"); - Output.Put (Img (Value.Den)); - end Fraction_Put_Image; - - function "+" (A, B : Fraction) return Fraction - is (Make (A.Num * B.Den + B.Num * A.Den, A.Den * B.Den)); - - function "-" (A, B : Fraction) return Fraction - is (Make (A.Num * B.Den - B.Num * A.Den, A.Den * B.Den)); - - function "*" (A, B : Fraction) return Fraction - is (Make (A.Num * B.Num, A.Den * B.Den)); - - function "/" (A, B : Fraction) return Fraction is - begin - if B.Num = 0 then - raise Constraint_Error with "Division by zero fraction"; - end if; - - return Make (A.Num * B.Den, A.Den * B.Num); - end "/"; - - function Compare (A, B : Fraction) return Integer is - ALB : constant Long_Long_Integer := - Long_Long_Integer (A.Num) * Long_Long_Integer (B.Den); - - BRA : constant Long_Long_Integer := - Long_Long_Integer (B.Num) * Long_Long_Integer (A.Den); - begin - return (if ALB < BRA then -1 elsif ALB > BRA then 1 else 0); - end Compare; - - function "=" (A, B : Fraction) return Boolean - is (Compare (A, B) = 0); - - function "<" (A, B : Fraction) return Boolean - is (Compare (A, B) < 0); - - function ">" (A, B : Fraction) return Boolean - is (Compare (A, B) > 0); - - function "<=" (A, B : Fraction) return Boolean - is (Compare (A, B) <= 0); - - function ">=" (A, B : Fraction) return Boolean - is (Compare (A, B) >= 0); - - end Fractions; - - procedure Print_Usage is - begin - Put_Line ("Usage: ./fraction-math operand1 operator operand2"); - end Print_Usage; - - function Bool_To_Int (B : Boolean) return String - is (Integer'Image (Boolean'Pos (B))); - -begin - if Argument_Count /= 3 then - Print_Usage; - return; - end if; - - declare - use Fractions; - A, B : Fraction; - Op : constant String := Argument (2); - begin - A := From_String (Argument (1)); - B := From_String (Argument (3)); - - if Op = "+" then - Put_Line (Fraction'Image (A + B)); - - elsif Op = "-" then - Put_Line (Fraction'Image (A - B)); - - elsif Op = "*" then - Put_Line (Fraction'Image (A * B)); - - elsif Op = "/" then - Put_Line (Fraction'Image (A / B)); - - elsif Op = "==" then - Put_Line (Bool_To_Int (A = B)); - - elsif Op = "!=" then - Put_Line (Bool_To_Int (A /= B)); - - elsif Op = "<" then - Put_Line (Bool_To_Int (A < B)); - - elsif Op = ">" then - Put_Line (Bool_To_Int (A > B)); - - elsif Op = "<=" then - Put_Line (Bool_To_Int (A <= B)); - - elsif Op = ">=" then - Put_Line (Bool_To_Int (A >= B)); - - end if; - exception - when Constraint_Error => - Print_Usage; - end; -end Fraction_Math; - -``` - -{% endraw %} - -Fraction Math in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/algol60/index.md b/docs/projects/fraction-math/algol60/index.md deleted file mode 100644 index 2d3bbce2ca..0000000000 --- a/docs/projects/fraction-math/algol60/index.md +++ /dev/null @@ -1,482 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-10 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- algol60 -- fraction-math -title: Fraction Math in ALGOL 60 -title1: Fraction Math -title2: in ALGOL 60 ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: ./fraction-math operand1 operator operand2\n"); - stop - end usage; - - procedure error(errMsg); - string errMsg; - begin - outstring(1, errMsg); - outstring(1, "\n"); - stop - end error; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - slash maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "/" maps to 17 - - null byte maps to 18 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n /", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowSlash); - value allowSlash; - integer result, ch; - boolean allowSlash; - begin - boolean valid, slashFound; - integer s; - - result := 0; - valid := false; - slashFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If slash not allowed, ignore characters until end - input. If slash allowed, ignore characters until slash - or end of input. Indicate if slash found; - ignoreloop: - if !(ch = -1 | (allowSlash & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - slashFound := true; - if !allowSlash then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If slash found, indicate last character is slash; - if slashFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Greatest common denominator using Euclidean algorithm - Source: https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations; - integer procedure gcd(a, b); - value a, b; - integer a, b; - begin - integer t; - - a := iabs(a); - b := iabs(b); - gloop: - if b != 0 then - begin - t := b; - b := a - b * (a % b); - a := t; - goto gloop - end; - - gcd := a - end gcd; - - procedure fractionReduce(n, d); - integer n, d; - begin - integer g; - - comment Error if denominator is 0; - if d = 0 then error("Divide by 0"); - - comment If denominator is negative, negate numerator and denominator; - if d < 0 then - begin - n := -n; - d := -d - end; - - comment Divide numerator and denominator by GCD; - g := gcd(n, d); - n := n / g; - d := d / g - end fractionReduce; - - boolean procedure inFraction(n, d); - integer n, d; - begin - integer ch; - boolean valid; - - comment Input numerator; - valid := inValidInteger(n, ch, true); - - comment If valid and last character is slash (13), input denominator; - d := 1; - if valid & ch = 13 then valid := inValidInteger(d, ch, false); - - comment Indicate invalid if last character is not null byte; - if valid & ch != -1 then valid := false; - - comment If valid, reduce fraction; - if valid then fractionReduce(n, d); - - inFraction := valid - end inFraction; - - comment Fraction addition and subtraction - n1/d1 +/- n2/d2 = (n1*d2 +/- n2*d1) / (d1*d2); - procedure fractionAdd(n1, d1, n2, d2, n, d); - value n1, d1, n2, d2; - integer n1, d1, n2, d2, n, d; - begin - n := n1 * d2 + n2 * d1; - d := d1 * d2 - end fractionAdd; - - procedure fractionSub(n1, d1, n2, d2, n, d); - value n1, d1, n2, d2; - integer n1, d1, n2, d2, n, d; - begin - n := n1 * d2 - n2 * d1; - d := d1 * d2 - end fractionSub; - - comment Fraction multiplication - n1/d1 * n2/d2 = (n1*n2) / (d1*d2); - procedure fractionMul(n1, d1, n2, d2, n, d); - value n1, d1, n2, d2; - integer n1, d1, n2, d2, n, d; - begin - n := n1 * n2; - d := d1 * d2 - end fractionMul; - - comment Fraction division - (n1/d1) / (n2/d2) = (n1*d2) / (n2*d1); - procedure fractionDiv(n1, d1, n2, d2, n, d); - value n1, d1, n2, d2; - integer n1, d1, n2, d2, n, d; - begin - n := n1 * d2; - d := n2 * d1 - end fractionDiv; - - comment Fraction comparison - n1/d1 comp n2/d2 = n1*d2 comp n2*d1 - - Returns: - - -1 if n1/d1 < n2/d2 - - 0 if n1/d1 == n2/d2 - - 1 otherwise; - integer procedure fractionComp(n1, d1, n2, d2); - value n1, d1, n2, d2; - integer n1, d1, n2, d2; - begin - fractionComp := sign(n1 * d2 - n2 * d1) - end fractionComp; - - comment Decode operator: - - "+" (43) maps to 1 - - "-" (45) maps to 2 - - "*" (42) maps to 3 - - "/" (47) maps to 4 - - "<" (60) maps to 5 - - ">" (62) maps to 6 - - "==" (61, 61) maps to 7 - - "<=" (60, 61) maps to 8 - - ">=" (62, 61) maps to 9 - - "!=" (33, 61) maps to 10 - - Invalid operator maps to 0; - integer procedure parseOperator(opStr, opLen); - value opLen; - integer array opStr; - integer opLen; - begin - integer op; - - comment Assume invalid operator; - op := 0; - - comment If operator length is 1: - - "+" (43) maps to 1 - - "-" (45) maps to 2 - - "*" (47) maps to 3 - - "/" (42) maps to 4 - - "<" (60) maps to 5 - - ">" (62) maps to 6; - if opLen = 1 then - begin - if opStr[1] = 43 then op := 1 - else if opStr[1] = 45 then op := 2 - else if opStr[1] = 42 then op := 3 - else if opStr[1] = 47 then op := 4 - else if opStr[1] = 60 then op := 5 - else if opStr[1] = 62 then op := 6 - end - else if opLen = 2 & opStr[2] = 61 then - begin - comment If operator length is 2 and 2nd character of operator - is 61 (=), first character of operation: - - "=" (61) maps to 7 - - "<" (60) maps to 8 - - ">" (62) maps to 9 - - "!" (33) maps to 10; - if opStr[1] = 61 then op := 7 - else if opStr[1] = 60 then op := 8 - else if opStr[1] = 62 then op := 9 - else if opStr[1] = 33 then op := 10 - end; - - parseOperator := op - end parseOperator; - - boolean procedure fractionMath(n1, d1, opStr, opLen, n2, d2, n, d); - value n1, d1, n2, d2, opLen; - integer n1, d1, opLen, n2, d2, n, d; - integer array opStr; - begin - integer op; - boolean isBool, boolResult; - - comment Parse operator. Error if invalid; - op := parseOperator(opStr, opLen); - if op < 1 then error("Invalid operator"); - - comment Handle fraction operators: - - "+" (1) - - "-" (2) - - "*" (3) - - "/" (4); - isBool := false; - if op = 1 then fractionAdd(n1, d1, n2, d2, n, d) - else if op = 2 then fractionSub(n1, d1, n2, d2, n, d) - else if op = 3 then fractionMul(n1, d1, n2, d2, n, d) - else if op = 4 then fractionDiv(n1, d1, n2, d2, n, d) - else - begin - comment Handle boolean operators: - - "<" (5) - - ">" (6) - - "==" (7) - - "<=" (8) - - ">=" (9) - - "!=" (10); - n := fractionComp(n1, d1, n2, d2); - d := 1; - isBool := true; - boolResult := if op = 5 then n < 0 - else if op = 6 then n > 0 - else if op = 7 then n = 0 - else if op = 8 then n <= 0 - else if op = 9 then n >= 0 - else n != 0 - end; - comment If boolean operation, set numerator to 1 if true, 0 if false. - Else reduce fraction; - if isBool then n := if boolResult then 1 else 0 - else fractionReduce(n, d); - - fractionMath := isBool - end fractionMath; - - procedure outFraction(n, d); - value n, d; - integer n, d; - begin - outIntegerNoSpace(n); - outstring(1, "/"); - outIntegerNoSpace(d) - end outFraction; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - integer argc, n1, d1, n2, d2, opLen, n, d; - integer array opStr[1:3]; - boolean isBool; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 3 then usage; - - comment Get fraction value from 1st argument. Exit if invalid; - if !inFraction(n1, d1) then usage; - - comment Get operator from 2nd argument. Exit if empty; - opLen := inCharArray(opStr, 3); - if opLen < 1 then usage; - - comment Get fraction value from 3rd argument. Exit if invalid; - if !inFraction(n2, d2) then usage; - - comment Perform fraction math; - isBool := fractionMath(n1, d1, opStr, opLen, n2, d2, n, d); - - comment Display numerator if boolean operation, fraction otherwise; - if isBool then outIntegerNoSpace(n) - else outFraction(n, d); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Fraction Math in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/algol68/index.md b/docs/projects/fraction-math/algol68/index.md deleted file mode 100644 index 8b81e394c7..0000000000 --- a/docs/projects/fraction-math/algol68/index.md +++ /dev/null @@ -1,266 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-01 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2023-02-01 -layout: default -tags: -- algol68 -- fraction-math -title: Fraction Math in ALGOL 68 -title1: Fraction Math -title2: in ALGOL 68 ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC usage = VOID: printf(($gl$, "Usage: ./fraction-math operand1 operator operand2")); - -# Fraction structure and operators to extract numerator and demoninator # -MODE FRACTION = STRUCT(INT num, INT den); -OP NUM = (FRACTION f) INT: num OF f; -OP DEN = (FRACTION f) INT: den OF f; - -COMMENT -Greatest common denominator using Euclidean algorithm -Source: https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations - -NOTE: This uses tail recursion -COMMENT -OP GCD = (INT a, INT b) INT: -( - IF b = 0 - THEN - ABS a - ELSE - b GCD (a MOD b) - FI -); -PRIO GCD = 8; - -# Fraction reduction # -PROC reduce = (INT n, INT d) FRACTION: -( - IF d = 0 - THEN - put(stand error, ("Division by 0", newline)); - stop - FI; - - COMMENT - Reduce by dividing numerator and denominator by greatest common denominator, - and adjust sign of numerator and denominator as follows: - - n d sign n sign d - + + + + - + - - + - - + - + - - - + + - COMMENT - INT g = n GCD d; - FRACTION(SIGN d * n OVER g, ABS d OVER g) -); - -# Fraction addition and subtraction # -# n1/d1 +/- n2/d2 = (n1*d2 +/- n2*d1) / (d1*d2) # -OP + = (FRACTION f1, FRACTION f2) FRACTION: ( - reduce(NUM f1 * DEN f2 + NUM f2 * DEN f1, DEN f1 * DEN f2) -); -OP - = (FRACTION f1, FRACTION f2) FRACTION: ( - reduce(NUM f1 * DEN f2 - NUM f2 * DEN f1, DEN f1 * DEN f2) -); - -# Fraction multiplication # -# n1/d1 * n2/d2 = (n1*n2) / (d1*d2) # -OP * = (FRACTION f1, FRACTION f2) FRACTION: ( - reduce(NUM f1 * NUM f2, DEN f1 * DEN f2) -); - -# Fraction division # -# (n1/d1) / (n2/d2) = (n1*d2) / (n2*d1) # -OP / = (FRACTION f1, FRACTION f2) FRACTION: ( - reduce(NUM f1 * DEN f2, NUM f2 * DEN f1) -); - -# Fraction comparison # -# n1/d1 OP n2/d2 = n1*d2 OP n2*d1 # -# where: OP is some comparision operation # -OP CMP = (FRACTION f1, FRACTION f2) INT: ( - NUM f1 * DEN f2 - NUM f2 * DEN f1 -); -PRIO CMP = 8; - -OP > = (FRACTION f1, FRACTION f2) BOOL: f1 CMP f2 > 0; -OP >= = (FRACTION f1, FRACTION f2) BOOL: f1 CMP f2 >= 0; -OP < = (FRACTION f1, FRACTION f2) BOOL: f1 CMP f2 < 0; -OP <= = (FRACTION f1, FRACTION f2) BOOL: f1 CMP f2 <= 0; -OP = = (FRACTION f1, FRACTION f2) BOOL: f1 CMP f2 = 0; -OP /= = (FRACTION f1, FRACTION f2) BOOL: f1 CMP f2 /= 0; - -# Parse fraction # -MODE PARSEFRACTION_RESULT = STRUCT(FRACTION value, BOOL valid); -PROC parse fraction = (REF STRING s) PARSEFRACTION_RESULT: -( - # Parse numerator # - PARSEINT_RESULT result := parse int(s); - BOOL valid := valid OF result; - INT n := value OF result; - STRING leftover := leftover OF result; - - # Assume denominator is 1 # - INT d := 1; - - # If numerator is valid and leftover starts with "/", parse denominator # - IF valid AND (leftover /= "" ANDF leftover[1] = "/") - THEN - leftover := leftover[2:]; - result := parse int(leftover); - valid := valid OF result; - d := value OF result; - leftover := leftover OF result - FI; - - # Invalid if leftover string is not empty # - IF leftover /= "" - THEN - valid := FALSE - FI; - - PARSEFRACTION_RESULT(FRACTION(n, d), valid) -); - -# Do fraction math # -MODE FRACTIONRESULT = UNION(FRACTION, BOOL); -PROC fraction math = (FRACTION f1, STRING op, FRACTION f2) FRACTIONRESULT: -( - IF op = "+" THEN f1 + f2 - ELIF op = "-" THEN f1 - f2 - ELIF op = "*" THEN f1 * f2 - ELIF op = "/" THEN f1 / f2 - ELIF op = ">" THEN f1 > f2 - ELIF op = ">=" THEN f1 >= f2 - ELIF op = "<" THEN f1 < f2 - ELIF op = "<=" THEN f1 <= f2 - ELIF op = "==" THEN f1 = f2 - ELIF op = "!=" THEN f1 /= f2 - ELSE - put(stand error, ("Invalid operator ", op, newline)); - stop - FI -); - -# Show fraction result # -PROC show fraction result = (FRACTIONRESULT result) VOID: -( - CASE result IN - (FRACTION f): printf(($g"/"gl$, whole(NUM f, 0), whole(DEN f, 0))), - (BOOL b): printf(($gl$, (b | "1" | "0"))) - ESAC -); - -# Parse 1st and 3rd command-line argument # -[2]FRACTION fractions; -STRING s; -[2]INT arg nums := (4, 6); -FOR k TO 2 -DO - s := argv(arg nums[k]); - PARSEFRACTION_RESULT result := parse fraction(s); - fractions[k] := value OF result; - - # If invalid, extra characters, exit # - IF NOT (valid OF result) - THEN - usage; - stop - FI -OD; - -# Get 2nd command-line argument. If empty, exit # -STRING op := argv(5); -IF UPB op = 0 -THEN - usage; - stop -FI; - -# DO fraction math and show result # -FRACTIONRESULT fraction result := fraction math(fractions[1], op, fractions[2]); -show fraction result(fraction result) - -``` - -{% endraw %} - -Fraction Math in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/awk/index.md b/docs/projects/fraction-math/awk/index.md deleted file mode 100644 index ebb02fb7f7..0000000000 --- a/docs/projects/fraction-math/awk/index.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-25 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2025-04-25 -layout: default -tags: -- awk -- fraction-math -title: Fraction Math in AWK -title1: Fraction -title2: Math in AWK ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: ./fraction-math operand1 operator operand2" - exit(1) -} - -function error(msg) { - print msg - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_fraction(s, f, str_arr, idx) { - # Initialize fraction to 0/1 - f[1] = 0 # numerator - f[2] = 1 # denominator - - # Split string on "/" - split(s, str_arr, "/") - - # Error if too many values - if (length(str_arr) > 2) { - f[1] = "ERROR" - } else { - # Convert each value to number - for (idx in str_arr) { - f[idx] = str_to_number(str_arr[idx]) - if (f[idx] == "ERROR") { - f[1] = "ERROR" - } - } - - # If no errors, reduce the fraction - if (f[1] != "ERROR") { - fraction_reduce(f[1], f[2], f) - } - } -} - -function fraction_reduce(n, d, f, g) { - # Error if denominator is zero - if (d == 0) { - error("Divide by zero") - } - - # If denominator is negative, negate numerator and denominator - if (d < 0) { - n = -n - d = -d - } - - # Divide numerator and denominator by GCD - g = gcd(n, d) - f[1] = n / g - f[2] = d / g -} - -# Greatest common denominator using Euclidean algorithm -# Source: https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations -function gcd(a, b, t) { - a = abs(a) - b = abs(b) - while (b) { - t = b - b = a % b - a = t - } - - return a -} - -function abs(a) { - return (a >= 0) ? a : -a -} - -function fraction_math(f1, op, f2, f, comp, type) { - type = "fraction" - switch (op) { - case "+": - fraction_add(f1, f2, f) - break - case "-": - fraction_sub(f1, f2, f) - break - case "*": - fraction_mult(f1, f2, f) - break - case "/": - fraction_div(f1, f2, f) - break - default: - type = "boolean" - switch (op) { - case "<": - f[1] = fraction_comp(f1, f2) < 0 - break - case "<=": - f[1] = fraction_comp(f1, f2) <= 0 - break - case "==": - f[1] = fraction_comp(f1, f2) == 0 - break - case "!=": - f[1] = fraction_comp(f1, f2) != 0 - break - case ">": - f[1] = fraction_comp(f1, f2) > 0 - break - case ">=": - f[1] = fraction_comp(f1, f2) >= 0 - break - default: - error("Invalid op: " op) - } - } - - return type -} - -# Fraction addition and subtraction -# n1/d1 +/- n2/d2 = (n1*d2 +/- n2*d1) / (d1*d2) -function fraction_add(f1, f2, f) { - fraction_reduce(f1[1] * f2[2] + f1[2] * f2[1], f1[2] * f2[2], f) -} - -function fraction_sub(f1, f2, f) { - fraction_reduce(f1[1] * f2[2] - f1[2] * f2[1], f1[2] * f2[2], f) -} - -# Fraction multiplication -# n1/d1 * n2/d2 = (n1*n2) / (d1*d2) -function fraction_mult(f1, f2, f) { - fraction_reduce(f1[1] * f2[1], f1[2] * f2[2], f) -} - -# Fraction division -# (n1/d1) / (n2/d2) = (n1*d2) / (n2*d1) -function fraction_div(f1, f2, f) { - fraction_reduce(f1[1] * f2[2], f1[2] * f2[1], f) -} - -# Fraction comparison -# n1/d1 comp n2/d2 = n1*d2 comp n2*d1 -# -# Returns: -# - negative if n1/d1 < n2/d2 -# - 0 if n1/d1 == n2/d2 -# - positive otherwise -function fraction_comp(f1, f2) { - return f1[1] * f2[2] - f1[2] * f2[1] -} - -function fraction_to_str(f, type, s) { - if (type == "fraction") { - s = sprintf("%d/%d", f[1], f[2]) - } else { - s = f[1] ? "1" : "0" - } - - return s -} - -BEGIN { - if (ARGC < 4) { - usage() - } - - str_to_fraction(ARGV[1], f1) - str_to_fraction(ARGV[3], f2) - if (f1[1] == "ERROR" || f2[1] == "ERROR") { - usage() - } - - type = fraction_math(f1, ARGV[2], f2, f) - print(fraction_to_str(f, type)) -} - -``` - -{% endraw %} - -Fraction Math in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/beef/index.md b/docs/projects/fraction-math/beef/index.md deleted file mode 100644 index e3b37d9984..0000000000 --- a/docs/projects/fraction-math/beef/index.md +++ /dev/null @@ -1,241 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-05 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2024-02-05 -layout: default -tags: -- beef -- fraction-math -title: Fraction Math in Beef -title1: Fraction -title2: Math in Beef ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace FractionMath; - -struct Fraction : IParseable -{ - int32 mNum; - int32 mDen; - - public this(int32 num, int32 den) - { - Runtime.Assert(den != 0); - mNum = num; - mDen = den; - reduce(); - } - - public void reduce() mut - { - if (mDen < 0) - { - mNum = -mNum; - mDen = -mDen; - } - - int32 g = gcd(mNum, mDen); - mNum /= g; - mDen /= g; - } - - public static int32 gcd(int32 num, int32 den) - { - Runtime.Assert(den != 0); - int32 a = num >= 0 ? num : -num; - int32 b = den >= 0 ? den : -den; - while (b != 0) - { - (a, b) = (b, a % b); - } - - return a; - } - - public static Result Parse(StringView str) - { - int32[] arr = scope int32[2] (0, 1); - int index = 0; - for (StringView part in str.Split('/', 2)) - { - StringView trimmedStr = scope String(part); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - switch (Int32.Parse(trimmedStr)) - { - case .Ok(out arr[index]): - case .Err: - return .Err; - } - - index++; - } - - return .Ok(Fraction(arr[0], arr[1])); - } - - public static Fraction operator +(Fraction lhs, Fraction rhs) - { - // n1/d1 + n2/d2 = (n1*d2 + n2*d1) / (d1*d2) - return .(lhs.mNum * rhs.mDen + rhs.mNum * lhs.mDen, lhs.mDen * rhs.mDen); - } - - public static Fraction operator -(Fraction lhs, Fraction rhs) - { - // n1/d1 - n2/d2 = (n1*d2 - n2*d1) / (d1*d2) - return .(lhs.mNum * rhs.mDen - rhs.mNum * lhs.mDen, lhs.mDen * rhs.mDen); - } - - public static Fraction operator *(Fraction lhs, Fraction rhs) - { - // n1/d1 * n2/d2 = (n1*n2) / (d1*d2) - return .(lhs.mNum * rhs.mNum, lhs.mDen * rhs.mDen); - } - - public static Fraction operator /(Fraction lhs, Fraction rhs) - { - // (n1/d1) / (n2/d2) = (n1*d2) / (d1*n2) - return .(lhs.mNum * rhs.mDen, lhs.mDen * rhs.mNum); - } - - public static int operator <=>(Fraction lhs, Fraction rhs) - { - // (n1/d1) <=> (n2/d2) = n1*d2 <=> d1*n2 - return (lhs.mNum * rhs.mDen) <=> (lhs.mDen * rhs.mNum); - } - - public override void ToString(String str) - { - str.Clear(); - str.AppendF($"{mNum}/{mDen}"); - } -} - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: ./fraction-math operand1 operator operand2"); - Environment.Exit(0); - } - - public enum FractionResult - { - case Frac(Fraction f); - case Bool(bool b); - - public override void ToString(String str) - { - switch (this) - { - case .Frac(let f): - f.ToString(str); - - case .Bool(let b): - ((b) ? 1 : 0).ToString(str); - } - } - } - - public static Result FractionMath(Fraction f1, Fraction f2, String op) - { - switch (op) - { - case "+": return .Ok(.Frac(f1 + f2)); - case "-": return .Ok(.Frac(f1 - f2)); - case "*": return .Ok(.Frac(f1 * f2)); - case "/": return .Ok(.Frac(f1 / f2)); - case ">": return .Ok(.Bool(f1 > f2)); - case ">=": return .Ok(.Bool(f1 >= f2)); - case "<": return .Ok(.Bool(f1 < f2)); - case "<=": return .Ok(.Bool(f1 <= f2)); - case "==": return .Ok(.Bool(f1 == f2)); - case "!=": return .Ok(.Bool(f1 != f2)); - default: return .Err; - } - } - - public static int Main(String[] args) - { - if (args.Count < 3) - { - Usage(); - } - - Fraction f1 = ?; - switch (Fraction.Parse(args[0])) - { - case .Ok(out f1): - case .Err: - Usage(); - } - - String op = scope String(args[1]); - - Fraction f2 = ?; - switch (Fraction.Parse(args[2])) - { - case .Ok(out f2): - case .Err: - Usage(); - } - - switch (FractionMath(f1, f2, op)) - { - case .Ok(let res): - Console.WriteLine(res); - - case .Err: - Usage(); - } - - return 0; - } -} - -``` - -{% endraw %} - -Fraction Math in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/c-plus-plus/index.md b/docs/projects/fraction-math/c-plus-plus/index.md deleted file mode 100644 index 83d244a506..0000000000 --- a/docs/projects/fraction-math/c-plus-plus/index.md +++ /dev/null @@ -1,682 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Niraj Kamdar -- Niraj-Kamdar -- rzuckerm -- Ștefan-Iulian Alecu -date: 2019-10-10 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- fraction-math -title: Fraction Math in C++ -title1: Fraction -title2: Math in C++ ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include - -class Fraction { -private: - long long num; - long long den; - - Fraction(long long n, long long d) : num(n), den(d) { normalize(); } - - void normalize() { - if (den < 0) { - num = -num; - den = -den; - } - long long g = std::gcd(num, den); - num /= g; - den /= g; - } - -public: - static std::optional from_string(std::string_view s) { - auto parse = [](std::string_view part) { - long long val{}; - auto [ptr, ec] = - std::from_chars(part.data(), part.data() + part.size(), val); - - return (ec == std::errc{} && ptr == part.data() + part.size()) - ? std::make_optional(val) - : std::nullopt; - }; - - auto pos = s.find('/'); - auto num = parse(s.substr(0, pos)); - auto den = - (pos == std::string_view::npos) ? 1 : parse(s.substr(pos + 1)); - - if (!num || !den || *den == 0) return std::nullopt; - return Fraction(*num, *den); - } - - Fraction& operator+=(const Fraction& r) { - num = num * r.den + r.num * den; - den *= r.den; - normalize(); - return *this; - } - Fraction& operator-=(const Fraction& r) { - num = num * r.den - r.num * den; - den *= r.den; - normalize(); - return *this; - } - Fraction& operator*=(const Fraction& r) { - num *= r.num; - den *= r.den; - normalize(); - return *this; - } - Fraction& operator/=(const Fraction& r) { - if (r.num != 0) { - num *= r.den; - den *= r.num; - normalize(); - } - return *this; - } - - friend Fraction operator+(Fraction l, const Fraction& r) { return l += r; } - friend Fraction operator-(Fraction l, const Fraction& r) { return l -= r; } - friend Fraction operator*(Fraction l, const Fraction& r) { return l *= r; } - friend Fraction operator/(Fraction l, const Fraction& r) { return l /= r; } - - auto operator<=>(const Fraction& r) const { - return num * r.den <=> r.num * den; - } - bool operator==(const Fraction&) const = default; - - long long n() const { return num; } - long long d() const { return den; } -}; - -template <> -struct std::formatter { - constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); } - auto format(const Fraction& f, format_context& ctx) const { - return std::format_to(ctx.out(), "{}/{}", f.n(), f.d()); - } -}; - -int main(int argc, char* argv[]) { - if (argc != 4) { - std::cerr << "Usage: ./fraction-math operand1 operator operand2\n"; - return EXIT_FAILURE; - } - - auto a = Fraction::from_string(argv[1]); - auto b = Fraction::from_string(argv[3]); - - if (!a || !b) { - std::cerr << "Error: invalid fraction input\n"; - return EXIT_FAILURE; - } - - std::string_view op = argv[2]; - - using Op = std::function; - - const std::unordered_map ops = { - {"+", [&] { std::cout << std::format("{}\n", *a + *b); }}, - {"-", [&] { std::cout << std::format("{}\n", *a - *b); }}, - {"*", [&] { std::cout << std::format("{}\n", *a * *b); }}, - {"/", [&] { std::cout << std::format("{}\n", *a / *b); }}, - - {"==", [&] { std::cout << (*a == *b) << '\n'; }}, - {"!=", [&] { std::cout << (*a != *b) << '\n'; }}, - {"<", [&] { std::cout << (*a < *b) << '\n'; }}, - {">", [&] { std::cout << (*a > *b) << '\n'; }}, - {"<=", [&] { std::cout << (*a <= *b) << '\n'; }}, - {">=", [&] { std::cout << (*a >= *b) << '\n'; }}, - }; - - if (auto it = ops.find(op); it != ops.end()) { - it->second(); - } else { - std::cerr << "Error: invalid operator\n"; - return EXIT_FAILURE; - } - - return EXIT_SUCCESS; -} -``` - -{% endraw %} - -Fraction Math in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Niraj Kamdar -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- Niraj Kamdar -- Niraj-Kamdar -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of May 05 2026 15:57:54. The solution was first committed on Oct 10 2019 21:55:40. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Let's first take a look at the solution. - -### Includes - -In our sample, we include two standard library utilities: - -```c++ -#include -#include -``` - -Here, we can see that we include the standard I/O for printing messages onto the -screen and we include string for performing string operation. - -### simple gcd function - -Here, we have defined `gcd` function which will give gcd of two numbers `a` and `b` using [Euclid's Algorithm][1]. - -```c++ -int gcd(int a, int b){ - if(a<0){ - a = -a; - } - while(a%b != 0){ - int i = a; - int j = b; - a = j; - b = i%j; - } - return b; -} -``` - -### constructor of Fraction class - -From there, we defined the `Fraction` class which we'll use to provide new data type for working with fractions: - -```c++ -class Fraction{ -private: - int numerator; - int denomenator; - -public: - - Fraction(int top=0, int bottom=1){ - if(bottom < 0){ - top = -top; - } - else if(bottom == 0){ - throw "Error: Denomenator can't be zero."; - } - int hcf = gcd(top, bottom); - numerator = top / hcf; - denomenator = bottom / hcf; - } -``` - -### Implementation of unary operator minus - -Here, we implement method to handle unary minus operator which just negate numerator: - -```c++ - Fraction operator -(){ - int top = -numerator; - int bottom = denomenator; - return Fraction(top, bottom); - } -``` - -### Getters for numerator and denomenator - -Below methods are just getters for the private attribute numerator and denomenator: - -```c++ - int getnumerator(){ - return numerator; - } - - int getdenometor(){ - return denomenator; - } -``` - -### Friend functions for Fraction class - -Here, we implement `friend` functions for `Fraction` class to perform Arithmatic and Relational operation and displaying -output of fraction using `cout`. This function just perform operator overloading. - -```c++ - friend ostream &operator<<(ostream &stream, const Fraction &frac); - friend Fraction operator+(const Fraction f1, const Fraction f2); - friend Fraction operator+(const Fraction f1, const int f2); - friend Fraction operator+(const int f1, const Fraction f2); - friend Fraction operator+=(const Fraction f1, const Fraction f2); - friend Fraction operator-(const Fraction f1, const Fraction f2); - friend Fraction operator-(const Fraction f1, const int f2); - friend Fraction operator-(const int f1, const Fraction f2); - friend Fraction operator-=(const Fraction f1, const Fraction f2); - friend Fraction operator*(const Fraction f1, const Fraction f2); - friend Fraction operator*(const Fraction f1, const int f2); - friend Fraction operator*(const int f1, const Fraction f2); - friend Fraction operator*=(const Fraction f1, const Fraction f2); - friend Fraction operator/(const Fraction f1, const Fraction f2); - friend Fraction operator/(const Fraction f1, const int f2); - friend Fraction operator/(const int f1, const Fraction f2); - friend Fraction operator/=(const Fraction f1, const Fraction f2); - friend bool operator==(const Fraction f1, const Fraction f2); - friend bool operator<(const Fraction f1, const Fraction f2); - friend bool operator>(const Fraction f1, const Fraction f2); - friend bool operator!=(const Fraction f1, const Fraction f2); - friend bool operator<=(const Fraction f1, const Fraction f2); - friend bool operator>=(const Fraction f1, const Fraction f2); -}; -``` - -### stream operator - -Here, we overloaded stream operator so that we can use cout directly on Fraction object. - -```c++ -ostream &operator <<(ostream &stream, const Fraction &frac){ - stream << frac.numerator << "/" << frac.denomenator; - return stream; -} -``` - -### Addition - -Here, we have defined methods for addition operator for different cases. -Examples: - -1. `Fraction(2, 3) + 6` -2. `Fraction(2, 3) + Fraction(4, 5)` -3. `7 + Fraction(4, 5)` - -```c++ -Fraction operator+(const Fraction f1, const Fraction f2) -{ - int top = f1.numerator * f2.denomenator + f2.numerator * f1.denomenator; - int bottom = f1.denomenator * f2.denomenator; - return Fraction(top, bottom); -} - -Fraction operator+=(const Fraction f1, const Fraction f2) -{ - return f1 + f2; -} - -Fraction operator+(const Fraction f1, const int f2) -{ - int top = f1.numerator + f2 * f1.denomenator; - int bottom = f1.denomenator; - return Fraction(top, bottom); -} - -Fraction operator+(const int f1, const Fraction f2) -{ - int top = f1 * f2.denomenator + f2.numerator; - int bottom = f2.denomenator; - return Fraction(top, bottom); -} -``` - -### Subtraction - -Here, we have defined methods for substraction operator for different cases. -Examples: - -1. `Fraction(2, 3) - 6` -2. `Fraction(2, 3) - Fraction(4, 5)` -3. `7 - Fraction(4, 5)` - -```c++ -Fraction operator-(const Fraction f1, const Fraction f2) -{ - int top = f1.numerator * f2.denomenator - f2.numerator * f1.denomenator; - int bottom = f1.denomenator * f2.denomenator; - return Fraction(top, bottom); -} - -Fraction operator-=(const Fraction f1, const Fraction f2) -{ - return f1 - f2; -} - -Fraction operator-(const Fraction f1, const int f2) -{ - int top = f1.numerator - f2 * f1.denomenator; - int bottom = f1.denomenator; - return Fraction(top, bottom); -} - -Fraction operator-(const int f1, const Fraction f2) -{ - int top = f1 * f2.denomenator - f2.numerator; - int bottom = f2.denomenator; - return Fraction(top, bottom); -} -``` - -### Multiplication - -Here, we have defined methods for multiplication operator for different cases. -Examples: - -1. `Fraction(2, 3) * 6` -2. `Fraction(2, 3) * Fraction(4, 5)` -3. `7 * Fraction(4, 5)` - -```c++ -Fraction operator*(const Fraction f1, const Fraction f2) -{ - int top = f1.numerator * f2.numerator; - int bottom = f1.denomenator * f2.denomenator; - return Fraction(top, bottom); -} - -Fraction operator*=(const Fraction f1, const Fraction f2) -{ - return f1 * f2; -} - -Fraction operator*(const Fraction f1, const int f2) -{ - int top = f1.numerator * f2; - int bottom = f1.denomenator; - return Fraction(top, bottom); -} - -Fraction operator*(const int f1, const Fraction f2) -{ - int top = f1 * f2.numerator; - int bottom = f2.denomenator; - return Fraction(top, bottom); -} -``` - -### Division - -Here, we have defined methods for division operator for different cases. -Examples: - -1. `Fraction(2, 3) / 6` -2. `Fraction(2, 3) / Fraction(4, 5)` -3. `7 / Fraction(4, 5)` - -```c++ -Fraction operator/(const Fraction f1, const Fraction f2) -{ - int top = f1.numerator * f2.denomenator; - int bottom = f1.denomenator * f2.numerator; - return Fraction(top, bottom); -} - -Fraction operator/=(const Fraction f1, const Fraction f2) -{ - return f1 / f2; -} - -Fraction operator/(const Fraction f1, const int f2) -{ - int top = f1.numerator; - int bottom = f1.denomenator * f2; - return Fraction(top, bottom); -} - -Fraction operator/(const int f1, const Fraction f2) -{ - int top = f2.numerator; - int bottom = f2.denomenator * f1; - return Fraction(top, bottom); -} -``` - -### Is equal to - -Here, we implemented `==` operator to check if two `Fraction`s are equal to each other. - -```c++ -bool operator==(const Fraction f1, const Fraction f2) -{ - int result = f1.numerator * f2.denomenator - f2.numerator * f1.denomenator; - if (result == 0) - { - return true; - } - else - { - return false; - } -} -``` - -### Greater than - -Here, we implemented `>` operator to check if first `Fraction` is greater than the second `Fraction`. - -```c++ -bool operator>(const Fraction f1, const Fraction f2) -{ - int result = f1.numerator * f2.denomenator - f2.numerator * f1.denomenator; - if (result > 0) - { - return true; - } - else - { - return false; - } -} -``` - -### Less than - -Here, we implemented `<` operator to check if first `Fraction` is less than the second `Fraction`. - -```c++ -bool operator<(const Fraction f1, const Fraction f2) -{ - int result = f1.numerator * f2.denomenator - f2.numerator * f1.denomenator; - if (result < 0) - { - return true; - } - else - { - return false; - } -} -``` - -### Greater than or equal to - -Here, we implemented `>=` operator to check if first `Fraction` is greater than or equal to the second `Fraction`. - -```c++ -bool operator>=(const Fraction f1, const Fraction f2) -{ - return !(f1 < f2); -} -``` - -### Less than - -Here, we implemented `<=` operator to check if first `Fraction` is less than or equal to the second `Fraction`. - -```c++ -bool operator<=(const Fraction f1, const Fraction f2) -{ - return !(f1 > f2); -} -``` - -### Is not equal to - -Here, we implemented `!=` operator to check if two `Fraction`s aren't equal to each other. - -```c++ -bool operator!=(const Fraction f1, const Fraction f2) -{ - return !(f1 == f2); -} -``` - -### From string to Fraction type - -Here, we implemented function to perform conversion to `Fraction` from `string` object for that we are using `find` method to find `/` -in operand to differentiate numerator from denomenator after that we are using `stoi` to convert `string` to integer and finally we are returning newly created Fraction object. -Example: `"2/7" -> Fraction(2, 7)` - -```c++ -Fraction fromstr(string s) -{ - int idx = s.find("/"); - if (idx != string::npos) - { - string top = s.substr(0, idx); - string bottom = s.substr(idx + 1); - int p = stoi(top); - int q = stoi(bottom); - return Fraction(p, q); - } - return Fraction(stoi(s)); -} -``` - -### Main function - -Here, we take varible arguments in `main` function from console to perform operation on fractions -if `argc` (argument count) is not 4 that's ./fraction (default: `./a.out`) operand1 operator operand2 then it exit the program; -otherwise, it converts those arguments to string object so that we can perform `string` to `Fraction` conversion using `fromstr` function on it. - -```c++ -int main(int argc, char const *argv[]) -{ - // Testing above class methods - if (argc != 4) - { - cout << "Usage: " << argv[0] << " operand1 operator operand2"; - exit(1); - } - string s1(argv[1]); - string op(argv[2]); - string s2(argv[3]); - - Fraction o1 = fromstr(s1); - Fraction o2 = fromstr(s2); -``` - -### Execute Operations - -From there, we check which operator is sent in the argument and perform operations according to that operator. -Example: - -* `if op == "+"` then print `o1 + o2` -* `if op == "=="` then print `o1 == o2` - -```c++ - if (op == "+") - { - cout << (o1 + o2) << endl; - } - else if (op == "-") - { - cout << (o1 - o2) << endl; - } - else if (op == "*") - { - cout << (o1 * o2) << endl; - } - else if (op == "/") - { - cout << (o1 / o2) << endl; - } - else if (op == "==") - { - cout << (o1 == o2) << endl; - } - else if (op == "!=") - { - cout << (o1 != o2) << endl; - } - else if (op == ">") - { - cout << (o1 > o2) << endl; - } - else if (op == "<") - { - cout << (o1 < o2) << endl; - } - else if (op == ">=") - { - cout << (o1 >= o2) << endl; - } - else if (op == "<=") - { - cout << (o1 <= o2) << endl; - } - else - { - cout << "Error: Invalid operand " << op << endl; - exit(1); - } - return 0; -} -``` - -[1]: https://en.wikipedia.org/wiki/Euclidean_algorithm - - -## How to Run the Solution - -To run the fractions operation in cpp program, grab a copy of the fractions.cpp file -from GitHub. After that, get the latest version of g++ compiler. Now, all you have to -do is run the following from the command line: - -```console -g++ fractions.cpp -o fractions -./fractions "1/4" "+" "5/8" -``` - -Alternatively, you can always copy the source code into an online c++ -compiler. Just make sure you pass some input to your program before you run -it. diff --git a/docs/projects/fraction-math/c-sharp/index.md b/docs/projects/fraction-math/c-sharp/index.md deleted file mode 100644 index 91ba6ab3e4..0000000000 --- a/docs/projects/fraction-math/c-sharp/index.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -authors: -- Alexander Ruban -- Ștefan-Iulian Alecu -date: 2024-11-13 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- fraction-math -title: Fraction Math in C# -title1: Fraction -title2: Math in C# ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if ( - args is not [var leftRaw, var op, var rightRaw] - || !Fraction.TryParse(leftRaw, out var a) - || !Fraction.TryParse(rightRaw, out var b) -) -{ - Console.Error.WriteLine("Usage: ./fraction-math operand1 operator operand2"); - return; -} - -Console.WriteLine( - op switch - { - "+" => (a + b).ToString(), - "-" => (a - b).ToString(), - "*" => (a * b).ToString(), - "/" => (a / b).ToString(), - "==" => (a == b ? 1 : 0), - "!=" => (a != b ? 1 : 0), - ">" => (a > b ? 1 : 0), - "<" => (a < b ? 1 : 0), - ">=" => (a >= b ? 1 : 0), - "<=" => (a <= b ? 1 : 0), - _ => "Error: Invalid operator", - } -); - -public readonly record struct Fraction(long N, long D) : IComparable -{ - public override string ToString() => $"{N}/{D}"; - - public static Fraction Create(long n, long d) - { - if (d == 0) - throw new DivideByZeroException(); - - long g = Gcd(n, d); - return new(n / g * Math.Sign(d), Math.Abs(d / g)); - } - - static long Gcd(long a, long b) - { - a = Math.Abs(a); - b = Math.Abs(b); - - while (b != 0) - (a, b) = (b, a % b); - - return a == 0 ? 1 : a; - } - - public static bool TryParse(ReadOnlySpan s, out Fraction f) - { - f = default; - - int i = s.IndexOf('/'); - return i >= 0 - && long.TryParse(s[..i], out long n) - && long.TryParse(s[(i + 1)..], out long d) - && d != 0 - && (f = Create(n, d)) == f; - } - - public static Fraction operator +(Fraction a, Fraction b) => - Create(a.N * b.D + b.N * a.D, a.D * b.D); - - public static Fraction operator -(Fraction a, Fraction b) => - Create(a.N * b.D - b.N * a.D, a.D * b.D); - - public static Fraction operator *(Fraction a, Fraction b) => Create(a.N * b.N, a.D * b.D); - - public static Fraction operator /(Fraction a, Fraction b) => Create(a.N * b.D, a.D * b.N); - - public static bool operator <(Fraction a, Fraction b) => a.N * b.D < b.N * a.D; - - public static bool operator >=(Fraction a, Fraction b) => !(a < b); - - public static bool operator >(Fraction a, Fraction b) => b < a; - - public static bool operator <=(Fraction a, Fraction b) => !(b < a); - - public int CompareTo(Fraction other) => (N * other.D).CompareTo(other.N * D); -} - -``` - -{% endraw %} - -Fraction Math in [C#](/languages/c-sharp) was written by: - -- Alexander Ruban -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/c/index.md b/docs/projects/fraction-math/c/index.md deleted file mode 100644 index 0d141fc24e..0000000000 --- a/docs/projects/fraction-math/c/index.md +++ /dev/null @@ -1,209 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-18 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- fraction-math -title: Fraction Math in C -title1: Fraction -title2: Math in C ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -typedef struct -{ - int numerator; - int denominator; -} Fraction; - -int gcd(int a, int b) -{ - if (b == 0) - return a; - return gcd(b, a % b); -} - -Fraction simplify(Fraction f) -{ - int g = gcd(abs(f.numerator), abs(f.denominator)); - f.numerator /= g; - f.denominator /= g; - if (f.denominator < 0) - { - f.numerator = -f.numerator; - f.denominator = -f.denominator; - } - return f; -} - -Fraction parse_fraction(const char *str) -{ - Fraction f; - sscanf(str, "%d/%d", &f.numerator, &f.denominator); - return simplify(f); -} - -Fraction add(Fraction a, Fraction b) -{ - Fraction result = {a.numerator * b.denominator - + b.numerator * a.denominator, - a.denominator * b.denominator}; - return simplify(result); -} - -Fraction subtract(Fraction a, Fraction b) -{ - Fraction result = {a.numerator * b.denominator - - b.numerator * a.denominator, - a.denominator * b.denominator}; - return simplify(result); -} - -Fraction multiply(Fraction a, Fraction b) -{ - Fraction result = {a.numerator * b.numerator, - a.denominator * b.denominator}; - return simplify(result); -} - -Fraction divide(Fraction a, Fraction b) -{ - Fraction result = {a.numerator * b.denominator, - a.denominator * b.numerator}; - return simplify(result); -} - -int compare(Fraction a, Fraction b) -{ - int lhs = a.numerator * b.denominator; - int rhs = b.numerator * a.denominator; - if (lhs < rhs) - return -1; - if (lhs > rhs) - return 1; - return 0; -} - -void print_fraction(Fraction f) -{ - printf("%d/%d\n", f.numerator, f.denominator); -} - -int main(int argc, char *argv[]) -{ - if (argc != 4) - { - printf("Usage: ./fraction-math operand1 operator operand2\n"); - return 1; - } - - Fraction a = parse_fraction(argv[1]); - Fraction b = parse_fraction(argv[3]); - char *op = argv[2]; - - Fraction result; - int cmp; - - if (strcmp(op, "+") == 0) - { - result = add(a, b); - print_fraction(result); - } - else if (strcmp(op, "-") == 0) - { - result = subtract(a, b); - print_fraction(result); - } - else if (strcmp(op, "*") == 0) - { - result = multiply(a, b); - print_fraction(result); - } - else if (strcmp(op, "/") == 0) - { - result = divide(a, b); - print_fraction(result); - } - else if (strcmp(op, "==") == 0) - { - cmp = compare(a, b); - printf("%d\n", cmp == 0); - } - else if (strcmp(op, ">") == 0) - { - cmp = compare(a, b); - printf("%d\n", cmp > 0); - } - else if (strcmp(op, "<") == 0) - { - cmp = compare(a, b); - printf("%d\n", cmp < 0); - } - else if (strcmp(op, ">=") == 0) - { - cmp = compare(a, b); - printf("%d\n", cmp >= 0); - } - else if (strcmp(op, "<=") == 0) - { - cmp = compare(a, b); - printf("%d\n", cmp <= 0); - } - else if (strcmp(op, "!=") == 0) - { - cmp = compare(a, b); - printf("%d\n", cmp != 0); - } - else - { - printf("Invalid operator\n"); - return 1; - } - - return 0; -} - -``` - -{% endraw %} - -Fraction Math in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/cobol/index.md b/docs/projects/fraction-math/cobol/index.md deleted file mode 100644 index 09895b437e..0000000000 --- a/docs/projects/fraction-math/cobol/index.md +++ /dev/null @@ -1,203 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- fraction-math -title: Fraction Math in COBOL -title1: Fraction Math -title2: in COBOL ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. fraction-math. - -data division. -working-storage section. - -01 ws-arguments. - 05 ws-arg1 pic x(50). - 05 ws-arg2 pic x(50). - 05 ws-op pic x(2). - -01 ws-fractions. - 05 ws-f1. - 10 ws-n1 pic s9(18). - 10 ws-d1 pic s9(18). - 05 ws-f2. - 10 ws-n2 pic s9(18). - 10 ws-d2 pic s9(18). - 05 ws-result. - 10 ws-rn pic s9(18). - 10 ws-rd pic s9(18). - -01 ws-flags. - 05 ws-valid-flag pic x value 'y'. - 88 is-valid value 'y'. - 88 is-invalid value 'n'. - -01 ws-work-areas. - 05 ws-temp-fraction pic x(50). - 05 ws-pos pic 9(4). - 05 ws-gcd-vars. - 10 ws-a pic s9(18). - 10 ws-b pic s9(18). - 10 ws-rem pic s9(18). - 05 ws-cross-prod-1 pic s9(36). - 05 ws-cross-prod-2 pic s9(36). - -01 ws-display-fields. - 05 ws-out-n pic -(18)9. - 05 ws-out-d pic -(18)9. - -procedure division. -000-main. - accept ws-arg1 from argument-value - accept ws-op from argument-value - accept ws-arg2 from argument-value - - if ws-arg1 = spaces or ws-op = spaces or ws-arg2 = spaces - perform show-usage - stop run - end-if - - move ws-arg1 to ws-temp-fraction - perform parse-fraction - move ws-rn to ws-n1 - move ws-rd to ws-d1 - - if is-valid - move ws-arg2 to ws-temp-fraction - perform parse-fraction - move ws-rn to ws-n2 - move ws-rd to ws-d2 - end-if - - if is-invalid - perform show-usage - stop run - end-if - - perform calculate-result - stop run. - -parse-fraction. - set is-valid to true - move 0 to ws-pos - inspect ws-temp-fraction tallying ws-pos for characters before "/" - - if ws-pos = 0 or ws-pos = length of ws-temp-fraction - set is-invalid to true - else - move function numval(ws-temp-fraction(1:ws-pos)) to ws-rn - move function numval(ws-temp-fraction(ws-pos + 2:)) to ws-rd - if ws-rd = 0 - set is-invalid to true - end-if - end-if. - -calculate-result. - evaluate ws-op - when "+" - compute ws-rn = ws-n1 * ws-d2 + ws-n2 * ws-d1 - compute ws-rd = ws-d1 * ws-d2 - perform reduce-and-print - when "-" - compute ws-rn = ws-n1 * ws-d2 - ws-n2 * ws-d1 - compute ws-rd = ws-d1 * ws-d2 - perform reduce-and-print - when "*" - multiply ws-n1 by ws-n2 giving ws-rn - multiply ws-d1 by ws-d2 giving ws-rd - perform reduce-and-print - when "/" - multiply ws-n1 by ws-d2 giving ws-rn - multiply ws-d1 by ws-n2 giving ws-rd - perform reduce-and-print - when "==" when "!=" when ">" when "<" when ">=" when "<=" - perform compare-fractions - when other - perform show-usage - end-evaluate. - -reduce-and-print. - if ws-rn = 0 - move 1 to ws-rd - else - move function abs(ws-rn) to ws-a - move function abs(ws-rd) to ws-b - perform until ws-b = 0 - divide ws-a by ws-b giving ws-a remainder ws-rem - move ws-b to ws-a - move ws-rem to ws-b - end-perform - divide ws-a into ws-rn - divide ws-a into ws-rd - end-if - - if ws-rd < 0 - multiply -1 by ws-rn - multiply -1 by ws-rd - end-if - - move ws-rn to ws-out-n - move ws-rd to ws-out-d - display function trim(ws-out-n) "/" function trim(ws-out-d). - -compare-fractions. - compute ws-cross-prod-1 = ws-n1 * ws-d2 - compute ws-cross-prod-2 = ws-n2 * ws-d1 - - evaluate true - when ws-op = "==" and ws-cross-prod-1 = ws-cross-prod-2 - when ws-op = "!=" and ws-cross-prod-1 not = ws-cross-prod-2 - when ws-op = ">" and ws-cross-prod-1 > ws-cross-prod-2 - when ws-op = "<" and ws-cross-prod-1 < ws-cross-prod-2 - when ws-op = ">=" and ws-cross-prod-1 >= ws-cross-prod-2 - when ws-op = "<=" and ws-cross-prod-1 <= ws-cross-prod-2 - display "1" - when other - display "0" - end-evaluate. - -show-usage. - display "Usage: ./fraction-math operand1 operator operand2". -``` - -{% endraw %} - -Fraction Math in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/commodore-basic/index.md b/docs/projects/fraction-math/commodore-basic/index.md deleted file mode 100644 index 5a582dd276..0000000000 --- a/docs/projects/fraction-math/commodore-basic/index.md +++ /dev/null @@ -1,245 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-18 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2023-10-18 -layout: default -tags: -- commodore-basic -- fraction-math -title: Fraction Math in Commodore BASIC -title1: Fraction Math in -title2: Commodore BASIC ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input fraction 1 -10 GOSUB 2000 -20 IF V = 0 OR C <> -1 THEN GOTO 200: REM invalid or end of input/value -30 N1 = N -40 D1 = D -45 REM Input operator -50 GOSUB 2500 -60 IF S$ = "" THEN GOTO 200 -70 OP$ = S$ -75 REM Input fraction 2 -80 GOSUB 2000 -90 IF V = 0 OR C <> -1 THEN GOTO 200: REM invalid or end of input/value -100 N2 = N -110 D2 = D -115 REM Perform fraction math and display result -120 GOSUB 3000 -130 IF V <> 0 THEN GOSUB 4000 -140 END -200 PRINT "Usage: ./fraction-math operand1 operator operand2" -210 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read fraction -2001 REM N contains numerator -2002 REM D contains denominator -2003 REM V = 1 if valid faction, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2010 GOSUB 1000: REM Read numerator value -2020 IF V = 0 THEN RETURN: REM invalid -2030 N = NR: REM store numerator -2040 D = 1: REM assume no denominator -2050 IF C < 0 THEN RETURN: REM end of input/value -2060 IF C <> 47 THEN GOTO 2110: REM not slash -2070 GOSUB 1000: REM Read denominator value -2080 IF V = 0 THEN RETURN: REM invalid -2090 D = NR: REM store denominator -2100 IF C < 0 THEN RETURN: REM end of input/value -2110 V = 0 -2120 RETURN -2500 REM Read input value one character at a time since Commodore BASIC -2501 REM has trouble reading line from stdin properly -2502 REM S$ = string -2503 REM Initialize -2510 S$ = "" -2515 REM Append characters until end of input -2520 GET A$ -2530 C = ASC(A$) -2540 IF C = 13 OR C = 255 THEN RETURN: REM end of value or input -2550 IF C = 9 OR C = 10 OR C = 32 THEN GOTO 2520: REM whitespace -2560 S$ = S$ + A$ -2570 GOTO 2520 -3000 REM Perform fraction math -3001 REM Inputs: -3002 REM - N1, D1 = Fraction 1 -3003 REM - OP$ = Operator -3004 REM - N2, D2 = Fraction 2 -3005 REM Outputs: -3006 REM - Boolean: -3007 REM - B = 1 -3008 REM - NB = 1 if true, zero if false -3009 REM - Fraction: -3010 REM - B = 0 -3020 REM - NR, DR = Fraction result -3030 REM - V = 1 if valid result, 0 otherwise -3040 V = 1: REM valid -3050 B = 0: REM not boolean -3060 IF OP$ = "+" THEN GOTO 3200 -3070 IF OP$ = "-" THEN GOTO 3250 -3080 IF OP$ = "*" THEN GOTO 3300 -3090 IF OP$ = "/" THEN GOTO 3350 -3100 B = 1: REM boolean -3110 GOSUB 3550: REM compare fractions -3120 IF OP$ = ">" THEN NB = (NB > 0): GOTO 3650 -3130 IF OP$ = ">=" THEN NB = (NB >= 0): GOTO 3650 -3140 IF OP$ = "<" THEN NB = (NB < 0): GOTO 3650 -3150 IF OP$ = "<=" THEN NB = (NB <= 0): GOTO 3650 -3160 IF OP$ = "==" THEN NB = (NB = 0): GOTO 3650 -3170 IF OP$ = "!=" THEN NB = (NB <> 0): GOTO 3650 -3180 PRINT "Invalid operator" -3190 V = 0: REM invalid -3195 RETURN -3200 REM Fraction addition -3201 REM N1/D1 + N2/D2 = (N1*D2 + N2*D1) / (D1*D2) -3210 NR = N1 * D2 + N2 * D1 -3220 DR = D1 * D2 -3230 GOTO 3400: REM reduce fraction -3250 REM Fraction subtraction -3251 REM N1/D1 - N2/D2 = (N1*D2 - N2*D1) / (D1*D2) -3260 NR = N1 * D2 - N2 * D1 -3270 DR = D1 * D2 -3280 GOTO 3400: REM reduce fraction -3300 REM Fraction multiplication -3301 REM N1/D1 * N2/D2 = (N1*N2) / (D1*D2) -3310 NR = N1 * N2 -3320 DR = D1 * D2 -3330 GOTO 3400: REM reduce fraction -3350 REM Fraction division -3351 REM (N1/D1) / (N2/D2) = (N1*D2) / (N2*D1) -3360 NR = N1 * D2 -3370 DR = N2 * D1 -3400 REM Reduce fraction -3401 REM Calculate GCD -3402 REM GA will contain GCD -3410 GA = ABS(NR) -3420 GB = ABS(DR) -3430 IF GB = 0 THEN GOTO 3480 -3440 T = GB -3450 GB = GA - INT(GA / GB) * GB: REM GA mod GB -3460 GA = T -3470 GOTO 3430 -3480 REM Fix up signs -3481 REM N D sign N sign D -3482 REM + + + + -3483 REM + - - + -3484 REM - + - + -3485 REM - - + + -3500 NR = SGN(DR) * NR / GA -3510 DR = ABS(DR) / GA -3520 RETURN -3550 REM Compare fractions -3551 REM Inputs: -3552 REM - N1, D1 = Fraction 1 -3553 REM - N2, D2 = Fraction 2 -3554 REM Output: NB = result of compare: -3555 REM - positive if N1/D1 > N2/D2 -3556 REM - zero if N1/D1 == N2/D2 -3557 REM - negative if N1/D1 < N2/D2 -3560 NB = N1 * D2 - N2 * D1 -3600 RETURN -3650 REM Convert comparison to 1 if true, 0 otherwise -3660 IF NB <> 0 THEN NB = 1 -3670 RETURN -4000 REM Display fraction math result -4001 REM Inputs: -4002 REM - B = 1 -4003 REM - NB = 1 if true, 0 if false -4004 REM - Fraction: -4005 REM - B = 0 -4006 REM - NR, DR = Fraction result -4010 IF B <> 0 THEN GOTO 4080 -4020 SN$ = STR$(NR) -4030 IF NR >= 0 THEN SN$ = MID$(SN$, 2): REM remove leading space -4040 SD$ = STR$(DR) -4050 IF DR >= 0 THEN SD$ = MID$(SD$, 2): REM remove leading space -4060 S$ = SN$ + "/" + SD$ -4070 GOTO 4090 -4080 S$ = MID$(STR$(NB), 2) -4090 PRINT S$ -4100 RETURN - -``` - -{% endraw %} - -Fraction Math in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/euphoria/index.md b/docs/projects/fraction-math/euphoria/index.md deleted file mode 100644 index 600cd9c765..0000000000 --- a/docs/projects/fraction-math/euphoria/index.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-26 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2023-02-26 -layout: default -tags: -- euphoria -- fraction-math -title: Fraction Math in Euphoria -title1: Fraction Math -title2: in Euphoria ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/math.e -include std/sequence.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_fraction() return value -enum NUM, DEN, PARSE_FRACTION_VALID - -function parse_fraction(sequence s) - -- Split numerator and denominator - sequence parts = split(s, '/',, 2) - - -- Parse numerator - sequence result = parse_int(parts[1]) - integer num = result[PARSE_INT_VALUE] - boolean valid = result[PARSE_INT_VALID] - - -- Assume denominator is 1 - integer den = 1 - - -- If numerator is valid and there is a denominator - if valid and length(parts) > 1 - then - -- Parse denominator - result = parse_int(parts[2]) - valid = result[PARSE_INT_VALID] - den = result[PARSE_INT_VALUE] - end if - - return {num, den, valid} -end function - -procedure usage() - puts(STDOUT, "Usage: ./fraction-math operand1 operator operand2\n") - abort(0) -end procedure - --- Do fraction math -function fraction_math(sequence fraction1, sequence op, sequence fraction2) - object result - switch op - do - case "+" - then - result = fraction_add(fraction1, fraction2) - case "-" - then - result = fraction_sub(fraction1, fraction2) - case "*" - then - result = fraction_mult(fraction1, fraction2) - case "/" - then - result = fraction_div(fraction1, fraction2) - case ">" - then - result = (fraction_compare(fraction1, fraction2) > 0) - case ">=" - then - result = (fraction_compare(fraction1, fraction2) >= 0) - case "<" - then - result = (fraction_compare(fraction1, fraction2) < 0) - case "<=" - then - result = (fraction_compare(fraction1, fraction2) <= 0) - case "==" - then - result = (fraction_compare(fraction1, fraction2) = 0) - case "!=" - then - result = (fraction_compare(fraction1, fraction2) != 0) - case else - printf(STDERR, "Invalid operator %s\n", {op}) - end switch - - return result -end function - --- Fraction reduction -function reduce(integer num, integer den) - if den = 0 - then - puts(STDERR, "Division by 0\n") - abort(0) - end if - - -- Reduce by dividing numerator and denominator by greatest common denominator, - -- and adjust sign of numerator and denominator as follows: - -- - -- n d sign n sign d - -- + + + + - -- + - - + - -- - + - + - -- - - + + - integer g = gcd(num, den) - return {sign(den) * intdiv(num, g), intdiv(abs(den), g)} -end function - --- Fraction addition --- n1/d1 + n2/d2 = (n1*d2 + n2*d1) / (d1*d2) -function fraction_add(sequence fraction1, sequence fraction2) - return reduce( - fraction1[NUM] * fraction2[DEN] + fraction2[NUM] * fraction1[DEN], - fraction1[DEN] * fraction2[DEN] - ) -end function - --- Fraction subtraction --- n1/d1 + n2/d2 = (n1*d2 - n2*d1) / (d1*d2) -function fraction_sub(sequence fraction1, sequence fraction2) - return reduce( - fraction1[NUM] * fraction2[DEN] - fraction2[NUM] * fraction1[DEN], - fraction1[DEN] * fraction2[DEN] - ) -end function - --- Fraction multiplication --- n1/d1 * n2/d2 = (n1*n2) / (d1*d2) -function fraction_mult(sequence fraction1, sequence fraction2) - return reduce(fraction1[NUM] * fraction2[NUM], fraction1[DEN] * fraction2[DEN]) -end function - --- Fraction division --- (n1/d1) / (n2/d2) = (n1*d2) / (n2*d1) -function fraction_div(sequence fraction1, sequence fraction2) - return reduce(fraction1[NUM] * fraction2[DEN], fraction1[DEN] * fraction2[NUM]) -end function - --- Fraction compare --- n1/d1 OP n2/d2 = n1*d2 OP n2*d1 -function fraction_compare(sequence fraction1, sequence fraction2) - return fraction1[NUM] * fraction2[DEN] - fraction2[NUM] * fraction1[DEN] -end function - --- Show fraction result -procedure show_fraction_result(object result) - -- If boolean, show boolean result - if boolean(result) - then - printf(STDOUT, "%d\n", result) - else - printf(STDOUT, "%d/%d\n", {result[NUM], result[DEN]}) - end if -end procedure - --- Check command-line arguments -sequence argv = command_line() -if ( - length(argv) < 6 - or length(argv[4]) = 0 - or length(argv[5]) = 0 - or length(argv[6]) = 0 -) -then - usage() -end if - --- Parse 1st and 3rd command-line argument -sequence arg_nums = {4, 6} -sequence fractions = {} -for k = 1 to 2 -do - sequence result = parse_fraction(argv[arg_nums[k]]) - fractions &= {result[NUM..DEN]} - if not result[PARSE_FRACTION_VALID] - then - usage() - end if -end for - --- Parse 2nd command-line argument -sequence op = argv[5] - --- Do fraction math and show result -object fraction_result = fraction_math(fractions[1], op, fractions[2]) -show_fraction_result(fraction_result) - -``` - -{% endraw %} - -Fraction Math in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/f-sharp/index.md b/docs/projects/fraction-math/f-sharp/index.md deleted file mode 100644 index b37a2251e9..0000000000 --- a/docs/projects/fraction-math/f-sharp/index.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- fraction-math -title: Fraction Math in F# -title1: Fraction -title2: Math in F# ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -[] -type Fraction = - private - { n: int64 - d: int64 } - - static member Raw(n, d) = - if d = 0L then - invalidArg "d" "Denominator cannot be zero" - - let rec gcd x y = if y = 0L then abs x else gcd y (x % y) - - let sign = if d < 0L then -1L else 1L - let nn = n * int64 sign - let dd = abs d - - let g = gcd nn dd - { n = nn / g; d = dd / g } - - static member Create(n, d) = - if d = 0L then - Error "Division by zero" - else - Ok(Fraction.Raw(n, d)) - - override x.ToString() = - if x.d = 1L then $"{x.n}" else $"{x.n}/{x.d}" - - override x.Equals o = - match o with - | :? Fraction as f -> x.n = f.n && x.d = f.d - | _ -> false - - override x.GetHashCode() = hash (x.n, x.d) - - interface IComparable with - member x.CompareTo o = - match o with - | :? Fraction as f -> compare (x.n * f.d) (f.n * x.d) - | _ -> 0 - - static member (+)(a, b) = - Fraction.Raw(a.n * b.d + b.n * a.d, a.d * b.d) - - static member (-)(a, b) = - Fraction.Raw(a.n * b.d - b.n * a.d, a.d * b.d) - - static member (*)(a, b) = Fraction.Raw(a.n * b.n, a.d * b.d) - - static member TryDiv(a, b) = - if b.n = 0L then - Error "Division by zero" - else - Ok(Fraction.Raw(a.n * b.d, a.d * b.n)) - -module Calculator = - let (|Int|_|) (s: string) = - match Int64.TryParse s with - | true, n -> Some n - | _ -> None - - let (|Fraction|_|) (s: string) = - match s.Split('/') with - | [| Int n; Int d |] -> Fraction.Create(n, d) |> Result.toOption - | [| Int n |] -> Some(Fraction.Raw(n, 1L)) - | _ -> None - - let (|Arith|_|) = - function - | "+" -> Some (+) - | "-" -> Some (-) - | "*" -> Some (*) - | "/" -> - Some(fun a b -> - Fraction.TryDiv(a, b) - |> Result.defaultWith (fun _ -> failwith "Division by zero")) - | _ -> None - - let (|Logic|_|) = - function - | "==" -> Some (=) - | "!=" -> Some (<>) - | ">" -> Some (>) - | "<" -> Some (<) - | ">=" -> Some (>=) - | "<=" -> Some (<=) - | _ -> None - - let run f1 opStr f2 = - match opStr with - | Arith f -> Ok(string (f f1 f2)) - | Logic f -> Ok(if f f1 f2 then "1" else "0") - | _ -> Error $"Invalid operator: {opStr}" - -module Helpers = - open Calculator - let usage = "Usage: ./fraction-math operand1 operator operand2" - - let parseArgs argv = - match argv with - | [| Fraction f1; op; Fraction f2 |] -> Ok(f1, op, f2) - | _ -> Error usage - - let handleResult = - function - | Ok r -> - printfn "%s" r - 0 - | Error m -> - eprintfn "%s" m - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.bind (fun (f1, op, f2) -> Calculator.run f1 op f2) - |> Helpers.handleResult - -``` - -{% endraw %} - -Fraction Math in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/go/index.md b/docs/projects/fraction-math/go/index.md deleted file mode 100644 index be2a27fc1f..0000000000 --- a/docs/projects/fraction-math/go/index.md +++ /dev/null @@ -1,151 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-12 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2025-01-12 -layout: default -tags: -- fraction-math -- go -title: Fraction Math in Go -title1: Fraction -title2: Math in Go ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "os" - "math/big" - "strings" - "strconv" -) - -func die(msg string) { - println(msg) - os.Exit(1) -} - -func main() { - if len(os.Args) != 4 { - die("Usage: ./fraction-math operand1 operator operand2") - } - - o1str := strings.Split(os.Args[1], "/") - if len(o1str) != 2 { - die("Invalid operand: " + os.Args[1]) - } - - o2str := strings.Split(os.Args[3], "/") - if len(o2str) != 2 { - die("Invalid operand: " + os.Args[3]) - } - - operator := os.Args[2] - - a, err := strconv.Atoi(o1str[0]) - if err != nil { - die("Invalid operand: " + os.Args[1]) - } - b, err := strconv.Atoi(o1str[1]) - if err != nil { - die("Invalid operand: " + os.Args[1]) - } - - o1 := big.NewRat(int64(a), int64(b)) - - a, err = strconv.Atoi(o2str[0]) - if err != nil { - die("Invalid operand: " + os.Args[1]) - } - b, err = strconv.Atoi(o2str[1]) - if err != nil { - die("Invalid operand: " + os.Args[1]) - } - - o2 := big.NewRat(int64(a), int64(b)) - - switch operator { - case "+": - println(o1.Add(o1, o2).RatString()) - case "-": - println(o1.Sub(o1, o2).RatString()) - case "*": - println(o1.Mul(o1, o2).RatString()) - case "/": - println(o1.Mul(o1, o2.Inv(o2)).RatString()) - case ">": - if o1.Cmp(o2) == -1 || o1.Cmp(o2) == 0 { - println(0) - } else if o1.Cmp(o2) == 1 { - println(1) - } - case "<": - if o1.Cmp(o2) == 1 { - println(0) - } else if o1.Cmp(o2) == -1 || o1.Cmp(o2) == 0 { - println(1) - } - case "==": - if o1.Cmp(o2) == 0 { - println(1) - } else { - println(0) - } - case "!=": - if o1.Cmp(o2) == 0 { - println(0) - } else { - println(1) - } - case ">=": - if o1.Cmp(o2) == 1 || o1.Cmp(o2) == 0 { - println(1) - } else { - println(0) - } - case "<=": - if o1.Cmp(o2) == -1 || o1.Cmp(o2) == 0 { - println(1) - } else { - println(0) - } - } -} - -``` - -{% endraw %} - -Fraction Math in [Go](/languages/go) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/haskell/index.md b/docs/projects/fraction-math/haskell/index.md deleted file mode 100644 index 79c7d92e2e..0000000000 --- a/docs/projects/fraction-math/haskell/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-18 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-18 -layout: default -tags: -- fraction-math -- haskell -title: Fraction Math in Haskell -title1: Fraction Math -title2: in Haskell ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read -import Data.Bifunctor (second) -import Data.Ratio - -parseOperator :: String -> Maybe (Rational -> Rational -> Rational) -parseOperator op = lookup op operators - where - -- converts relational operations that return bool, to operations that return rationals - 1 for True, 0 for False - relationalToRational f a b = toRational $ fromEnum (f a b) - arithmeticOps = [("+", (+)), ("-", (-)), ("/", (/)), ("*", (*))] - relationalOps = [(">", (>)), ("<", (<)), (">=", (>=)), ("<=", (<=)), ("==", (==)), ("!=", (/=))] - operators = arithmeticOps ++ map (second relationalToRational) relationalOps - -parseFraction :: String -> Maybe Rational -parseFraction s = do - let (num, den) = break (== '/') s - num' <- readMaybe num - den' <- readMaybe (drop 1 den) -- drop 1 for the '/' - return (num' % den') - -applyOperator :: [String] -> Maybe Rational -applyOperator [frac1, op, frac2] = do - operand1 <- parseFraction frac1 - operand2 <- parseFraction frac2 - operator <- parseOperator op - return (operand1 `operator` operand2) -applyOperator _ = Nothing - -rationalToString :: Rational -> String -rationalToString x - | denominator x == 1 = show (numerator x) - | otherwise = show (numerator x) ++ "/" ++ show (denominator x) - -main :: IO () -main = do - args <- getArgs - case applyOperator args of - Just res -> putStrLn (rationalToString res) - Nothing -> putStrLn "Usage: ./fraction-math operand1 operator operand2" - -``` - -{% endraw %} - -Fraction Math in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/index.md b/docs/projects/fraction-math/index.md deleted file mode 100644 index ad6ad56ff9..0000000000 --- a/docs/projects/fraction-math/index.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -date: 2019-10-10 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-18 -layout: default -tags: -- fraction-math -title: Fraction Math -title1: Fraction -title2: Math ---- - - - -Welcome to the Fraction Math page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Languages like python have built-in utilities or functions for working with fractions. -Many of these fractions functions follow a similar pattern across programming languages: -takes a numerator and a denomenator as an attribute. -Perform basic arithmatic and relational operations with operator overloading. - - -## Requirements - -In general, a fractions library should perform the following: - -1. Perform arithmatic operation like multiplications, addition etc. -2. Give output for relational operations like >=, >, == etc. - -More specifically, begin with creating object instance of fraction class with two attributes: -numerator and denomenator.Using operator overloading feature of langauge implement basic arithmatic -and relational operaions. - -For instance `./fraction-math "6/2" "+" "1/4"` would output `13/4` - -In addition, there should be some error handling for situations where the user -doesn't supply any input. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Fraction Math. -In order to keep things simple, we split up the testing as follows: - -- Fractions Valid Tests -- Fractions Invalid Tests - -### Fractions Valid Tests - -| Description | Fraction 1 | Operation | Fraction 2 | Output | -| ----------- | ---------- | --------- | ---------- | ------ | -| Sample Input: Addition | "2/3" | "+" | "4/5" | "22/15" | -| Sample Input: Multiplication | "2/3" | "*" | "4/5" | "8/15" | -| Sample Input: Subtraction | "2/3" | "-" | "4/5" | "-2/15" | -| Sample Input: Division | "2/3" | "/" | "4/5" | "5/6" | -| Sample Input: Equals | "2/3" | "==" | "4/5" | "0" | -| Sample Input: Greater Than | "2/3" | ">" | "4/5" | "0" | -| Sample Input: Less Than | "2/3" | "<" | "4/5" | "1" | -| Sample Input: Greater Than Equals | "2/3" | ">=" | "4/5" | "0" | -| Sample Input: Less Than Equals | "2/3" | "<=" | "4/5" | "1" | -| Sample Input: Not Equals | "2/3" | "!=" | "4/5" | "1" | - -### Fractions Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | - -All of these tests should output the following: - -``` -Usage: ./fraction-math operand1 operator operand2 -``` - - -## Articles - -There are 29 articles: - -- [Fraction Math in ALGOL 60](/projects/fraction-math/algol60) -- [Fraction Math in ALGOL 68](/projects/fraction-math/algol68) -- [Fraction Math in AWK](/projects/fraction-math/awk) -- [Fraction Math in Ada](/projects/fraction-math/ada) -- [Fraction Math in Beef](/projects/fraction-math/beef) -- [Fraction Math in C](/projects/fraction-math/c) -- [Fraction Math in C#](/projects/fraction-math/c-sharp) -- [Fraction Math in C++](/projects/fraction-math/c-plus-plus) -- [Fraction Math in COBOL](/projects/fraction-math/cobol) -- [Fraction Math in Commodore BASIC](/projects/fraction-math/commodore-basic) -- [Fraction Math in Euphoria](/projects/fraction-math/euphoria) -- [Fraction Math in F#](/projects/fraction-math/f-sharp) -- [Fraction Math in Go](/projects/fraction-math/go) -- [Fraction Math in Haskell](/projects/fraction-math/haskell) -- [Fraction Math in Java](/projects/fraction-math/java) -- [Fraction Math in JavaScript](/projects/fraction-math/javascript) -- [Fraction Math in Mathematica](/projects/fraction-math/mathematica) -- [Fraction Math in Modula-2](/projects/fraction-math/modula2) -- [Fraction Math in PHP](/projects/fraction-math/php) -- [Fraction Math in Pascal](/projects/fraction-math/pascal) -- [Fraction Math in PowerShell](/projects/fraction-math/powershell) -- [Fraction Math in Python](/projects/fraction-math/python) -- [Fraction Math in Ruby](/projects/fraction-math/ruby) -- [Fraction Math in Rust](/projects/fraction-math/rust) -- [Fraction Math in Swift](/projects/fraction-math/swift) -- [Fraction Math in Tcl](/projects/fraction-math/tcl) -- [Fraction Math in TypeScript](/projects/fraction-math/typescript) -- [Fraction Math in Visual Basic](/projects/fraction-math/visual-basic) -- [Fraction Math in m4](/projects/fraction-math/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/fraction-math/java/index.md b/docs/projects/fraction-math/java/index.md deleted file mode 100644 index dbdb015c22..0000000000 --- a/docs/projects/fraction-math/java/index.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- fraction-math -- java -title: Fraction Math in Java -title1: Fraction -title2: Math in Java ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class FractionMath { - private static void usage() { - System.out.println("Usage: ./fraction-math operand1 operator operand2"); - System.exit(1); - } - - private record Fraction(int n, int d) implements Comparable { - private Fraction { - if (d == 0) throw new IllegalArgumentException(); - - int gcd = gcd(Math.abs(n), Math.abs(d)); - n /= gcd; - d /= gcd; - - if (d < 0) { - n = -n; - d = -d; - } - } - - static Fraction parse(String s) { - String[] p = s.trim().split("/"); - - if (p.length != 2) { - throw new IllegalArgumentException("Invalid fraction: " + s); - } - - return new Fraction(Integer.parseInt(p[0].trim()), Integer.parseInt(p[1].trim())); - } - - Fraction add(Fraction o) { - return new Fraction(n * o.d + o.n * d, d * o.d); - } - - Fraction sub(Fraction o) { - return new Fraction(n * o.d - o.n * d, d * o.d); - } - - Fraction mul(Fraction o) { - return new Fraction(n * o.n, d * o.d); - } - - Fraction div(Fraction o) { - if (o.n == 0) throw new ArithmeticException("Division by zero"); - return new Fraction(n * o.d, d * o.n); - } - - private static int gcd(int a, int b) { - return b == 0 ? Math.abs(a) : gcd(b, a % b); - } - - @Override - public String toString() { - return n + "/" + d; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (!(obj instanceof Fraction f)) return false; - return n == f.n && d == f.d; - } - - @Override - public int hashCode() { - return 31 * n + d; - } - - @Override - public int compareTo(Fraction o) { - return Long.compare((long) n * o.d, (long) d * o.n); - } - } - - public static void main(String[] args) { - if (args.length != 3) { - usage(); - } - - try { - Fraction a = Fraction.parse(args[0]); - String op = args[1]; - Fraction b = Fraction.parse(args[2]); - - switch (op) { - case "+" -> System.out.println(a.add(b)); - case "-" -> System.out.println(a.sub(b)); - case "*" -> System.out.println(a.mul(b)); - case "/" -> System.out.println(a.div(b)); - - case "==" -> System.out.println(a.equals(b) ? "1" : "0"); - case "!=" -> System.out.println(!a.equals(b) ? "1" : "0"); - case ">" -> System.out.println(a.compareTo(b) > 0 ? "1" : "0"); - case "<" -> System.out.println(a.compareTo(b) < 0 ? "1" : "0"); - case ">=" -> System.out.println(a.compareTo(b) >= 0 ? "1" : "0"); - case "<=" -> System.out.println(a.compareTo(b) <= 0 ? "1" : "0"); - - default -> usage(); - } - - } catch (Exception e) { - usage(); - } - } -} - -``` - -{% endraw %} - -Fraction Math in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/javascript/index.md b/docs/projects/fraction-math/javascript/index.md deleted file mode 100644 index c08957d712..0000000000 --- a/docs/projects/fraction-math/javascript/index.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- fraction-math -- javascript -title: Fraction Math in JavaScript -title1: Fraction Math -title2: in JavaScript ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -"use strict"; - -const USAGE = "Usage: ./fraction-math operand1 operator operand2"; - -class Fraction { - #n; - #d; - - constructor(numerator, denominator) { - if (denominator === 0n) throw new Error("Division by zero"); - - const sign = denominator < 0n ? -1n : 1n; - const common = Fraction.#gcd(numerator, denominator); - - this.#n = (numerator / common) * sign; - this.#d = (denominator / common) * sign; - } - - static #gcd(a, b) { - let x = a < 0n ? -a : a; - let y = b < 0n ? -b : b; - while (y) { - x %= y; - [x, y] = [y, x]; - } - return x; - } - - static parse(str) { - const [num, den] = str.split("/"); - try { - const n = BigInt(num); - const d = den !== undefined ? BigInt(den) : 1n; - return new Fraction(n, d); - } catch { - throw new Error(`Invalid fraction format: ${str}`); - } - } - - add(o) { - return new Fraction(this.#n * o.#d + o.#n * this.#d, this.#d * o.#d); - } - sub(o) { - return new Fraction(this.#n * o.#d - o.#n * this.#d, this.#d * o.#d); - } - mul(o) { - return new Fraction(this.#n * o.#n, this.#d * o.#d); - } - div(o) { - return new Fraction(this.#n * o.#d, this.#d * o.#n); - } - - compare(o) { - const diff = this.#n * o.#d - o.#n * this.#d; - return diff === 0n ? 0 : diff > 0n ? 1 : -1; - } - - toString() { - return `${this.#n}/${this.#d}`; - } -} - -const operators = { - "+": (a, b) => a.add(b), - "-": (a, b) => a.sub(b), - "*": (a, b) => a.mul(b), - "/": (a, b) => a.div(b), - "==": (a, b) => (a.compare(b) === 0 ? 1 : 0), - "!=": (a, b) => (a.compare(b) !== 0 ? 1 : 0), - ">": (a, b) => (a.compare(b) > 0 ? 1 : 0), - "<": (a, b) => (a.compare(b) < 0 ? 1 : 0), - ">=": (a, b) => (a.compare(b) >= 0 ? 1 : 0), - "<=": (a, b) => (a.compare(b) <= 0 ? 1 : 0), -}; - -const run = () => { - const [, , rawA, op, rawB] = process.argv; - - if (!rawA || !op || !rawB || !operators[op]) { - console.error(USAGE); - process.exit(1); - } - - try { - const f1 = Fraction.parse(rawA); - const f2 = Fraction.parse(rawB); - - const result = operators[op](f1, f2); - console.log(result.toString()); - } catch (err) { - console.error(USAGE); - process.exit(1); - } -}; - -run(); - -``` - -{% endraw %} - -Fraction Math in [JavaScript](/languages/javascript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/m4/index.md b/docs/projects/fraction-math/m4/index.md deleted file mode 100644 index 5ef6b17f3c..0000000000 --- a/docs/projects/fraction-math/m4/index.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-22 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2025-08-22 -layout: default -tags: -- fraction-math -- m4 -title: Fraction Math in m4 -title1: Fraction -title2: Math in m4 ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: ./fraction-math operand1 operator operand2 -m4exit(`1')') - -define(`show_error', -`Error: $1 -m4exit(`1')') - -dnl is_valid_fraction(f) -define(`is_valid_fraction', `eval(regexp(`$1', `^\s*-?[0-9]+\(/\s*-?[0-9]+\)?\s*$') >= 0)') - -dnl string_to_fraction(var_name, f) -define(`string_to_fraction', -`define(`idx', index(`$2', `/'))dnl -define(`num', ifelse(eval(idx < 0), 1, `$2', `substr(`$2', 0, idx)'))dnl -define(`den', ifelse(eval(idx < 0), 1, 1, `substr(`$2', incr(idx))'))dnl -fraction_reduce(`$1', num, den)'dnl -) - -dnl set_fraction(var_name, num, den) -define(`set_fraction', `define(`$1_n', $2)define(`$1_d', $3)define(`$1_error', `')') - -dnl set_fraction_error(var_name, error_msg) -define(`set_fraction_error', `define(`$1_error', `$2')') - -dnl fraction_reduce(var_name, n, d) -dnl if d == 0: -dnl var_name.error = "Divide by 0" -dnl else: -dnl g = gcd(abs(n), abs(d)) -dnl if d > 0: -dnl var_name.n, var_name.d = n / g, d / g -dnl else: -dnl var_name.n, var_name.d = -n / g, -d / g -define(`fraction_reduce', -`ifelse($3, 0, `set_fraction_error(`$1', `Divide by 0')', -`define(`g', gcd(abs(`$2'), abs(`$3')))dnl -ifelse(eval($3 > 0), 1, - `set_fraction(`$1', eval($2 / g), eval($3 / g))', - `set_fraction(`$1', eval((0 - $2) / g), eval((0 - $3) / g))'dnl -)'dnl -)'dnl -) - -dnl gcd(a, b) -dnl if a == 0: -dnl Return b -dnl else: -dnl while b != 0: -dnl a, b = b, a % b -dnl Return a -define(`gcd', `ifelse(`$1', 0, `$2', `$2', 0, `$1', `gcd($2, eval($1 % $2))')') - -dnl abs(n) -define(`abs', `ifelse(eval($1 >= 0), 1, eval($1), eval(0 - $1))') - -dnl fraction_math(result_var_name, var_name1, op, var_name2) -define(`fraction_math', -`set_fraction_error(`$1', `')dnl -ifelse( - `$3', `+', `fraction_add($1, $2, $4)', - `$3', `-', `fraction_sub($1, $2, $4)', - `$3', `*', `fraction_mul($1, $2, $4)', - `$3', `/', `fraction_div($1, $2, $4)', - `$3', `==', `fraction_cmp($1, $2, $3, $4)', - `$3', `!=', `fraction_cmp($1, $2, $3, $4)', - `$3', `<', `fraction_cmp($1, $2, $3, $4)', - `$3', `<=', `fraction_cmp($1, $2, $3, $4)', - `$3', `>', `fraction_cmp($1, $2, $3, $4)', - `$3', `>=', `fraction_cmp($1, $2, $3, $4)', - `set_fraction_error(`$1', `Invalid operation "$3"')'dnl -)'dnl -) - -dnl fraction_add(result_varname, f1, f2) -dnl f1.n/f1.d + f2.n/f2.d = (f1.n*f2.d + f2.n*f1.d) / (f1.d*f2.d) -define(`fraction_add', `fraction_reduce(`$1', eval($2_n * $3_d + $3_n * $2_d), eval($2_d * $3_d))') - -dnl fraction_sub(result_varname, f1, f2) -dnl f1.n/f1.d - f2.n/f2.d = (f1.n*f2.d - f2.n*f1.d) / (f1.d*f2.d) -define(`fraction_sub', `fraction_reduce(`$1', eval($2_n * $3_d - $3_n * $2_d), eval($2_d * $3_d))') - -dnl fraction_mul(result_varname, f1, f2) -dnl f1.n/f1.d * f2.n/f2.d = (f1.n*f2.n) / (f1.d*f2.d) -define(`fraction_mul', `fraction_reduce(`$1', eval($2_n * $3_n), eval($2_d * $3_d))') - -dnl fraction_div(result_varname, f1, f2) -dnl (f1.n/f1.d) / (f2.n/f2.d) = (f1.n*f2.d) / (f2.n*f1.d) -define(`fraction_div', `fraction_reduce(`$1', eval($2_n * $3_d), eval($3_n * $2_d))') - -dnl fraction_cmp(result_varname, f1, op, f2) -dnl f1.n/f1.d op f2.n/f2.d = f1.n*f2.d op f2.n*f1.d -define(`fraction_cmp', `define(`$1', eval(($2_n * $4_d) $3 ($4_n * $2_d)))') - -dnl fraction_to_string(varname) -define(`fraction_to_string', `ifdef(`$1', `$1', `$1_n/$1_d')') -divert(0)dnl -ifelse(eval(ARGC < 3 || !is_valid_fraction(ARGV1) || !is_valid_fraction(ARGV3)), 1, `show_usage()')dnl -string_to_fraction(`f1', ARGV1)dnl -ifelse(eval(len(f1_error) > 0), 1, `show_error(f1_error)')dnl -string_to_fraction(`f2', ARGV3)dnl -ifelse(eval(len(f2_error) > 0), 1, `show_error(f2_error)')dnl -fraction_math(`result', `f1', ARGV2, `f2')dnl -ifelse(eval(len(result_error) > 0), 1, `show_error(result_error)')dnl -fraction_to_string(`result') - -``` - -{% endraw %} - -Fraction Math in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/mathematica/index.md b/docs/projects/fraction-math/mathematica/index.md deleted file mode 100644 index 1109e4e0cc..0000000000 --- a/docs/projects/fraction-math/mathematica/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- fraction-math -- mathematica -title: Fraction Math in Mathematica -title1: Fraction Math -title2: in Mathematica ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Most the required behavior is already provided by the ToExpression built-in. - It would be easy to simply print these out in a loop; however, in the spirit of - keeping the mathematical operation separate from its presentation I opted to - return the result as a list explicitly: *) - -fractionMath = Function[{l, o, r}, - ToExpression[(* simply evaluate the string as Mathematica input *) - (* format the three arguments as a single string, parenthesizing the operands for precedence *) - StringTemplate["(``) `` (``)"][l, o, r]]]; - -(* The outer function provides the 'user interface': *) - -fractionMathMain = l \[Function] - Catch[ - Replace[{(* output formatting according to literal requirement *) - (* False/True to be shown as 0/1 *) - False -> 0, True -> 1, - (* fractions to be displayed in-line *) - x_Rational :> StringTemplate["``/``"][Numerator[x], Denominator[x]] - }]@* - fractionMath @@ - (* check input has no empty strings *) - (If[# != "", #, Throw["Usage: ./fraction-math operand1 operator operand2"]] & /@ l)]; - - -(* Valid Tests *) - -Print /@ fractionMathMain /@ { - {"2/3", "+", "4/5"}, - {"2/3", "*", "4/5"}, - {"2/3", "-", "4/5"}, - {"2/3", "/", "4/5"}, - {"2/3", "==", "4/5"}, - {"2/3", ">", "4/5"}, - {"2/3", "<", "4/5"}, - {"2/3", ">=", "4/5"}, - {"2/3", "<=", "4/5"}, - {"2/3", "!=", "4/5"}}; - - -(* Invalid Tests *) - -fractionMathMain[{"", "+", "4/5"}] -``` - -{% endraw %} - -Fraction Math in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/modula2/index.md b/docs/projects/fraction-math/modula2/index.md deleted file mode 100644 index 0387e62998..0000000000 --- a/docs/projects/fraction-math/modula2/index.md +++ /dev/null @@ -1,255 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- fraction-math -- modula2 -title: Fraction Math in Modula-2 -title1: Fraction Math -title2: in Modula-2 ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Modula-2](/languages/modula2) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```modula-2 -MODULE FractionMath; - -FROM STextIO IMPORT WriteString, WriteLn, WriteChar; -FROM NumberIO IMPORT WriteInt, WriteCard; -FROM TextIO IMPORT ReadToken; -FROM ProgramArgs IMPORT NextArg, IsArgPresent, ArgChan; -FROM StrLib IMPORT StrEqual; - -TYPE - Fraction = RECORD - num: INTEGER; - den: INTEGER; - END; - -PROCEDURE Usage; -BEGIN - WriteString("Usage: ./fraction-math operand1 operator operand2"); - WriteLn; -END Usage; - -PROCEDURE ReadArg(VAR s: ARRAY OF CHAR): BOOLEAN; -BEGIN - NextArg; - - IF IsArgPresent() THEN - ReadToken(ArgChan(), s); - RETURN TRUE; - END; - - RETURN FALSE; -END ReadArg; - -PROCEDURE GCD(a, b: INTEGER): INTEGER; -VAR t: INTEGER; -BEGIN - IF a < 0 THEN a := -a END; - IF b < 0 THEN b := -b END; - - WHILE b # 0 DO - t := b; - b := a MOD b; - a := t; - END; - - RETURN a; -END GCD; - -PROCEDURE Normalize(VAR f: Fraction); -VAR g: INTEGER; -BEGIN - IF f.den = 0 THEN - HALT; - END; - - g := GCD(f.num, f.den); - f.num := f.num DIV g; - f.den := f.den DIV g; - - IF f.den < 0 THEN - f.num := -f.num; - f.den := -f.den; - END; -END Normalize; - -PROCEDURE ParseFraction(s: ARRAY OF CHAR; VAR f: Fraction): BOOLEAN; -VAR i, n, d, sign: INTEGER; ok: BOOLEAN; -BEGIN - ok := FALSE; - n := 0; d := 0; sign := 1; - - i := 0; - - (* parse numerator *) - IF s[i] = '-' THEN - sign := -1; INC(i); - END; - - WHILE (s[i] >= '0') & (s[i] <= '9') DO - n := n * 10 + INTEGER(ORD(s[i]) - ORD('0')); - INC(i); - END; - - IF s[i] # '/' THEN RETURN FALSE END; - INC(i); - - (* parse denominator *) - WHILE (s[i] >= '0') & (s[i] <= '9') DO - d := d * 10 + INTEGER(ORD(s[i]) - ORD('0')); - INC(i); - END; - - f.num := sign * n; - f.den := d; - - Normalize(f); - RETURN TRUE; -END ParseFraction; - -PROCEDURE Add(a, b: Fraction): Fraction; -VAR r: Fraction; -BEGIN - r.num := a.num * b.den + b.num * a.den; - r.den := a.den * b.den; - Normalize(r); - RETURN r; -END Add; - -PROCEDURE Sub(a, b: Fraction): Fraction; -VAR r: Fraction; -BEGIN - r.num := a.num * b.den - b.num * a.den; - r.den := a.den * b.den; - Normalize(r); - RETURN r; -END Sub; - -PROCEDURE Mul(a, b: Fraction): Fraction; -VAR r: Fraction; -BEGIN - r.num := a.num * b.num; - r.den := a.den * b.den; - Normalize(r); - RETURN r; -END Mul; - -PROCEDURE Div(a, b: Fraction): Fraction; -VAR r: Fraction; -BEGIN - IF b.num = 0 THEN HALT END; - r.num := a.num * b.den; - r.den := a.den * b.num; - Normalize(r); - RETURN r; -END Div; - -PROCEDURE Cmp(a, b: Fraction): INTEGER; -VAR lhs, rhs: INTEGER; -BEGIN - lhs := a.num * b.den; - rhs := b.num * a.den; - - IF lhs > rhs THEN RETURN 1 END; - IF lhs < rhs THEN RETURN -1 END; - RETURN 0; -END Cmp; - -PROCEDURE Eq(a, b: Fraction): INTEGER; -BEGIN IF Cmp(a,b) = 0 THEN RETURN 1 ELSE RETURN 0 END; END Eq; - -PROCEDURE Ne(a, b: Fraction): INTEGER; -BEGIN IF Cmp(a,b) # 0 THEN RETURN 1 ELSE RETURN 0 END; END Ne; - -PROCEDURE Gt(a, b: Fraction): INTEGER; -BEGIN IF Cmp(a,b) > 0 THEN RETURN 1 ELSE RETURN 0 END; END Gt; - -PROCEDURE Lt(a, b: Fraction): INTEGER; -BEGIN IF Cmp(a,b) < 0 THEN RETURN 1 ELSE RETURN 0 END; END Lt; - -PROCEDURE Ge(a, b: Fraction): INTEGER; -BEGIN IF Cmp(a,b) >= 0 THEN RETURN 1 ELSE RETURN 0 END; END Ge; - -PROCEDURE Le(a, b: Fraction): INTEGER; -BEGIN IF Cmp(a,b) <= 0 THEN RETURN 1 ELSE RETURN 0 END; END Le; - -PROCEDURE PrintFraction(f: Fraction); -BEGIN - WriteInt(f.num, 0); - WriteString("/"); - WriteInt(f.den, 0); - WriteLn; -END PrintFraction; - -VAR - aStr, op, bStr: ARRAY [0..63] OF CHAR; - a, b, r: Fraction; - ok1, ok2, found: BOOLEAN; - -BEGIN - IF ~(ReadArg(aStr) AND ReadArg(op) AND ReadArg(bStr)) THEN - Usage; - RETURN; - END; - - IF ~(ParseFraction(aStr, a) AND ParseFraction(bStr, b)) THEN - Usage; - RETURN; - END; - - found := FALSE; - - IF StrEqual(op, "+") THEN PrintFraction(Add(a, b)) - ELSIF StrEqual(op, "-") THEN PrintFraction(Sub(a, b)) - ELSIF StrEqual(op, "*") THEN PrintFraction(Mul(a, b)) - ELSIF StrEqual(op, "/") THEN PrintFraction(Div(a, b)) - - ELSIF StrEqual(op, "==") THEN WriteInt(Eq(a, b), 1) - ELSIF StrEqual(op, "!=") THEN WriteInt(Ne(a, b), 1) - ELSIF StrEqual(op, ">") THEN WriteInt(Gt(a, b), 1) - ELSIF StrEqual(op, "<") THEN WriteInt(Lt(a, b), 1) - ELSIF StrEqual(op, ">=") THEN WriteInt(Ge(a, b), 1) - ELSIF StrEqual(op, "<=") THEN WriteInt(Le(a, b), 1) - ELSE Usage END; - -END FractionMath. - -``` - -{% endraw %} - -Fraction Math in [Modula-2](/languages/modula2) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/pascal/index.md b/docs/projects/fraction-math/pascal/index.md deleted file mode 100644 index 78120a0929..0000000000 --- a/docs/projects/fraction-math/pascal/index.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- fraction-math -- pascal -title: Fraction Math in Pascal -title1: Fraction Math -title2: in Pascal ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program FractionMath; - -{$mode objfpc}{$H+}{$modeswitch advancedrecords} - -uses - Math, - SysUtils; - -type - - { TFraction } - - TFraction = record - Numerator, Denominator: int64; - - procedure Reduce; - function ToString: string; - class operator +(const A, B: TFraction): TFraction; - class operator -(const A, B: TFraction): TFraction; - class operator *(const A, B: TFraction): TFraction; - class operator /(const A, B: TFraction): TFraction; - class operator =(const A, B: TFraction): boolean; - class operator <>(const A, B: TFraction): boolean; - class operator <(const A, B: TFraction): boolean; - class operator <=(const A, B: TFraction): boolean; - class operator >(const A, B: TFraction): boolean; - class operator >=(const A, B: TFraction): boolean; - end; - -procedure TFraction.Reduce; inline; -var - Divisor, GcdA, GcdB, Temp: int64; -begin - if Denominator = 0 then - raise Exception.Create('Denominator cannot be zero'); - - if Numerator = 0 then - begin - Denominator := 1; - Exit; - end; - - if Denominator < 0 then - begin - Denominator := -Denominator; - Numerator := -Numerator; - end; - - GcdA := Abs(Numerator); - GcdB := Denominator; - - while GcdB <> 0 do - begin - Temp := GcdB; - GcdB := GcdA mod GcdB; - GcdA := Temp; - end; - - Divisor := GcdA; - - // If the GCD is not 1, then simplify the top and the bottom. - if Divisor > 1 then - begin - Numerator := Numerator div Divisor; - Denominator := Denominator div Divisor; - end; -end; - -function TFraction.ToString: string; -begin - Result := Format('%d/%d', [Numerator, Denominator]); -end; - -class operator TFraction.+(const A, B: TFraction): TFraction; -begin - Result.Numerator := A.Numerator * B.Denominator + B.Numerator * A.Denominator; - Result.Denominator := A.Denominator * B.Denominator; - Result.Reduce; -end; - -class operator TFraction.-(const A, B: TFraction): TFraction; -begin - Result.Numerator := A.Numerator * B.Denominator - B.Numerator * A.Denominator; - Result.Denominator := A.Denominator * B.Denominator; - Result.Reduce; -end; - -class operator TFraction.*(const A, B: TFraction): TFraction; -begin - Result.Numerator := A.Numerator * B.Numerator; - Result.Denominator := A.Denominator * B.Denominator; - Result.Reduce; -end; - -class operator TFraction./(const A, B: TFraction): TFraction; -begin - if B.Numerator = 0 then - raise Exception.Create('Division by zero fraction'); - - Result.Numerator := A.Numerator * B.Denominator; - Result.Denominator := A.Denominator * B.Numerator; - Result.Reduce; -end; - -class operator TFraction.=(const A, B: TFraction): boolean; -begin - Result := A.Numerator * B.Denominator = B.Numerator * A.Denominator; -end; - -class operator TFraction.<>(const A, B: TFraction): boolean; -begin - Result := not (A = B); -end; - -class operator TFraction.<(const A, B: TFraction): boolean; -begin - Result := A.Numerator * B.Denominator < B.Numerator * A.Denominator; -end; - -class operator TFraction.>=(const A, B: TFraction): boolean; -begin - Result := not (A < B); -end; - -class operator TFraction.>(const A, B: TFraction): boolean; -begin - Result := B < A; -end; - -class operator TFraction.<=(const A, B: TFraction): boolean; -begin - Result := not (B < A); -end; - -function ParseFraction(const S: string): TFraction; -var - Parts: TStringArray; -begin - Parts := S.Trim.Split(['/']); - if Length(Parts) <> 2 then - raise Exception.CreateFmt('Invalid fraction format "%s". Expected "num/den"', [S]); - - if not TryStrToInt64(Parts[0].Trim, Result.Numerator) then - raise Exception.Create('Invalid numerator'); - - if not TryStrToInt64(Parts[1].Trim, Result.Denominator) then - raise Exception.Create('Invalid denominator'); - - if Result.Denominator = 0 then - raise Exception.Create('Denominator cannot be zero'); - - Result.Reduce; -end; - -procedure ShowUsage; -begin - Writeln('Usage: ./fraction-math operand1 operator operand2'); - Halt(1); -end; - -function PerformOperation(const Left: TFraction; const Op: string; -const Right: TFraction): string; -begin - case Op of - '+': Result := (Left + Right).ToString; - '-': Result := (Left - Right).ToString; - '*': Result := (Left * Right).ToString; - '/': Result := (Left / Right).ToString; - '==': Result := BoolToStr(Left = Right, '1', '0'); - '!=': Result := BoolToStr(Left <> Right, '1', '0'); - '<': Result := BoolToStr(Left < Right, '1', '0'); - '<=': Result := BoolToStr(Left <= Right, '1', '0'); - '>': Result := BoolToStr(Left > Right, '1', '0'); - '>=': Result := BoolToStr(Left >= Right, '1', '0'); - else - raise Exception.CreateFmt('Unknown operator: "%s"', [Op]); - end; -end; - - -var - Op: string; - LeftOperand, RightOperand: TFraction; -begin - if ParamCount <> 3 then - ShowUsage; - - try - LeftOperand := ParseFraction(ParamStr(1)); - Op := ParamStr(2).Trim; - RightOperand := ParseFraction(ParamStr(3)); - - Writeln(PerformOperation(LeftOperand, &Op, RightOperand)); - except - on E: Exception do - ShowUsage; - end; - -end. - -``` - -{% endraw %} - -Fraction Math in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/php/index.md b/docs/projects/fraction-math/php/index.md deleted file mode 100644 index 19da598a19..0000000000 --- a/docs/projects/fraction-math/php/index.md +++ /dev/null @@ -1,271 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- fraction-math -- php -title: Fraction Math in PHP -title1: Fraction -title2: Math in PHP ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_fraction($str_value) -{ - // Split numerator and denonimator - $str_parts = explode("/", $str_value, 2); - - // Parse numerator. Exit if numerator invalid - $num = parse_int($str_parts[0]); - if ($num === FALSE) - { - return FALSE; - } - - // Assume denominator is 1 - $den = 1; - - // If there is denominator, - if (count($str_parts) > 1) - { - // Parse denominator. Exit if denominator invalid - $den = parse_int($str_parts[1]); - if ($den === FALSE) - { - return FALSE; - } - } - - return new Fraction($num, $den); -} - -class Fraction -{ - public function __construct(public int $num, public int $den) - { - $this->num = $num; - $this->den = $den; - } - - // Fraction addition - // n1/d1 + n2/d2 = (n1*d2 + n2*d1) / (d1*d2) - public function add(Fraction $other): Fraction - { - return reduce( - $this->num * $other->den + $other->num * $this->den, - $this->den * $other->den - ); - } - - // Fraction subtraction - // n1/d1 - n2/d2 = (n1*d2 - n2*d1) / (d1*d2) - public function sub(Fraction $other): Fraction - { - return reduce( - $this->num * $other->den - $other->num * $this->den, - $this->den * $other->den - ); - } - - // Fraction multiplication - // n1/d1 * n2/d2 = (n1*n2) / (d1*d2) - public function mult(Fraction $other): Fraction - { - return reduce($this->num * $other->num, $this->den * $other->den); - } - - // Fraction division - // (n1/d1) / (n2/d2) = (n1*d2) / (n2*d1) - public function div(Fraction $other): Fraction - { - return reduce($this->num * $other->den, $other->num * $this->den); - } - - // Fraction comparison - // n1/d1 OP n2/d2 = n1*d2 OP n2*d1 - public function cmp(Fraction $other): int - { - return $this->num * $other->den - $other->num * $this->den; - } - - // Show fraction - public function show() - { - echo "{$this->num}/{$this->den}\n"; - } -} - -// Fraction reduction -function reduce($num, $den) -{ - if ($den == 0) - { - die("Division by 0"); - } - - // Reduce by dividing numerator and denominator by greatest common denominator, - // and adjust sign of numerator and denominator as follows: - // - // n d sign n sign d - // + + + + - // + - - + - // - + - + - // - - + + - $den_sign = ($den > 0) ? 1 : -1; - $g = gcd($num, $den); - return new Fraction(intdiv($den_sign * $num, $g), intdiv(abs($den), $g)); -} - -// Greatest common denominator -function gcd($a, $b) -{ - $a = abs($a); - $b = abs($b); - while ($b != 0) - { - $t = $b; - $b = $a % $b; - $a = $t; - } - - return $a; -} - -// Do fraction math -function fraction_math(Fraction $f1, Fraction $f2, string $op): Fraction|bool -{ - switch ($op) - { - case "+": - return $f1->add($f2); - case "-": - return $f1->sub($f2); - case "*": - return $f1->mult($f2); - case "/": - return $f1->div($f2); - case ">": - return $f1->cmp($f2) > 0; - case ">=": - return $f1->cmp($f2) >= 0; - case "<": - return $f1->cmp($f2) < 0; - case "<=": - return $f1->cmp($f2) <= 0; - case "==": - return $f1->cmp($f2) == 0; - case "!=": - return $f1->cmp($f2) != 0; - default: - die("Invalid operator $op"); - } -} - -// Show fraction result -function show_fraction_result(Fraction|int $value) -{ - if (gettype($value) == "object") - { - $value->show(); - } - else - { - echo "$value\n"; - } -} - -// Exit if too few arguments or 2nd argument is empty -if (count($argv) < 4 || empty($argv[2])) -{ - usage(); -} - -// Parse 1st and 3rd arguments. Exit if invalid -$f1 = parse_fraction($argv[1]); -$f2 = parse_fraction($argv[3]); -if ($f1 === FALSE || $f2 == FALSE) -{ - usage(); -} - -// Do fraction math and show result -$op = $argv[2]; -$result = fraction_math($f1, $f2, $op); -show_fraction_result($result); - -``` - -{% endraw %} - -Fraction Math in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/powershell/index.md b/docs/projects/fraction-math/powershell/index.md deleted file mode 100644 index 747c9feed4..0000000000 --- a/docs/projects/fraction-math/powershell/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-07 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2025-07-07 -layout: default -tags: -- fraction-math -- powershell -title: Fraction Math in PowerShell -title1: Fraction Math -title2: in PowerShell ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: ./fraction-math operand1 operator operand2" - Exit 1 -} - -class Fraction : IComparable { - [int]$Num - [int]$Den - - Fraction([int]$n, [int]$d) { - if ($d -lt 0) { - $n = -$n - $d = -$d - } - - $g = [Fraction]::Gcd($n, $d) - $this.Num = [Math]::Floor($n / $g) - $this.Den = [Math]::Floor($d / $g) - } - - static [int] Gcd([int]$a, [int]$b) { - if (-not $a) { - return $b - } - - while ($b) { - $a, $b = $b, ($a % $b) - } - - return $a - } - - static [Fraction] Parse([string]$str) { - $parts = $str.Split('/') - $d = 1 - $n = [int]::Parse($parts[0]) - if ($parts.Length -eq 2) { - $d = [int]::Parse($parts[1]) - } elseif ($parts.Length -gt 2) { - throw "Invalid format" - } - - return [Fraction]::new($n, $d) - } - - [string] ToString() { - return "$($this.Num)/$($this.Den)" - } - - [bool] Equals([object]$other) { - return $this.Num -eq $other.Num -and $this.Den -eq $other.Den - } - - # n1/d1 OP n2/d2 = n1*d2 OP n2*d1 - [int] CompareTo([object]$other) { - return $this.Num * $other.Den - $other.Num * $this.Den - } - - # n1/d1 +/- n2/d2 = (n1*d2 +/- n2*d1) / (d1*d2) - static [Fraction] op_Addition([Fraction]$lhs, [Fraction]$rhs) { - return [Fraction]::new($lhs.Num * $rhs.Den + $rhs.Num * $lhs.Den, $lhs.Den * $rhs.Den) - } - - static [Fraction] op_Subtraction([Fraction]$lhs, [Fraction]$rhs) { - return [Fraction]::new($lhs.Num * $rhs.Den - $rhs.Num * $lhs.Den, $lhs.Den * $rhs.Den) - } - - # n1/d1 * n2/d2 = (n1*n2) / (d1*d2) - static [Fraction] op_Multiply([Fraction]$lhs, [Fraction]$rhs) { - return [Fraction]::new($lhs.Num * $rhs.Num, $lhs.Den * $rhs.Den) - } - - # (n1/d1) / (n2/d2) = (n1*d2) / (n2*d1) - static [Fraction] op_Division([Fraction]$lhs, [Fraction]$rhs) { - return [Fraction]::new($lhs.Num * $rhs.Den, $rhs.Num * $lhs.Den) - } -} - -function Invoke-FractionMath([Fraction]$frac1, [string]$op, [Fraction]$frac2) { - switch ($op) { - "+" { return $frac1 + $frac2 } - "-" { return $frac1 - $frac2 } - "*" { return $frac1 * $frac2 } - "/" { return $frac1 / $frac2 } - "==" { return $frac1 -eq $frac2 } - "!=" { return $frac1 -ne $frac2 } - ">" { return $frac1 -gt $frac2 } - ">=" { return $frac1 -ge $frac2 } - "<" { return $frac1 -lt $frac2 } - "<=" { return $frac1 -le $frac2 } - default { throw "Invalid operation" } - } -} - -if ($args.Length -lt 3) { - Show-Usage -} - -try { - $frac1 = [Fraction]::Parse($args[0]) - $frac2 = [Fraction]::Parse($args[2]) -} catch { - Show-Usage -} - -$op = $args[1] -$result = Invoke-FractionMath $frac1 $op $frac2 -if ($result -is [bool]) { - Write-Output ([int]$result) -} else { - Write-Output "$result" -} - -``` - -{% endraw %} - -Fraction Math in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/python/index.md b/docs/projects/fraction-math/python/index.md deleted file mode 100644 index 0c680da924..0000000000 --- a/docs/projects/fraction-math/python/index.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Niraj Kamdar -- rzuckerm -date: 2019-10-16 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- fraction-math -- python -title: Fraction Math in Python -title1: Fraction Math -title2: in Python ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import operator -import sys -from fractions import Fraction - -d = { - "+": operator.add, - "-": operator.sub, - "*": operator.mul, - "/": operator.truediv, - "==": lambda x, y: int(operator.eq(x, y)), - "<": lambda x, y: int(operator.lt(x, y)), - ">": lambda x, y: int(operator.gt(x, y)), - "<=": lambda x, y: int(operator.le(x, y)), - ">=": lambda x, y: int(operator.ge(x, y)), - "!=": lambda x, y: int(operator.ne(x, y)), -} - - -def main(args): - if len(args) != 3: - print("Usage: ./fraction-math operand1 operator operand2") - sys.exit(1) - else: - try: - o1 = Fraction(args[0]) - except ValueError: - print(f"Invalid operand: {args[0]}") - try: - o2 = Fraction(args[2]) - except ValueError: - print(f"Invalid operand: {args[2]}") - try: - print(d[args[1]](o1, o2)) - except KeyError: - print(f"Invalid operator: {args[1]}") - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Fraction Math in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Niraj Kamdar - -This article was written by: - -- Jeremy Grifski -- Niraj Kamdar -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's first take a look at the solution. - -### Imports - -In our sample, we import three standard library utilities: - -```python -import operator -import sys -from fractions import Fraction -``` - -Here, we have imported `sys` for taking arguments from console. `operator` are to perform artithmatic and relational operation. `Fraction` class provide various methods for working with fractions. - -### Mapping operator - -```python -d = { - "+": operator.add, - "-": operator.sub, - "*": operator.mul, - "/": operator.truediv, - "==": lambda x, y: int(operator.eq(x, y)), - "<": lambda x, y: int(operator.lt(x, y)), - ">": lambda x, y: int(operator.gt(x, y)), - "<=": lambda x, y: int(operator.le(x, y)), - ">=": lambda x, y: int(operator.ge(x, y)), - "!=": lambda x, y: int(operator.ne(x, y)), -} -``` - -Here, we are mapping operator entered in the string to actual operator method so that `Fraction class` can perform that. - -### Check number of arguments - -Our `main` function takes arguments as parameter. - -```python -def main(args): - if len(args) != 3: - print("Usage: ./fraction-math operand1 operator operand2") - sys.exit(1) -``` - -Here, we check if number of arguments entered are three, if it's not then print `Usage: python fraction.py operand1 operator operand2` on console and exit. - -### Perform operation - -```python - else: - try: - o1 = Fraction(args[0]) - except ValueError: - print(f"Invalid operand: {args[0]}") - try: - o2 = Fraction(args[2]) - except ValueError: - print(f"Invalid operand: {args[2]}") - try: - print(d[args[1]](o1, o2)) - except KeyError: - print(f"Invalid operator: {args[1]}") -``` - -Now, we check if we can convert entered `args` into `Fraction` type if we can't then we print `Invalid operand: (entered operand)` on console. After that we check if operator is valid and if it's not then we print `Invalid operator: (entered operator)` on console. If everything is good then it prints desired output on console - -### Taking arguments from console - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -Here, `sys.argv` contains arguments passed from the console. We know that first argument is name of file itself. -so, all we need is arguments that are passed after that. We then give it to the `main` function. - - -## How to Run the Solution - -To run the fractions operation in python program, grab a copy of the `fractions.py` file -from GitHub. After that, get the latest version of python interpreter. Now, all you have to -do is run the following from the command line: - -```console -python fraction.py "1/4" "+" "5/8" -``` - -Alternatively, you can always copy the source code into an online python interpreter. Just make sure you pass some input to your program before you run it. diff --git a/docs/projects/fraction-math/ruby/index.md b/docs/projects/fraction-math/ruby/index.md deleted file mode 100644 index 02aa8f9175..0000000000 --- a/docs/projects/fraction-math/ruby/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Ebtisam Jelani -- Ștefan-Iulian Alecu -date: 2025-10-31 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- fraction-math -- ruby -title: Fraction Math in Ruby -title1: Fraction -title2: Math in Ruby ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -class Fraction - attr_reader :numerator, :denominator - - def initialize(numerator, denominator) - @numerator = numerator - @denominator = denominator - end - - def to_r - Rational(numerator, denominator) - end - - def operate(other, op) - a = to_r - b = other.to_r - - case op - when "+" then (a + b).to_s - when "-" then (a - b).to_s - when "*" then (a * b).to_s - when "/" then (a / b).to_s - end - end - - def compare(other, op) - a = to_r - b = other.to_r - - case op - when "==" then a == b - when "!=" then a != b - when ">" then a > b - when "<" then a < b - when ">=" then a >= b - when "<=" then a <= b - end - end -end - -a, op, b = ARGV -abort("Usage: ./fraction-math operand1 operator operand2") unless a && op && b - -num1, den1 = a.split("/").map(&:to_i) -num2, den2 = b.split("/").map(&:to_i) - -lhs = Fraction.new(num1, den1) -rhs = Fraction.new(num2, den2) - -result = lhs.operate(rhs, op) - -if !result.nil? - puts result -else - cmp = lhs.compare(rhs, op) - - if !cmp.nil? - puts cmp ? 1 : 0 - else - puts "Invalid operator" - end -end - -``` - -{% endraw %} - -Fraction Math in [Ruby](/languages/ruby) was written by: - -- Ebtisam Jelani -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/rust/index.md b/docs/projects/fraction-math/rust/index.md deleted file mode 100644 index 3a176c29fd..0000000000 --- a/docs/projects/fraction-math/rust/index.md +++ /dev/null @@ -1,261 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-12 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- fraction-math -- rust -title: Fraction Math in Rust -title1: Fraction -title2: Math in Rust ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::fmt; -use std::ops; -use std::cmp::Ordering; - -fn usage() -> ! { - println!("Usage: ./fraction-math operand1 operator operand2"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_fraction(s: &str) -> Option { - // Parse numerator, denonimator, and remainder - let parts: Vec::Err>> = s.split('/') - .map(parse_int) - .collect(); - - // Return None if numerator or denominator invalid or there was a remainder - // Return numerator with a denominator of 1 if just numerator - // Otherwise numerator and denominator - let num_parts = parts.len(); - match parts.iter().any(|s| s.is_err()) || num_parts > 2 { - true => None, - false => { - let num: i32 = parts[0].clone().unwrap(); - let den: i32 = if num_parts < 2 { 1 } else { parts[1].clone().unwrap() }; - Some(Fraction::new(num, den)) - }, - } -} - -#[derive(Copy, Clone)] -struct Fraction { - num: i32, - den: i32, -} - -impl Fraction { - // Create new fraction - fn new(num: i32, den: i32) -> Self { - Self {num: num, den: den} - } - - // Fraction comparison: - // n1/d1 OP n2/d2 = n1*d2 OP n2*d1 - fn compare(&self, other: &Self) -> i32 { - self.num * other.den - other.num * self.den - } -} - -impl fmt::Debug for Fraction { - // Show fraction - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}/{}", self.num, self.den) - } -} - -impl ops::Add for Fraction { - type Output = Self; - - // Add fractions: - // n1/d1 + n2/d2 = (n1*d2 + n2*d1) / (d1*d2) - fn add(self, other: Self) -> Self { - reduce( - self.num * other.den + other.num * self.den, - self.den * other.den - ) - } -} - -impl ops::Sub for Fraction { - type Output = Self; - - // Subtract fractions: - // n1/d1 - n2/d2 = (n1*d2 - n2*d1) / (d1*d2) - fn sub(self, other: Self) -> Self { - reduce( - self.num * other.den - other.num * self.den, - self.den * other.den - ) - } -} - -impl ops::Mul for Fraction { - type Output = Self; - - // Mulitply fractions: - // n1/d1 * n2/d2 = (n1*n2) / (d1*d2) - fn mul(self, other: Self) -> Self { - reduce(self.num * other.num, self.den * other.den) - } -} - -impl ops::Div for Fraction { - type Output = Self; - - // Divide fractions: - // (n1/d1) / (n2/d2) = (n1*d2) / (n2*d1) - fn div(self, other: Self) -> Self { - reduce(self.num * other.den, self.den * other.num) - } -} - -impl PartialOrd for Fraction { - // Fraction comparison for ordering - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.compare(other).cmp(&0)) - } -} - -impl PartialEq for Fraction { - // Fraction comparison for equality - fn eq(&self, other: &Self) -> bool { - self.compare(other) == 0 - } -} - -// Fraction reduction -fn reduce(num: i32, den: i32) -> Fraction { - if den == 0 { - panic!("Division by 0"); - } - - // Reduce by dividing numerator and denominator by greatest common denominator, - // and adjust sign of numerator and denominator as follows: - // - // n d sign n sign d - // + + + + - // + - - + - // - + - + - // - - + + - let den_sign: i32 = if den > 0 { 1 } else { -1 }; - let g: i32 = gcd(num, den); - Fraction::new(den_sign * num / g, den.abs() / g) -} - -// Greatest common denominator -fn gcd(a: i32, b: i32) -> i32 { - let mut a: i32 = a.abs(); - let mut b: i32 = b.abs(); - while b != 0 { - (a, b) = (b, a % b); - } - - a -} - -// Fraction result -enum FractionResult { - Frac(Fraction), - Bool(bool), -} - -impl fmt::Debug for FractionResult { - // Show fraction or boolean - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Frac(fraction) => write!(f, "{fraction:?}"), - Self::Bool(boolean) => write!(f, "{}", *boolean as u8), - } - } -} - -// Do fraction math -fn fraction_math(f1: Fraction, f2: Fraction, op: String) -> FractionResult { - let op: &str = &op[..]; - match op { - "+" => FractionResult::Frac(f1 + f2), - "-" => FractionResult::Frac(f1 - f2), - "*" => FractionResult::Frac(f1 * f2), - "/" => FractionResult::Frac(f1 / f2), - ">" => FractionResult::Bool(f1 > f2), - ">=" => FractionResult::Bool(f1 >= f2), - "<" => FractionResult::Bool(f1 < f2), - "<=" => FractionResult::Bool(f1 <= f2), - "==" => FractionResult::Bool(f1 == f2), - "!=" => FractionResult::Bool(f1 != f2), - _ => panic!("Invalid operation {op}") - } -} - -fn main() { - let mut args = args().skip(1); - - // Parse 1st command-line argument - let frac1 = args - .next() - .and_then(|s| parse_fraction(&s)) - .unwrap_or_else(|| usage()); - - // Get 2nd command-line argument - let op = args - .next() - .unwrap_or_else(|| usage()); - - // Parse 3rd command-line argument - let frac2 = args - .next() - .and_then(|s| parse_fraction(&s)) - .unwrap_or_else(|| usage()); - - // Do fraction math and show result - let result: FractionResult = fraction_math(frac1, frac2, op); - println!("{result:?}"); -} - -``` - -{% endraw %} - -Fraction Math in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/swift/index.md b/docs/projects/fraction-math/swift/index.md deleted file mode 100644 index 489a0e5682..0000000000 --- a/docs/projects/fraction-math/swift/index.md +++ /dev/null @@ -1,206 +0,0 @@ ---- -authors: -- Zapnuk -date: 2020-10-01 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2020-10-01 -layout: default -tags: -- fraction-math -- swift -title: Fraction Math in Swift -title1: Fraction Math -title2: in Swift ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -// for System.exit() -import Foundation - - -/* - Implementation of the Euclid's Algorithm. - Used to simplify the fractions during initialization -*/ -func gcd(_ a: Int, _ b:Int) -> Int { - var a = a >= 0 ? a : -a - var b = b - var tmp = 0 - while b != 0 { - tmp = b - b = a % b - a = tmp - } - return a -} - -/* - Used for Type conversion Bool => Int -*/ -extension Bool { - var intValue: Int { - return self ? 1 : 0 - } -} - -struct IntFraction { - var numerator, denominator: Int - - init(_ num:Int, _ denom:Int) { - guard denom != 0 else { - print("Error: Denominator cannot be 0") - exit(0) - } - - var num = num - if denom < 0 { - num = -num - } - let gcd_ = gcd(num, denom) - numerator = num / gcd_ - denominator = denom / gcd_ - } - - init?(fromString str:String) { - let parts = str.components(separatedBy: "/") - guard parts.count == 2, let num = Int(parts[0]), let denom = Int(parts[1]) else { - return nil - } - - self.init(num, denom) - } - - - static func +(lhs: IntFraction, rhs: IntFraction) -> IntFraction { - let top = lhs.numerator*rhs.denominator + rhs.numerator*lhs.denominator - let bottom = lhs.denominator*rhs.denominator - return IntFraction(top, bottom) - } - - static func -(lhs: IntFraction, rhs: IntFraction) -> IntFraction { - let top = lhs.numerator*rhs.denominator - rhs.numerator*lhs.denominator - let bottom = lhs.denominator*rhs.denominator - return IntFraction(top, bottom) - } - - static func *(lhs: IntFraction, rhs: IntFraction) -> IntFraction { - return IntFraction(lhs.numerator*rhs.numerator, lhs.denominator*rhs.denominator) - } - - static func /(lhs: IntFraction, rhs: IntFraction) -> IntFraction { - let top = lhs.numerator*rhs.denominator - let bottom = lhs.denominator*rhs.numerator - return IntFraction(top, bottom); - } - - static func ==(lhs: IntFraction, rhs: IntFraction) -> Bool { - let res = lhs.numerator * rhs.denominator - rhs.numerator * lhs.denominator - return res == 0 - } - - static func >(lhs: IntFraction, rhs: IntFraction) -> Bool { - let res = lhs.numerator * rhs.denominator - rhs.numerator * lhs.denominator - return res > 0 - } - - static func <(lhs: IntFraction, rhs: IntFraction) -> Bool { - let res = lhs.numerator * rhs.denominator - rhs.numerator * lhs.denominator - return res < 0 - } - - static func >=(lhs: IntFraction, rhs: IntFraction) -> Bool { - return !(lhs < rhs) - } - - static func <=(lhs: IntFraction, rhs: IntFraction) -> Bool { - return !(lhs > rhs) - } - - static func !=(lhs: IntFraction, rhs: IntFraction) -> Bool { - return !(lhs == rhs) - } -} - - -/* - Check validity of command line arguments -*/ -guard CommandLine.argc == 4 else { - print("Usage: \(CommandLine.arguments[0]) operand1 operator operand2") - exit(0) -} -guard let operand1 = IntFraction(fromString: CommandLine.arguments[1]), let operand2 = IntFraction(fromString: CommandLine.arguments[3]) else { - print("Invalid operand. Usage: a/b => 3/4") - exit(0) -} - -let op = CommandLine.arguments[2] -switch op { -case "+": - let res = operand1 + operand2 - print("\(res.numerator)/\(res.denominator)") -case "-": - let res = operand1 - operand2 - print("\(res.numerator)/\(res.denominator)") -case "*": - let res = operand1 * operand2 - print("\(res.numerator)/\(res.denominator)") -case "/": - let res = operand1 / operand2 - print("\(res.numerator)/\(res.denominator)") -case "==": - let res = operand1 == operand2 - print("\(res.intValue)") -case ">": - let res = operand1 > operand2 - print("\(res.intValue)") -case "<": - let res = operand1 < operand2 - print("\(res.intValue)") -case ">=": - let res = operand1 >= operand2 - print("\(res.intValue)") -case "<=": - let res = operand1 <= operand2 - print("\(res.intValue)") -case "!=": - let res = operand1 != operand2 - print("\(res.intValue)") -default: - print("No matching operation for symbol: '\(op)'") - exit(0) -} -``` - -{% endraw %} - -Fraction Math in [Swift](/languages/swift) was written by: - -- Zapnuk - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/tcl/index.md b/docs/projects/fraction-math/tcl/index.md deleted file mode 100644 index 891cd0911b..0000000000 --- a/docs/projects/fraction-math/tcl/index.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- fraction-math -- tcl -title: Fraction Math in Tcl -title1: Fraction -title2: Math in Tcl ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -oo::class create Fraction { - variable numer denom - - constructor {fractionStr} { - if {[regexp {^\s*(-?\d+)\s*/\s*(\d+)\s*$} $fractionStr -> n d]} { - # NUM/DEN format - } elseif {[regexp {^\s*(-?\d+)$} $fractionStr -> n]} { - # Integer format - set n $n - set d 1 - } else { - error "Invalid fraction: $fractionStr" - } - - set numer [expr {$n}] - set denom [expr {$d}] - - if {$denom == 0} { error "Denominator cannot be zero" } - - set a [expr {abs($numer)}] - set b [expr {abs($denom)}] - while {$b != 0} { - set t $b - set b [expr {$a % $b}] - set a $t - } - set g $a - - set numer [expr {($numer / $g) * ($denom < 0 ? -1 : 1)}] - set denom [expr {abs($denom) / $g}] - } - - method numer {} {return $numer} - method denom {} {return $denom} - - method print {} { return ($denom == 1) ? "$numer" : "$numer/$denom" } - - method _binOp {other op} { - set on [$other numer] - set od [$other denom] - switch -- $op { - + {set n [expr {$numer * $od + $on * $denom}]; set d [expr {$denom * $od}]} - - {set n [expr {$numer * $od - $on * $denom}]; set d [expr {$denom * $od}]} - * {set n [expr {$numer * $on}]; set d [expr {$denom * $od}]} - / { - if {$on == 0} { error "Division by zero" } - set n [expr {$numer * $od}] - set d [expr {$denom * $on}] - } - } - return [Fraction new "$n/$d"] - } - - method add {other} {return [my _binOp $other +]} - method sub {other} {return [my _binOp $other -]} - method mult {other} {return [my _binOp $other *]} - method div {other} {return [my _binOp $other /]} - - method _cross {other} { - set on [$other numer] - set od [$other denom] - return [expr {$numer * $od - $on * $denom}] - } - - method eq {other} {return [expr {[my _cross $other] == 0}]} - method ne {other} {return [expr {[my _cross $other] != 0}]} - method lt {other} {return [expr {[my _cross $other] < 0}]} - method le {other} {return [expr {[my _cross $other] <= 0}]} - method gt {other} {return [expr {[my _cross $other] > 0}]} - method ge {other} {return [expr {[my _cross $other] >= 0}]} -} - -if {[llength $argv] != 3} { - puts "Usage: ./fraction-math operand1 operator operand2" - exit 1 -} - -set op1 [string trim [lindex $argv 0]] -set oper [string trim [lindex $argv 1]] -set op2 [string trim [lindex $argv 2]] - -if {[catch {set f1 [Fraction new $op1]} err]} { - puts "Error: $err" - exit 1 -} -if {[catch {set f2 [Fraction new $op2]} err]} { - puts "Error: $err" - exit 1 -} - -set opMap [dict create \ - + add - sub * mult / div \ - == eq != ne > gt < lt >= ge <= le] - -if {![dict exists $opMap $oper]} { - puts "Unknown operator: $oper" - exit 1 -} - -set result [$f1 [dict get $opMap $oper] $f2] - -if {[lsearch -exact {+ - * /} $oper] != -1} { - puts [$result print] -} else { - puts $result -} - - -``` - -{% endraw %} - -Fraction Math in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/typescript/index.md b/docs/projects/fraction-math/typescript/index.md deleted file mode 100644 index 2575824f25..0000000000 --- a/docs/projects/fraction-math/typescript/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- fraction-math -- typescript -title: Fraction Math in TypeScript -title1: Fraction Math -title2: in TypeScript ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -"use strict"; - -const USAGE = "Usage: ./fraction-math operand1 operator operand2"; - -class Fraction { - private n: number; - private d: number; - - constructor(numerator: number, denominator: number) { - if (denominator === 0) { - throw new Error("Division by zero"); - } - - const sign = denominator < 0 ? -1 : 1; - const common = Fraction.gcd(numerator, denominator); - - this.n = (numerator / common) * sign; - this.d = (denominator / common) * sign; - } - - static gcd(a: number, b: number): number { - let x = Math.abs(a); - let y = Math.abs(b); - - while (y !== 0) { - const tmp = x % y; - x = y; - y = tmp; - } - - return x; - } - - static parse(str: string): Fraction { - const parts = str.split("/"); - - const n = parseInt(parts[0], 10); - const d = parts[1] !== undefined ? parseInt(parts[1], 10) : 1; - - if (isNaN(n) || isNaN(d)) { - throw new Error("Invalid fraction format"); - } - - return new Fraction(n, d); - } - - add(o: Fraction): Fraction { - return new Fraction(this.n * o.d + o.n * this.d, this.d * o.d); - } - - sub(o: Fraction): Fraction { - return new Fraction(this.n * o.d - o.n * this.d, this.d * o.d); - } - - mul(o: Fraction): Fraction { - return new Fraction(this.n * o.n, this.d * o.d); - } - - div(o: Fraction): Fraction { - return new Fraction(this.n * o.d, this.d * o.n); - } - - compare(o: Fraction): number { - const diff = this.n * o.d - o.n * this.d; - - if (diff === 0) return 0; - return diff > 0 ? 1 : -1; - } - - toString(): string { - return `${this.n}/${this.d}`; - } -} - -const operators: { - [key: string]: (a: Fraction, b: Fraction) => Fraction | number; -} = { - "+": (a, b) => a.add(b), - "-": (a, b) => a.sub(b), - "*": (a, b) => a.mul(b), - "/": (a, b) => a.div(b), - - "==": (a, b) => (a.compare(b) === 0 ? 1 : 0), - "!=": (a, b) => (a.compare(b) !== 0 ? 1 : 0), - ">": (a, b) => (a.compare(b) > 0 ? 1 : 0), - "<": (a, b) => (a.compare(b) < 0 ? 1 : 0), - ">=": (a, b) => (a.compare(b) >= 0 ? 1 : 0), - "<=": (a, b) => (a.compare(b) <= 0 ? 1 : 0), -}; - -function run(): void { - const [, , rawA, op, rawB] = process.argv; - - if (!rawA || !rawB || !op || !(op in operators)) { - console.error(USAGE); - process.exit(1); - } - - try { - const f1 = Fraction.parse(rawA); - const f2 = Fraction.parse(rawB); - - const result = operators[op](f1, f2); - - console.log(result.toString()); - } catch { - console.error(USAGE); - process.exit(1); - } -} - -run(); - -``` - -{% endraw %} - -Fraction Math in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/fraction-math/visual-basic/index.md b/docs/projects/fraction-math/visual-basic/index.md deleted file mode 100644 index ba0f7fc72f..0000000000 --- a/docs/projects/fraction-math/visual-basic/index.md +++ /dev/null @@ -1,247 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: fraction-math-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- fraction-math -- visual-basic -title: Fraction Math in Visual Basic -title1: Fraction Math -title2: in Visual Basic ---- - - - -Welcome to the [Fraction Math](/projects/fraction-math) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Class FractionMath - - Private ReadOnly numerator As Integer - Private ReadOnly denominator As Integer - - Public Sub New(Optional numerator As Integer = 0, Optional denominator As Integer = 1) - - If denominator = 0 Then - Throw New ArgumentException("Denominator cannot be zero.") - End If - - If denominator < 0 Then - numerator = -numerator - denominator = -denominator - End If - - Dim gcdValue = GCD(Math.Abs(numerator), denominator) - - Me.numerator = numerator \ gcdValue - Me.denominator = denominator \ gcdValue - - End Sub - - - Private Shared Function GCD(x As Integer, y As Integer) As Integer - - While y <> 0 - Dim temp = x Mod y - x = y - y = temp - End While - - Return x - - End Function - - - Public Overrides Function ToString() As String - Return $"{numerator}/{denominator}" - End Function - - - Public Shared Function Parse(value As String) As FractionMath - - If String.IsNullOrWhiteSpace(value) Then - Throw New FormatException("Fraction cannot be empty.") - End If - - Dim parts = value.Split("/"c) - - If parts.Length <> 2 Then - Throw New FormatException("Expected format: numerator/denominator") - End If - - Dim n As Integer - Dim d As Integer - - If Not Integer.TryParse(parts(0), n) OrElse - Not Integer.TryParse(parts(1), d) Then - Throw New FormatException("Invalid integer in fraction.") - End If - - Return New FractionMath(n, d) - - End Function - - - Public Shared Operator +(a As FractionMath, b As FractionMath) As FractionMath - Return New FractionMath( - a.numerator * b.denominator + b.numerator * a.denominator, - a.denominator * b.denominator - ) - End Operator - - Public Shared Operator -(a As FractionMath, b As FractionMath) As FractionMath - Return New FractionMath( - a.numerator * b.denominator - b.numerator * a.denominator, - a.denominator * b.denominator - ) - End Operator - - Public Shared Operator *(a As FractionMath, b As FractionMath) As FractionMath - Return New FractionMath( - a.numerator * b.numerator, - a.denominator * b.denominator - ) - End Operator - - Public Shared Operator /(a As FractionMath, b As FractionMath) As FractionMath - - If b.numerator = 0 Then - Throw New DivideByZeroException() - End If - - Return New FractionMath( - a.numerator * b.denominator, - a.denominator * b.numerator - ) - - End Operator - - - Private Function CompareTo(other As FractionMath) As Integer - Dim left = CLng(numerator) * other.denominator - Dim right = CLng(other.numerator) * denominator - Return left.CompareTo(right) - End Function - - - Public Shared Operator =(a As FractionMath, b As FractionMath) As Boolean - Return a.CompareTo(b) = 0 - End Operator - - Public Shared Operator <>(a As FractionMath, b As FractionMath) As Boolean - Return a.CompareTo(b) <> 0 - End Operator - - Public Shared Operator >(a As FractionMath, b As FractionMath) As Boolean - Return a.CompareTo(b) > 0 - End Operator - - Public Shared Operator <(a As FractionMath, b As FractionMath) As Boolean - Return a.CompareTo(b) < 0 - End Operator - - Public Shared Operator >=(a As FractionMath, b As FractionMath) As Boolean - Return a.CompareTo(b) >= 0 - End Operator - - Public Shared Operator <=(a As FractionMath, b As FractionMath) As Boolean - Return a.CompareTo(b) <= 0 - End Operator -End Class - - -Public Module Program - Private Sub ShowUsage() - Console.WriteLine("Usage: ./fraction-math operand1 operator operand2") - Environment.Exit(1) - End Sub - - Public Sub Main(args As String()) - - If args.Length <> 3 Then - ShowUsage() - End If - - Try - - Dim a = FractionMath.Parse(args(0)) - Dim op = args(1) - Dim b = FractionMath.Parse(args(2)) - - Select Case op - - Case "+" - Console.WriteLine(a + b) - - Case "-" - Console.WriteLine(a - b) - - Case "*" - Console.WriteLine(a * b) - - Case "/" - Console.WriteLine(a / b) - - Case "==" - Console.WriteLine(If(a = b, "1", "0")) - - Case "!=" - Console.WriteLine(If(a <> b, "1", "0")) - - Case ">" - Console.WriteLine(If(a > b, "1", "0")) - - Case "<" - Console.WriteLine(If(a < b, "1", "0")) - - Case ">=" - Console.WriteLine(If(a >= b, "1", "0")) - - Case "<=" - Console.WriteLine(If(a <= b, "1", "0")) - - Case Else - ShowUsage() - - End Select - - Catch ex As Exception - ShowUsage() - End Try - - End Sub - -End Module -``` - -{% endraw %} - -Fraction Math in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/ada/index.md b/docs/projects/hello-world/ada/index.md deleted file mode 100644 index 1b7153023b..0000000000 --- a/docs/projects/hello-world/ada/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-04-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-24 -layout: default -tags: -- ada -- hello-world -title: Hello World in Ada -title1: Hello World -title2: in Ada ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Text_IO; -procedure Hello_World is - -begin - Text_IO.Put_Line("Hello, World!"); -end Hello_World; - -``` - -{% endraw %} - -Hello World in [Ada](/languages/ada) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/agda/index.md b/docs/projects/hello-world/agda/index.md deleted file mode 100644 index 6d2eebc676..0000000000 --- a/docs/projects/hello-world/agda/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-11-10 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-10 -layout: default -tags: -- agda -- hello-world -title: Hello World in Agda -title1: Hello World -title2: in Agda ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Agda](/languages/agda) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```agda -module HelloWorld where - -open import Agda.Builtin.IO using (IO) -open import Agda.Builtin.Unit using (⊤) -open import Agda.Builtin.String using (String) - -postulate putStrLn : String → IO ⊤ -{-# FOREIGN GHC import qualified Data.Text as T #-} -{-# COMPILE GHC putStrLn = putStrLn . T.unpack #-} - -main : IO ⊤ -main = putStrLn "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Agda](/languages/agda) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/algol60/index.md b/docs/projects/hello-world/algol60/index.md deleted file mode 100644 index 371bade177..0000000000 --- a/docs/projects/hello-world/algol60/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-12 -featured-image: hello-world-in-every-language.jpg -last-modified: 2026-03-16 -layout: default -tags: -- algol60 -- hello-world -title: Hello World in ALGOL 60 -title1: Hello World -title2: in ALGOL 60 ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - outstring(1, "Hello, World!\n") -end - -``` - -{% endraw %} - -Hello World in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/algol68/index.md b/docs/projects/hello-world/algol68/index.md deleted file mode 100644 index 799440cbfa..0000000000 --- a/docs/projects/hello-world/algol68/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- awoerner92 -- Jeremy Grifski -- rzuckerm -date: 2018-05-06 -featured-image: hello-world-in-algol68.jpg -last-modified: 2023-05-15 -layout: default -tags: -- algol68 -- hello-world -title: Hello World in ALGOL 68 -title1: Hello World -title2: in ALGOL 68 ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -printf(($gl$, "Hello, World!")) - -``` - -{% endraw %} - -Hello World in [ALGOL 68](/languages/algol68) was written by: - -- Jeremy Grifski - -This article was written by: - -- awoerner92 -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Without further ado, let's implement Hello World in ALGOL 68. - -Now, I believe we can actually shorten this implementation to look identical to the -[Python implementation][1]. But, that wouldn't be too interesting. Instead, we opted -to use a *printf* solution to show off a couple of features. - -If you're unfamiliar with *printf*, it's typically a version of the print function -which allows for string formatting. Unfortunately, that's about where the similarities -end. In ALGOL 68, the syntax for formatting text is about as bizarre as I've ever seen. -Luckily, we have a simple example: `$gl$`. - -In this example, everything between the dollar signs is considered a format string. -In this case, we have two characters: *g* and *l*. - -Since we're formatting strings, one of those tokens will be replaced by our `"Hello, World!"` -string. In this case, it's *g*. As for *l*, that's actually the newline token, something -we haven't paid a lot of attention to in this series. When put together, `"Hello, World!"` -will print to the console. - -Another interesting bit about this program is the fact that we have double parentheses -that almost look redundant. But make no mistake, they're important: - -```console -1 printf($gl$, "Hello, World!") - 1 -a68g: error: 1: incorrect number of arguments for PROC ([] "SIMPLOUT") VOID (detected in particular-program). -``` - -To be honest, I don't understand the error. My best guess is *printf* requires an array -of arguments. Whereas, the *varargs* solution I'm proposing issues the format string -and `"Hello, World!"` as separate arguments. - -[1]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/hello_world.py - - -## How to Run the Solution - -Perhaps the easiest way to run the solution is to use an [online ALGOL 68 editor][2]. -If we copy the solution above into the editor, we can hit execute to run it. - -Alternatively, we have the option to install an ALGOL 68 interpreter. Apparently, there -is a limited [ALGOL 68 Genie interpreter][3] which should get the job done. After all, -it's the same interpreter the online solution uses. Feel free to leverage the -[documentation][4]. - -[2]: https://www.jdoodle.com/execute-algol68-online/ -[3]: https://jmvdveer.home.xs4all.nl/en.algol-68-genie.html -[4]: https://jmvdveer.home.xs4all.nl/learning-algol-68-genie.pdf diff --git a/docs/projects/hello-world/arkscript/index.md b/docs/projects/hello-world/arkscript/index.md deleted file mode 100644 index 3514b0bdb8..0000000000 --- a/docs/projects/hello-world/arkscript/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Alexandre Plateau -- SuperFola -date: 2020-10-03 -featured-image: hello-world-in-every-language.jpg -last-modified: 2024-09-30 -layout: default -tags: -- arkscript -- hello-world -title: Hello World in ArkScript -title1: Hello World -title2: in ArkScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [ArkScript](/languages/arkscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```arkscript -(print "Hello, World!") -``` - -{% endraw %} - -Hello World in [ArkScript](/languages/arkscript) was written by: - -- SuperFola - -This article was written by: - -- Alexandre Plateau - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -ArkScript programs do not require a `main` function as in C or C++. Every expression is executed, thus a single `(print "Hello, World!")` can write to the console. - -A modular way to write the program could be as follows: - -```arkscript -(let say (fun (to) - (print (str:format "Hello, {}!" to)))) - -(say "World") -``` - -1. The first line, `(let say (fun (to)`, declares a function named `say`, taking a single argument, `to`. -2. On the second line, we have a call to `str:format`: it takes a format string and values to be formatted - 1. This is then wrapped in a call to `print` to write the resulting string to the console -3. On the last line, we call the `say` function with the argument `World`, printing `Hello, World!` - - - -## How to Run the Solution - -Using the online playground: - -1. Go to [playground.arkscript-lang.dev](https://playground.arkscript-lang.dev/#/pages/ide/ark/hello_world.template) -2. Copy the code you want to run, eg `(print "Hello, World!")`, and paste it in the editor -3. Click the `Run` button - -Using the interpreter: - -1. Download the [latest release](https://github.com/ArkScript-lang/Ark/releases) - 1. See [the documentation](https://arkscript-lang.dev/tutorials/building.html#from-a-release) in case you need help finding the correct binary & installing it -2. Create a `file.ark` with your code inside -3. Run it using `arkscript file.ark` - -Using Docker: - -1. Pull `arkscript/nightly:latest` -2. Create a `file.ark` with your code inside -3. Run it using `docker run --rm -v $(pwd):/tmp arkscript/nightly /tmp/file.ark` - diff --git a/docs/projects/hello-world/awk/index.md b/docs/projects/hello-world/awk/index.md deleted file mode 100644 index dd24fb2859..0000000000 --- a/docs/projects/hello-world/awk/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-06 -featured-image: hello-world-in-every-language.jpg -last-modified: 2025-04-06 -layout: default -tags: -- awk -- hello-world -title: Hello World in AWK -title1: Hello World -title2: in AWK ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -BEGIN { - print "Hello, World!" -} - -``` - -{% endraw %} - -Hello World in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/baik/index.md b/docs/projects/hello-world/baik/index.md deleted file mode 100644 index 83ddcdb8bc..0000000000 --- a/docs/projects/hello-world/baik/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- baik -- hello-world -title: Hello World in BAIK -title1: Hello World -title2: in BAIK ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [BAIK](/languages/baik) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```baik -tulis "Hello, World!\n" - -``` - -{% endraw %} - -Hello World in [BAIK](/languages/baik) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/ballerina/index.md b/docs/projects/hello-world/ballerina/index.md deleted file mode 100644 index d54b0f0baf..0000000000 --- a/docs/projects/hello-world/ballerina/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2018-06-15 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-07-27 -layout: default -tags: -- ballerina -- hello-world -title: Hello World in Ballerina -title1: Hello World -title2: in Ballerina ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Ballerina](/languages/ballerina) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ballerina -import ballerina/io; -public function main(string... args) { - io:println("Hello, World!"); -} - -``` - -{% endraw %} - -Hello World in [Ballerina](/languages/ballerina) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/bash/index.md b/docs/projects/hello-world/bash/index.md deleted file mode 100644 index 7fdea64b73..0000000000 --- a/docs/projects/hello-world/bash/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Abdus -- Jeremy Grifski -- rzuckerm -date: 2018-05-09 -featured-image: hello-world-in-bash.jpg -last-modified: 2023-05-15 -layout: default -tags: -- bash -- hello-world -title: Hello World in Bash -title1: Hello World -title2: in Bash ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -echo Hello, World! - -``` - -{% endraw %} - -Hello World in [Bash](/languages/bash) was written by: - -- Abdus -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -As we can see, printing "Hello, World!" in Bash is quite simple. All we do is call the -`echo` command to print the string. - -As an added note, the shebang (`#!`) tells the environment how to run the script. -In this case, we want to run the script using Bash. But, we can use this same -notation for other languages as well: - -```python -#!/usr/bin/env python -print("Hello, World!") -``` - -```ruby -#!/usr/bin/env ruby -puts "Hello, World!" -``` - -```node -#!/usr/bin/env node -console.log("Hello, World!") -``` - -Here, we have Hello World in Python, Ruby, and Node.js, respectively. Each of these -scripting languages can leverage the shebang syntax for easy execution in Unix, Linux, -and Mac environments. - - -## How to Run the Solution - -If we want to run the solution, we can easily leverage an online Bash shell. To use -the tool, we just have to drop our solution into the editor and hit run. - -Alternatively, if we have a bash shell available, we can easily download the script, -navigate to its folder from the command line, and run it: - -```console -./hello-world.sh -``` - -In fact, even Windows 10 users can leverage Bash. How-To Geek has a nice tutorial -on how to use Bash on Windows 10. If that sounds interesting, check it out! diff --git a/docs/projects/hello-world/batch/index.md b/docs/projects/hello-world/batch/index.md deleted file mode 100644 index f5745df71b..0000000000 --- a/docs/projects/hello-world/batch/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2020-04-23 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-07-27 -layout: default -tags: -- batch -- hello-world -title: Hello World in Batch -title1: Hello World -title2: in Batch ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Batch](/languages/batch) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```batch -@echo off -echo Hello, World! - -``` - -{% endraw %} - -Hello World in [Batch](/languages/batch) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/beef/index.md b/docs/projects/hello-world/beef/index.md deleted file mode 100644 index f74055da8e..0000000000 --- a/docs/projects/hello-world/beef/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-11 -featured-image: hello-world-in-every-language.jpg -last-modified: 2024-01-11 -layout: default -tags: -- beef -- hello-world -title: Hello World in Beef -title1: Hello World -title2: in Beef ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace HelloWorld; - -class Program -{ - public static int Main(String[] args) - { - Console.WriteLine("Hello, World!"); - return 0; - } -} - -``` - -{% endraw %} - -Hello World in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/befunge/index.md b/docs/projects/hello-world/befunge/index.md deleted file mode 100644 index d8d8e8cd6d..0000000000 --- a/docs/projects/hello-world/befunge/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Stuart -- Stuart Irwin -date: 2018-11-27 -featured-image: hello-world-in-befunge.jpg -last-modified: 2023-05-15 -layout: default -tags: -- befunge -- hello-world -title: Hello World in Befunge -title1: Hello World -title2: in Befunge ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Befunge](/languages/befunge) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```befunge -0"!dlroW ,olleH"v - > , v - | : < - @ - -``` - -{% endraw %} - -Hello World in [Befunge](/languages/befunge) was written by: - -- Stuart Irwin - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Stuart -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -There are many valid ways to set up a Befunge program. People tend to design for either artistic or compactness purposes. - -In Befunge, everything works off of a stack. A stack in programming is a list of values, set up sort of like a stack of papers. Only the top number can be retrieved, and new numbers are always placed on the very top. Because of this, strings have to be read in backwards, as the last letter in will be the first letter out. - -The program starts out in string mode to read in the characters. At the end of the first line, our stack will look something like this: (with translated characters below) - -``` -33 100 108 114 111 87 32 44 111 108 108 101 72 -! d l r o W , o l l e H -``` - -The following section is a literal loop, to print out each of the values off the stack: - -```befunge -> , v -| : < -@ -``` - -In order, the arrow sends it right, `,` prints out the H, the arrows loop it back around, `:` copies the top value of the stack, and `|` takes that copy for an if statement. - -With `|`, if the top value is 0 (or null), then the pointer starts to go downwards, otherwise it is sent up. `_` works the same way, except it means right on 0 and left for anything else. - -The pointer will continue to run through the loop until the stack is empty. When it finishes, the if bar drops it down to the bottom. The `@` indicates end of program. - - -## How to Run the Solution - -Because of the particular design of the language, your best option is a Befunge interpreter. This is both for availability and because watching it run is the only way to really understand (or debug) it. - -- [Befunge Playground][2] -- [jsFunge IDE][3] -- [Befunge-93 Interpreter][4] - -There are compilers as well, even through the technical challenges: - -- [BefunUtils][6] - -For a much more thorough look at Befunge, it's list of operators, and its various derivatives, I recommend the [Esolang Wiki][7]. - -[2]: https://www.bedroomlan.org/tools/befunge-playground/#prog=hello,mode=edit -[3]: https://befunge.flogisoft.com/ -[4]: http://qiao.github.io/javascript-playground/visual-befunge93-interpreter/ -[6]: https://github.com/Mikescher/BefunUtils -[7]: https://esolangs.org/wiki/Befunge diff --git a/docs/projects/hello-world/boo/index.md b/docs/projects/hello-world/boo/index.md deleted file mode 100644 index 0c8021ae63..0000000000 --- a/docs/projects/hello-world/boo/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Subhayu Roy -date: 2020-10-02 -featured-image: hello-world-in-every-language.jpg -last-modified: 2020-10-02 -layout: default -tags: -- boo -- hello-world -title: Hello World in Boo -title1: Hello World -title2: in Boo ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Boo](/languages/boo) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```boo -print "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Boo](/languages/boo) was written by: - -- Subhayu Roy - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/bracmat/index.md b/docs/projects/hello-world/bracmat/index.md deleted file mode 100644 index 5f09f7eb0b..0000000000 --- a/docs/projects/hello-world/bracmat/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- Shivam Choudhary -date: 2020-12-07 -featured-image: hello-world-in-every-language.jpg -last-modified: 2020-12-07 -layout: default -tags: -- bracmat -- hello-world -title: Hello World in Bracmat -title1: Hello World -title2: in Bracmat ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Bracmat](/languages/bracmat) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bracmat -put$"Hello, World!" -``` - -{% endraw %} - -Hello World in [Bracmat](/languages/bracmat) was written by: - -- Shivam Choudhary - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/brainfuck/index.md b/docs/projects/hello-world/brainfuck/index.md deleted file mode 100644 index a0359f196d..0000000000 --- a/docs/projects/hello-world/brainfuck/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- Jeremy Grifski -- rzuckerm -date: 2018-08-24 -featured-image: hello-world-in-brainfuck.jpg -last-modified: 2023-05-15 -layout: default -tags: -- brainfuck -- hello-world -title: Hello World in Brainfuck -title1: Hello World -title2: in Brainfuck ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Brainfuck](/languages/brainfuck) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```brainfuck ->++++++++[<+++++++++>-]<.>++++[<+++++++>-]<+.+++++++..+++.>>++++++[<+++++++>-]<+ -+.------------.>++++++[<+++++++++>-]<+.<.+++.------.--------.>>>++++[<++++++++>- -]<+. - -``` - -{% endraw %} - -Hello World in [Brainfuck](/languages/brainfuck) was written by: - -- Christoph Böhmwalder - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -If you're unfamiliar with Brainfuck, this might not really look like a -"Hello World" example to you. It might even look a little intimidating. -Granted, the syntax might not be the most verbose, but fear not! I'm sure it -will start making sense once we break it down. - -For starters, let's reindent it a little bit: - -```brainfuck ->++++++++[<+++++++++>-]<. ->++++[<+++++++>-]<+. -+++++++.. -+++. ->>++++++[<+++++++>-]<++. -------------. ->++++++[<+++++++++>-]<+. -<. -+++. -------. ---------. ->>>++++[<++++++++>-]<+. -``` - -Well, that's already looking slightly better. Remember, the `.` operator writes -the current cell value to the output, so we've inserted a line break for every -character that gets printed. - -Let's look at it line by line: - -```brainfuck ->++++++++[<+++++++++>-]<. -``` - -We can see that we immediately move one cell to the right and increment that -cell's value eight times. This gives us, you guessed it, the value 8 in cell 1. - -Then we start a loop, in which we move left (back to cell 0), add nine to that -cell, move right again, and subtract one from the value of cell 1. Remember that -the loop runs until the cell value is zero, so this would run 8 times, adding 9 -to cell 0 every time. So we can already see that the value of cell 0 at this -point is 72, which corresponds to the uppercase letter 'H' in the [ASCII table][2]. - -So, we got our first character printed. Let's look at the second line: - -```brainfuck ->++++[<+++++++>-]<+. -``` - -You might immediately notice that this line looks quite similar to the last one. -That might be because it does pretty much exactly the same thing. The only -difference is in the numbers. It adds the value 28 (4 times 7) to cell 0, -and then adds one more at the end of the loop, giving us a value of 101, or -a lowercase 'e'. - -This is basically how the entire program works. It's just a matter of choosing -the right path in order to get from one value to the next by only using simple -addition, subtraction, and loops. - -[2]: https://www.asciitable.com/ - - -## How to Run the Solution - -There are plenty of Brainfuck interpreters (and even compilers!) available, -online or offline: - -- [Copy.sh][3] -- [Sange.fi][4] -- [Dcode.fr][5] - -As a starting point, [here's this example on "Brainfuck Visualizer"][6], an online -tool that displays each step of a Brainfuck program's execution. - -[3]: https://copy.sh/brainfuck/ -[4]: https://sange.fi/esoteric/brainfuck/impl/interp/i.html -[5]: https://www.dcode.fr/brainfuck-language -[6]: https://ashupk.github.io/Brainfuck/brainfuck-visualizer-master/index.html diff --git a/docs/projects/hello-world/c-plus-plus/index.md b/docs/projects/hello-world/c-plus-plus/index.md deleted file mode 100644 index a7430f7dd0..0000000000 --- a/docs/projects/hello-world/c-plus-plus/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -- Ștefan-Iulian Alecu -date: 2018-03-21 -featured-image: hello-world-in-c-plus-plus.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- hello-world -title: Hello World in C++ -title1: Hello World -title2: in C++ ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include - -int main() { - std::cout << "Hello, World!\n"; - return 0; -} - -``` - -{% endraw %} - -Hello World in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Griffith -- Jeremy Grifski -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of May 05 2026 15:57:54. The solution was first committed on Mar 21 2018 00:11:57. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Even though C++ was built on C, the implementation of Hello World in -C++ is slightly different. - -It appears this implementation of Hello World may be competing with -Java for hardest to learn. But at any rate, let's break it down. - -Once again, the first line is an `include` statement. Here, we're including -the IO stream code in our solution. This is how we gain access to the -IO objects like `cout`. - -Next, we gain access to the `std` namespace which basically allows us to -shorten `std::cout` to `cout`. It's really just a style thing that eliminates -a lot of verbosity that you might get with other languages like Java. -Of course, if another namespace also has a `cout`, we'll run into problems. - -After that, we make a `main` method as usual. This is exactly the same as -C, so I won't bother explaining the return type bit again. - -Finally, we write our string to the `cout` stream. The syntax is a bit -strange, but basically we can imagine that the Hello World string is -inserted into the `cout` stream. In fact, the double-arrow operator is -the insertion operator, and it has some fun properties. For instance, -the operator can be chained together, but that's a topic for another time. - - -## How to Run the Solution - -Perhaps the easiest way to run the solution is to leverage the [online gdb compiler][1]. - -Alternatively, you can try to run the C++ code in a similar way described -in the last article. Honestly, it's pretty easy to write and run C/C++ code -on most platforms: - -```console -gcc -o hello-world hello-world.cpp -./hello-world -``` - -Unfortunately, Windows pretty much requires the use of Visual Studio. So, -instead of sharing platform specific directions, I'll fallback on my online -compiler recommendation. - -[1]: https://www.onlinegdb.com/online_c++_compiler diff --git a/docs/projects/hello-world/c-sharp/index.md b/docs/projects/hello-world/c-sharp/index.md deleted file mode 100644 index 08786357dd..0000000000 --- a/docs/projects/hello-world/c-sharp/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Ștefan-Iulian Alecu -date: 2022-04-28 -featured-image: hello-world-in-c-sharp.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- hello-world -title: Hello World in C# -title1: Hello World -title2: in C# ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -Console.WriteLine("Hello, World!"); -``` - -{% endraw %} - -Hello World in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Now, we can implement Hello World in C# in a couple of ways. For simplicity, -I'll share the minimalist approach but be aware that there are more complete ways -to do this. - -If you read the Hello World in Java tutorial, then this probably looks very -similar. In fact, C# shares a lot of the same look and feel as Java. With that -being the case, I'll only highlight the major pieces here. - -Before we can print, we have to create a class. Inside our class, we declare -the `main` method. Inside our `main` method, we run our print command. The syntax -and core libraries are a little different, but it feels eerily similar to Java. - - -## How to Run the Solution - -Perhaps the easiest way to run this solution would be to open up an [online C# compiler][1]. -Just copy the code from above and drop it into the editor before -hitting run. - -Alternatively, we can download Visual Studio or Mono to run C# locally. Of -course, we'll want a copy of the solution as well. Refer to the manual of the -various tools to run C#. - -As far as I know, there aren't any easy ways to run C# code from the command -line, but I imagine it can be done. - -[1]: https://www.programiz.com/csharp-programming/online-compiler/ diff --git a/docs/projects/hello-world/c-star/index.md b/docs/projects/hello-world/c-star/index.md deleted file mode 100644 index cb72153fd1..0000000000 --- a/docs/projects/hello-world/c-star/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2022-04-28 -featured-image: hello-world-in-c-star.jpg -last-modified: 2023-12-09 -layout: default -tags: -- c-star -- hello-world -title: Hello World in C* -title1: Hello World -title2: in C* ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [C\*](/languages/c-star) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c\* -void main() -{ - println("Hello, World!"); -} - -``` - -{% endraw %} - -Hello World in [C\*](/languages/c-star) was written by: - -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -At long last, here's Hello World in C*. - -As we can see, Hello World in C* looks similar to C. That said, C* -is a superset of C, so this shouldn't be too much of a surprise. At any rate, -let's dig in. - -Unlike C, there is no `include` statement. As far as I can tell, the language -does not actually have an `include` statement or header files. Somehow, the -compiler know where to pull the definition for standard libraries. - -Next, we have our usual `main` function declaration which serves as the drop in -function for our program. We should be used to seeing this convention since it's -common in the popular industrial languages like C++ and Java. - -Finally, we make a call to `println` which is a special print function that outputs -the specified string with a newline character. Of course, all we're going to pass -to it is the "Hello, World!" string. And, that's it! - - -## How to Run the Solution - -The compiler source can be found in the [C* GitHub repository][1]. To build it, -just follow the [build from source instructions][2] for your particular OS. -Once, you've built the compiler, download a copy of the [Hello World in C* sample][3]. -Then, build and run the program like this: - -``` -cx -o hello-world hello-world.cx -./hello-world -``` - -[1]: https://github.com/cx-language/cx -[2]: https://github.com/cx-language/cx#building-from-source -[3]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/c/c-star/hello-world.cx diff --git a/docs/projects/hello-world/c/index.md b/docs/projects/hello-world/c/index.md deleted file mode 100644 index 2993cbbd5b..0000000000 --- a/docs/projects/hello-world/c/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- Johnny Fang -- rzuckerm -- Ștefan-Iulian Alecu -date: 2018-03-15 -featured-image: hello-world-in-c.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- hello-world -title: Hello World in C -title1: Hello World -title2: in C ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include - -int main() -{ - puts("Hello, World!"); - return 0; -} - -``` - -{% endraw %} - -Hello World in [C](/languages/c) was written by: - -- Jeremy Griffith -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- Johnny Fang -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Apr 15 2026 00:50:56. The solution was first committed on Mar 15 2018 20:27:08. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Since C predates both Java and Python, the syntax is naturally a bit archaic. -That said, you'll find that the syntax for Hello World in C is still easier to -understand than Java. - -At the top, we'll notice an `include` statement. Basically, this statement copies -in functionality from the standard IO library of C. This includes the `printf` -functionality we'll need to actually write our string to the command line. - -Like Java, we'll notice that we have a `main` function. In C, the `main` function is -much simpler. In fact, we don't even have classes in C, so we don't have to bother -with that extra layer of abstraction. Instead, we can define the `main` function -directly. Again, we can only define one of these per program. - -Inside the `main` function, we'll find our usual call to print. However, in C, -we use `printf` which allows us to format strings as well. - -Finally, we'll notice that we return zero. That's because the `main` function is -like any other function, so it has a return type. In this case, the return type -is an integer, and that integer is used to indicate status codes. A status code -of zero means no errors occurred. - - -## How to Run the Solution - -Now, if we want to run the solution, we'll need to [get a hold of a C compiler][1]. -In addition, we'll probably want to [get a copy of Hello World in C][2]. With both -prerequisites out of the way, all we have to do is navigate to our file and run -the following commands from the command line: - -```console -gcc -o hello-world hello-world.c -./hello-world -``` - -Of course, these are Unix/Linux instructions. If we're on Windows, it may be easier -to take advantage of an [online C compiler][3]. Alternatively, we can leverage a tool -like [MinGW][4]. - -[1]: https://gcc.gnu.org/ -[2]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/c/c/hello-world.c -[3]: https://www.programiz.com/c-programming/online-compiler/ -[4]: https://www.mingw-w64.org/ diff --git a/docs/projects/hello-world/c2/index.md b/docs/projects/hello-world/c2/index.md deleted file mode 100644 index 4e4ae6f3d3..0000000000 --- a/docs/projects/hello-world/c2/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2021-05-25 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-26 -layout: default -tags: -- c2 -- hello-world -title: Hello World in C2 -title1: Hello World -title2: in C2 ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [C2](/languages/c2) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c2 -module hello_world; - -import stdio as io; - -public fn i32 main(i32 argc, char** argv) { - io.printf("Hello, World!\n"); - return 0; -} - -``` - -{% endraw %} - -Hello World in [C2](/languages/c2) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/carp/index.md b/docs/projects/hello-world/carp/index.md deleted file mode 100644 index eb34a6b60d..0000000000 --- a/docs/projects/hello-world/carp/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-07-29 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-07-29 -layout: default -tags: -- carp -- hello-world -title: Hello World in Carp -title1: Hello World -title2: in Carp ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Carp](/languages/carp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```carp -(defn main[] - (println* "Hello, World!") -) - -``` - -{% endraw %} - -Hello World in [Carp](/languages/carp) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/chaiscript/index.md b/docs/projects/hello-world/chaiscript/index.md deleted file mode 100644 index 6ad5405812..0000000000 --- a/docs/projects/hello-world/chaiscript/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-24 -layout: default -tags: -- chaiscript -- hello-world -title: Hello World in ChaiScript -title1: Hello World -title2: in ChaiScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [ChaiScript](/languages/chaiscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```chaiscript -print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [ChaiScript](/languages/chaiscript) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/chapel/index.md b/docs/projects/hello-world/chapel/index.md deleted file mode 100644 index 6cdd1ffd4d..0000000000 --- a/docs/projects/hello-world/chapel/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-11-22 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-11-22 -layout: default -tags: -- chapel -- hello-world -title: Hello World in Chapel -title1: Hello World -title2: in Chapel ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Chapel](/languages/chapel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```chapel -writeln("Hello, World!"); - -``` - -{% endraw %} - -Hello World in [Chapel](/languages/chapel) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/clojure/index.md b/docs/projects/hello-world/clojure/index.md deleted file mode 100644 index ecb23d7cd1..0000000000 --- a/docs/projects/hello-world/clojure/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-12-22 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-12-23 -layout: default -tags: -- clojure -- hello-world -title: Hello World in Clojure -title1: Hello World -title2: in Clojure ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Clojure](/languages/clojure) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```clojure -(ns hello-world - (:gen-class)) - -(defn main - "Hello World" - [& args] - (println "Hello, World!")) - -(main) - - -``` - -{% endraw %} - -Hello World in [Clojure](/languages/clojure) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/cobol/index.md b/docs/projects/hello-world/cobol/index.md deleted file mode 100644 index 7cf5d2b1b7..0000000000 --- a/docs/projects/hello-world/cobol/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Sudhanshu Dubey -- Ștefan-Iulian Alecu -date: 2021-10-08 -featured-image: hello-world-in-cobol.jpg -last-modified: 2026-04-18 -layout: default -tags: -- cobol -- hello-world -title: Hello World in COBOL -title1: Hello World -title2: in COBOL ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. hello-world. - -procedure division. - -main. - display "Hello, World!" - stop run. -``` - -{% endraw %} - -Hello World in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Sudhanshu Dubey - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -From it's very nature, COBOL is a very readable language. -But even though it's readable, it follows very strict rules. - -The structure of a COBOL program follows like this: - -- At the highest level are "Divisions". -- "Divisions" consist of "Sections". -- "Sections" consist of "Paragraphs". -- "Paragraphs" consist of "Sentences". -- "Sentences" consist of "Statements". -- "Statements" consist of "Characters". - -We know that Python as language cares a lot about indentation but COBOL is even more particular about it. -A COBOL program is divided into columns. The Divisions must start from column 8 (Area A). -Paragraphs and Sentences should start from column 12 (Area B) which you can see is 1 tab or 4 spaces away from Area A. -This indentation is also a reason why COBOL is so readable. -Now that we have cleared some basics, let's start reading the Hello World program. - -The `IDENTIFICATION DIVISION` is one of the 4 Divisions that we have and it is mandatory. -As the name suggests, it consists of information that identifies the program like the author name, date of creation, etc. -One mandatory information for program identification is, you guessed it, the `PROGRAM-ID` statement. -Here we are declaring the `PROGRAM-ID` as `HELLO-WORLD`. -As a side note, we should ideally keep the `PROGRAM-ID` same as the file name and only 8 characters long. But since we will be running this program on a Linux environment, it's fine. - -Next we have the other mandatory Division, `PROCEDURE DIVISION`. -This contains all the Paragraphs and Sentences that do the actual work. -Here, the Sentence doing our work is `DISPLAY "Hello, World!"`. -`DISPLAY` is our Statement here and it does what it says it does. -Then, we have another Statement, which is a Sentence in itself, `STOP RUN`. -It stops the run and returns the control to either the calling program or the OS. -Also, you should end any part of the program with a period. It might be optional at some places but it is recommended. -That's it! Apart from the little nuances of indentation and program structure, it's a very readable program. - - -## How to Run the Solution - -To run the solution we will need [a COBOL compiler][1] installed and of the course [the actual code file][2]. -Finally we need to run these commands in order: - -```console -cobc -x hello-world.cbl -$ ./hello-world -``` -The commands first compile the source code into an executable and then execute it. -Alternatively, you might want to use an [online COBOL compiler][3] - -[1]: https://gnucobol.sourceforge.io/ -[2]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/c/cobol/hello-world.cbl -[3]: https://www.jdoodle.com/execute-cobol-online/ diff --git a/docs/projects/hello-world/coffeescript/index.md b/docs/projects/hello-world/coffeescript/index.md deleted file mode 100644 index dcfc22deb0..0000000000 --- a/docs/projects/hello-world/coffeescript/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-12-30 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-12-30 -layout: default -tags: -- coffeescript -- hello-world -title: Hello World in CoffeeScript -title1: Hello World in -title2: CoffeeScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -console.log("Hello, World!") - -``` - -{% endraw %} - -Hello World in [CoffeeScript](/languages/coffeescript) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/commodore-basic/index.md b/docs/projects/hello-world/commodore-basic/index.md deleted file mode 100644 index 5302ee8d48..0000000000 --- a/docs/projects/hello-world/commodore-basic/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- hello-world -title: Hello World in Commodore BASIC -title1: Hello World in -title2: Commodore BASIC ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 PRINT "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/crystal/index.md b/docs/projects/hello-world/crystal/index.md deleted file mode 100644 index 9b04c8d4be..0000000000 --- a/docs/projects/hello-world/crystal/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-22 -featured-image: hello-world-in-crystal.jpg -last-modified: 2023-05-15 -layout: default -tags: -- crystal -- hello-world -title: Hello World in Crystal -title1: Hello World -title2: in Crystal ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Crystal](/languages/crystal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```crystal -puts "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Crystal](/languages/crystal) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -With the background out of the way, let's implement Hello World in Crystal. - -If we think back, we might remember that this syntax is exactly the same in Ruby. -Of course, this should come as no surprise as Ruby's syntax was a major influence -on Crystal. - -[Digging through the API][1] reveals that there are four definitions of puts: - -```crystal -def puts(*objects : _) : Nil -def puts : Nil -def puts(obj) : Nil -def puts(string : String) : Nil -``` - -In our case, we're using option four which simply writes a string to standard output. - -Now, puts is pretty interesting because it automatically appends a new line unless -a new line already exists. Personally, that's the first time I've heard of a library -call doing that kind of string formatting for the user. So, my question becomes: what -happens if the string ends with multiple new lines? - -Based on the source code: - -```crystal -def puts(string : String) : Nil -self << string -puts unless string.ends_with?('\n') -nil -end -``` - -The puts library appears to only remove the last new line. After running it, I can -confirm that's all this function does. Now, that's some bizarre behavior: - -```crystal -puts 'Hello, World!' # Writes 'Hello, World!\n' -puts 'Hello, World!\n' # Writes 'Hello, World!\n' -puts 'Hello, World!\n\n' # Writes 'Hello, World!\n\n' -``` - -Honestly, I find this a little buggy. If, by default, this function adds a new -line, then I would instinctively add a new line to the string (see line 2 above) to -create extra space. - -Of course, that doesn't work. I suspect that Crystal style would prefer the following: - -```crystal -puts 'Hello, World!' -puts -``` - -Or, something along those lines. At any rate, I've gone a bit too far down a rabbit hole. -Let's learn how to run our solution. - -[1]: https://crystal-lang.org/api/1.8.2 - - -## How to Run the Solution - -If we want to run our solution, perhaps the easiest thing to do is to copy our solution -into the [online Crystal editor][2]. After that, we can hit run to see the output. - -Alternatively, we can try to install the compiler on our system. However, I won't bother -going into that because I'm using a Windows PC which doesn't appear to be supported. - -[2]: https://play.crystal-lang.org/ diff --git a/docs/projects/hello-world/cyclone/index.md b/docs/projects/hello-world/cyclone/index.md deleted file mode 100644 index 00bf857904..0000000000 --- a/docs/projects/hello-world/cyclone/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Shivam Choudhary -date: 2020-12-02 -featured-image: hello-world-in-every-language.jpg -last-modified: 2020-12-02 -layout: default -tags: -- cyclone -- hello-world -title: Hello World in Cyclone -title1: Hello World -title2: in Cyclone ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Cyclone](/languages/cyclone) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cyclone -#include -int main() { - puts("Hello, World!"); - return 0; -} - -``` - -{% endraw %} - -Hello World in [Cyclone](/languages/cyclone) was written by: - -- Shivam Choudhary - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/cython/index.md b/docs/projects/hello-world/cython/index.md deleted file mode 100644 index 28a67722f0..0000000000 --- a/docs/projects/hello-world/cython/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-27 -featured-image: hello-world-in-every-language.jpg -last-modified: 2025-10-27 -layout: default -tags: -- cython -- hello-world -title: Hello World in Cython -title1: Hello World -title2: in Cython ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Cython](/languages/cython) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cython -from libc.stdio cimport printf - - -cdef main(): - printf(b"%s\n", b"Hello, World!") - - -if __name__ == "__main__": - main() - -``` - -{% endraw %} - -Hello World in [Cython](/languages/cython) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/d/index.md b/docs/projects/hello-world/d/index.md deleted file mode 100644 index d490b3b51a..0000000000 --- a/docs/projects/hello-world/d/index.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Trever Shick -date: 2018-05-06 -featured-image: hello-world-in-d.jpg -last-modified: 2023-05-15 -layout: default -tags: -- d -- hello-world -title: Hello World in D -title1: Hello World -title2: in D ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [D](/languages/d) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```d -import std.stdio; - -void main() -{ - writeln("Hello, World!"); -} - -``` - -{% endraw %} - -Hello World in [D](/languages/d) was written by: - -- rzuckerm -- Trever Shick - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -At any rate, let's get to the implementation of Hello World in D. - -At this point, you may be questioning whether or not D is even a new -language. After all, this Hello World implementation looks a lot like -C/C++. - -Well, then it should come as no surprise the solution is pretty much -the same. We have basically three main parts: the `import` statement, -the `main` function, and the print function. - -Just like C/C++, the first thing we do is import our standard IO -library. In this case, D references `std.stdio` as opposed to `stdio.h` -in C. - -Up next, we have our usual `main` function. At this point in the series, -we're pretty use to this syntax. - -Finally, we have our typical print function. In this case, we call -`writeln` and pass a string to it. - - -## How to Run the Solution - -If we wanted to run our code snippet from above, we can leverage an -[online D compiler][1]. - -Alternatively, we can download our own D compiler from the official -website. Then, we'll want to get a copy of Hello World in D. After -that, we can simply run the following: - -```shell -rdmd hello-world.d -``` - -And, that's it! The string "Hello, World!" should appear in the console. - -[1]: https://run.dlang.io/ diff --git a/docs/projects/hello-world/dale/index.md b/docs/projects/hello-world/dale/index.md deleted file mode 100644 index 2ac533a8a9..0000000000 --- a/docs/projects/hello-world/dale/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -- tom-vthptvh -date: 2018-10-03 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-13 -layout: default -tags: -- dale -- hello-world -title: Hello World in Dale -title1: Hello World -title2: in Dale ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Dale](/languages/dale) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dale -(import cstdio) - -(def main (fn extern-c int (void) - (printf "Hello, World!\n"))) - -``` - -{% endraw %} - -Hello World in [Dale](/languages/dale) was written by: - -- rzuckerm -- tom-vthptvh - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/dart/index.md b/docs/projects/hello-world/dart/index.md deleted file mode 100644 index 0fedc7a89d..0000000000 --- a/docs/projects/hello-world/dart/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2018-06-21 -featured-image: hello-world-in-dart.jpg -last-modified: 2023-05-15 -layout: default -tags: -- dart -- hello-world -title: Hello World in Dart -title1: Hello World -title2: in Dart ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -void main() => print('Hello, World!'); - -``` - -{% endraw %} - -Hello World in [Dart](/languages/dart) was written by: - -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Coming from a Java background, the following snippet of code is downright -stripped to the barebones. - -In order to implement Hello World in Dart, developers need to understand only -three concepts like `main` methods, strings, and arrow functions. But look at the -code above, it seems deceptively easy, right? - -What is going on is `main()` only does one thing, print the phrase "Hello, World!". -We'll dig into how and why all of this happens in a bit, but it's important to -step away for a bit and just look at what's there and acknowledge how simple it is. - -In a Dart project, only one class would have a main method (`main()`). A `main` -method is how every Dart program knows where to start. Therefore, every program -must have exactly one of these `main` methods implemented. Don't worry too much -about the syntax. Just know that we need a `main` method. - -Then we have to output our greeting ("Hello, World!") to the command line. To -do so, we have to leverage a static method out of Dart's built-in library. It's -the `print` statement. It's a method like `main()` only difference is we put a -string inside the parentheses. It tells the computer to take the string and -print out so we can read it. - -The last concept are arrow functions (`=>`). These are methods like `print` or, -in this case, `main` that only do one thing. Because they only do one thing, we -can use `=>` from the method's definition (`main()`) directly to the logic. -Other more complex methods may require the use of `return`. But that's not -required in this case. - - -## How to Run the Solution - -To run this program, just download the [Dart interpreter][1]. Then, run this: - -``` -dart hello-world.dart -``` - -Alternatively, you can use an [online Dart interpreter][2]. - -[1]: https://dart.dev/tutorials/server/get-started#2-install-dart -[2]: https://dartpad.dev/dart diff --git a/docs/projects/hello-world/dg/index.md b/docs/projects/hello-world/dg/index.md deleted file mode 100644 index f4e9a526e3..0000000000 --- a/docs/projects/hello-world/dg/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Riley Martine -date: 2018-10-03 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-10-03 -layout: default -tags: -- dg -- hello-world -title: Hello World in Dg -title1: Hello World -title2: in Dg ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Dg](/languages/dg) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dg -print "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Dg](/languages/dg) was written by: - -- Riley Martine - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/discus/index.md b/docs/projects/hello-world/discus/index.md deleted file mode 100644 index ff58e772f9..0000000000 --- a/docs/projects/hello-world/discus/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-24 -layout: default -tags: -- discus -- hello-world -title: Hello World in Discus -title1: Hello World -title2: in Discus ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Discus](/languages/discus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```discus -module Main -import System.IO.Console - -where - -main () - = do writel "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Discus](/languages/discus) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/dusk/index.md b/docs/projects/hello-world/dusk/index.md deleted file mode 100644 index 1bf6a69f3a..0000000000 --- a/docs/projects/hello-world/dusk/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-12-30 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-12-30 -layout: default -tags: -- dusk -- hello-world -title: Hello World in Dusk -title1: Hello World -title2: in Dusk ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Dusk](/languages/dusk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dusk -println("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Dusk](/languages/dusk) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/egison/index.md b/docs/projects/hello-world/egison/index.md deleted file mode 100644 index 4a27d0e288..0000000000 --- a/docs/projects/hello-world/egison/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-04-15 -featured-image: hello-world-in-every-language.jpg -last-modified: 2024-04-15 -layout: default -tags: -- egison -- hello-world -title: Hello World in Egison -title1: Hello World -title2: in Egison ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Egison](/languages/egison) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```egison --- Prints "Hello, World!" to the standard output. -def main args := do - write "Hello, World!\n" - -``` - -{% endraw %} - -Hello World in [Egison](/languages/egison) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/eiffel/index.md b/docs/projects/hello-world/eiffel/index.md deleted file mode 100644 index 453182fae3..0000000000 --- a/docs/projects/hello-world/eiffel/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2021-05-25 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-11 -layout: default -tags: -- eiffel -- hello-world -title: Hello World in Eiffel -title1: Hello World -title2: in Eiffel ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Eiffel](/languages/eiffel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```eiffel -class - hello_world - -create - make - -feature - - make - do - print ("Hello, World!%N") - end - -end - -``` - -{% endraw %} - -Hello World in [Eiffel](/languages/eiffel) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/elena/index.md b/docs/projects/hello-world/elena/index.md deleted file mode 100644 index 1d98b8fbdf..0000000000 --- a/docs/projects/hello-world/elena/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-16 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-16 -layout: default -tags: -- elena -- hello-world -title: Hello World in Elena -title1: Hello World -title2: in Elena ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Elena](/languages/elena) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elena -public program() -{ - console.writeLine("Hello, World!"); -} - -``` - -{% endraw %} - -Hello World in [Elena](/languages/elena) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/elixir/index.md b/docs/projects/hello-world/elixir/index.md deleted file mode 100644 index 83454db706..0000000000 --- a/docs/projects/hello-world/elixir/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2019-05-08 -featured-image: hello-world-in-elixir.jpg -last-modified: 2023-05-15 -layout: default -tags: -- elixir -- hello-world -title: Hello World in Elixir -title1: Hello World -title2: in Elixir ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Elixir](/languages/elixir) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elixir -IO.puts "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Elixir](/languages/elixir) was written by: - -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Alright, let's get right to it. - -As we can see, Hello World in Elixir is just a single line of -code. As usual, let's dig into it a bit. - -Up first, we have a reference to the IO module. In Elixir, the `IO` -module is the standard tool for working with standard input and -output as well as files and other devices. So, it makes sense that -we'd use it here to gain access to standard output. - -Up next, we call the `puts` function of the `IO` module. Like print in -most languages, `puts` simply writes a value to standard output. In -fact, we aren't limited to standard output. We can redirect the output -to other streams such as standard error: - -```elixir -IO.puts :stderr, "Uh Oh!" -``` - -At any rate, `puts`, in our primary example, will simply write "Hello, -World!" to the user. To be honest, I'm surprised this is only the -second time we've seen the `puts` keyword in this series, the first being -Ruby. - - -## How to Run the Solution - -As always, if we want to give the code above a try, we can use an [online Elixir editor][1]. -Copy the code into the editor and hit run. - -Alternatively, we can run the solution locally if we download the latest -version of [Elixir][2]. After that, we'll want to get a copy of the solution. -Assuming Elixir is in our path, all we have to do is run the following -commands from the command line: - -```shell -elixir hello-world.ex -``` - -If successful, the "Hello, World" string should print to the console. - -[1]: https://www.jdoodle.com/execute-elixir-online/ -[2]: https://elixir-lang.org/install.html diff --git a/docs/projects/hello-world/elvish/index.md b/docs/projects/hello-world/elvish/index.md deleted file mode 100644 index 6587d16829..0000000000 --- a/docs/projects/hello-world/elvish/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-25 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-25 -layout: default -tags: -- elvish -- hello-world -title: Hello World in Elvish -title1: Hello World -title2: in Elvish ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -echo "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Elvish](/languages/elvish) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/emojicode/index.md b/docs/projects/hello-world/emojicode/index.md deleted file mode 100644 index aa641205ec..0000000000 --- a/docs/projects/hello-world/emojicode/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Thomas Braccia -date: 2018-05-05 -featured-image: hello-world-in-emojicode.jpg -last-modified: 2023-05-15 -layout: default -tags: -- emojicode -- hello-world -title: Hello World in Emojicode -title1: Hello World -title2: in Emojicode ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Emojicode](/languages/emojicode) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```emojicode -🏁 🍇 - 😀 🔤Hello, World!🔤❗️ -🍉 - -``` - -{% endraw %} - -Hello World in [Emojicode](/languages/emojicode) was written by: - -- Jeremy Grifski -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Thomas Braccia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's take a look at the Hello World sample. - -From there we will break down the rest. - -First `🏁` is symbolic of the starting flag in a race, and it represents that following it there will be a code block. Also when running it will run the code block that follows the Flag emoji. - -Next, code blocks are denoted by starting with a `🍇`, followed by the code, and ending with a `🍉`. - -One of the most important emojis is `😀` and this smiling emoji is passed a string and it outputs the string to standard output (in this case the string is `Hello, World!`). It must be terminated with `❗️`. - -Finally, the `🔤` emoji is used similarly to `"s` or `'s` in other languages as it holds a string within a pair of them. - - -## How to Run the Solution - -There is no better spot to learn how to run the Hello World program in Emojicode than directly from [Emojicode Official Docs][1] - -[1]: https://www.emojicode.org/docs/ diff --git a/docs/projects/hello-world/erlang/index.md b/docs/projects/hello-world/erlang/index.md deleted file mode 100644 index 9a6490df67..0000000000 --- a/docs/projects/hello-world/erlang/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Nick Keers -- rzuckerm -date: 2018-08-08 -featured-image: hello-world-in-erlang.jpg -last-modified: 2023-11-21 -layout: default -tags: -- erlang -- hello-world -title: Hello World in Erlang -title1: Hello World -title2: in Erlang ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Erlang](/languages/erlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```erlang --module(hello_world). --export([main/1]). - -main(_) -> - io:format("Hello, World!~n"). - -``` - -{% endraw %} - -Hello World in [Erlang](/languages/erlang) was written by: - -- Jeremy Grifski -- Nick Keers -- rzuckerm - -This article was written by: - -- Nick Keers -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Erlang looks scary when you first look at it, so we'll show the full program and -then we'll break it down into parts to fully describe it. - -### Breaking it down - -The first key part of an Erlang program is the `-module().` preprocessor directive: - -```erlang --module(hello_world). -``` - -Every Erlang file **must** start with this directive or you'll get a compiler error like the following: - -``` -file.erl:2: no module definition -``` - -Next, to use functions from the module we've written we have to export them explicitly. - -```erlang --export([main/1]). -``` - -This exports our `main` function, it takes one argument so we reference the function as `main/1`. The number of arguments is called the "arity" of the function. - - -Functions in Erlang start with an atom (for now, think of these as just lowercase letters + underscores), then the parameters, followed by an arrow `->`. The following functions are both valid: - -```erlang -my_function() -> - ok. - -myfunction() -> - ok. -``` - -Our `main` function only does one thing for this simple program, it calls the `format` function from the `io` module to print characters to standard output by default. `io:format()`. The string `"Hello world!~n"` includes the newline control sequence `~n` - you can see a list of control sequences available for use in the documentation for `io:fwrite` [here][1] (scroll down to "Available control sequences"). - -[1]: https://www.erlang.org/doc/man/io.html#fwrite-1 - - -## How to Run the Solution - -To run this example, just run `escript hello_world.erl`. diff --git a/docs/projects/hello-world/eta/index.md b/docs/projects/hello-world/eta/index.md deleted file mode 100644 index ef2d7cfa57..0000000000 --- a/docs/projects/hello-world/eta/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-25 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-25 -layout: default -tags: -- eta -- hello-world -title: Hello World in Eta -title1: Hello World -title2: in Eta ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Eta](/languages/eta) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```eta -module Main where -main :: IO () -main = putStrLn "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Eta](/languages/eta) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/euphoria/index.md b/docs/projects/hello-world/euphoria/index.md deleted file mode 100644 index cecaa4cad9..0000000000 --- a/docs/projects/hello-world/euphoria/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-14 -featured-image: hello-world-in-euphoria.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- hello-world -title: Hello World in Euphoria -title1: Hello World -title2: in Euphoria ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e - -puts(STDOUT, "Hello, World!\n") - -``` - -{% endraw %} - -Hello World in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -This article was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -The syntax of Euphoria is similar to C in some respects but without -braces and semicolons, and the `include` statement does not have -quotes or angle brackets around the file that is being included. - -```euphoria -include std/io.e -``` - -The `std/io.e` include file contains the definitions for standard -I/O file numbers. `STDOUT`, as expected, has the value of `1`. While -it is not necessary to include this, it makes the code more readable -since the intent of `STDOUT` is more obvious than just a hard-coded -value of `1`. - -```euphoria -puts(STDOUT, "Hello, World!\n") -``` - -The `puts` function is similar to the `fputs` function -in C, but the parameters are reversed. The first argument is the file -number. The second argument is the string to output. In C, the first -argument is the string to output, and the second argument is a -`FILE` pointer. - - -## How to Run the Solution - -If you want to run this program, you'll first need to download a -copy of the -[Euphoria interpreter](https://openeuphoria.org/wiki/view/DownloadEuphoria.wc), -and follow the installation instructions. From there, open a terminal, and -run this command: - -``` -eui hello_world.eu -``` diff --git a/docs/projects/hello-world/f-sharp/index.md b/docs/projects/hello-world/f-sharp/index.md deleted file mode 100644 index 1b62b0d9ad..0000000000 --- a/docs/projects/hello-world/f-sharp/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-04-27 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-27 -layout: default -tags: -- f-sharp -- hello-world -title: Hello World in F# -title1: Hello World -title2: in F# ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -printf "Hello, World!" - -``` - -{% endraw %} - -Hello World in [F#](/languages/f-sharp) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/f-star/index.md b/docs/projects/hello-world/f-star/index.md deleted file mode 100644 index 8f177edb81..0000000000 --- a/docs/projects/hello-world/f-star/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2021-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-05 -layout: default -tags: -- f-star -- hello-world -title: Hello World in F* -title1: Hello World -title2: in F* ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [F\*](/languages/f-star) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f\* -module HelloWorld - -open FStar.IO - -let main = print_string "Hello, World!\n" - -``` - -{% endraw %} - -Hello World in [F\*](/languages/f-star) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/factor/index.md b/docs/projects/hello-world/factor/index.md deleted file mode 100644 index 4770c8fa5b..0000000000 --- a/docs/projects/hello-world/factor/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2018-05-03 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-13 -layout: default -tags: -- factor -- hello-world -title: Hello World in Factor -title1: Hello World -title2: in Factor ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Factor](/languages/factor) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```factor -USE: io - -"Hello, World!" print - -``` - -{% endraw %} - -Hello World in [Factor](/languages/factor) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/felix/index.md b/docs/projects/hello-world/felix/index.md deleted file mode 100644 index 97e8e180ab..0000000000 --- a/docs/projects/hello-world/felix/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-04-29 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-29 -layout: default -tags: -- felix -- hello-world -title: Hello World in Felix -title1: Hello World -title2: in Felix ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Felix](/languages/felix) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```felix -println$ "Hello, World!"; - -``` - -{% endraw %} - -Hello World in [Felix](/languages/felix) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/fennel/index.md b/docs/projects/hello-world/fennel/index.md deleted file mode 100644 index f5bc897e85..0000000000 --- a/docs/projects/hello-world/fennel/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-12-30 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-12-30 -layout: default -tags: -- fennel -- hello-world -title: Hello World in Fennel -title1: Hello World -title2: in Fennel ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Fennel](/languages/fennel) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fennel -(print "Hello, World!") - -``` - -{% endraw %} - -Hello World in [Fennel](/languages/fennel) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/ferret/index.md b/docs/projects/hello-world/ferret/index.md deleted file mode 100644 index 4453caca2b..0000000000 --- a/docs/projects/hello-world/ferret/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- Arfat Salman -date: 2018-10-09 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-10-09 -layout: default -tags: -- ferret -- hello-world -title: Hello World in Ferret -title1: Hello World -title2: in Ferret ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Ferret](/languages/ferret) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ferret -(do - (println "Hello, World!")) - -``` - -{% endraw %} - -Hello World in [Ferret](/languages/ferret) was written by: - -- Arfat Salman - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/fetlang/index.md b/docs/projects/hello-world/fetlang/index.md deleted file mode 100644 index dfffdc1d3b..0000000000 --- a/docs/projects/hello-world/fetlang/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-05-03 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-05-03 -layout: default -tags: -- fetlang -- hello-world -title: Hello World in Fetlang -title1: Hello World -title2: in Fetlang ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Fetlang](/languages/fetlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fetlang -make slave scream "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Fetlang](/languages/fetlang) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/flix/index.md b/docs/projects/hello-world/flix/index.md deleted file mode 100644 index a93bd31d94..0000000000 --- a/docs/projects/hello-world/flix/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-01-04 -featured-image: hello-world-in-every-language.jpg -last-modified: 2025-01-04 -layout: default -tags: -- flix -- hello-world -title: Hello World in Flix -title1: Hello World -title2: in Flix ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Flix](/languages/flix) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```flix -def main(): Unit \ IO = println("Hello, World!") -``` - -{% endraw %} - -Hello World in [Flix](/languages/flix) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/formality/index.md b/docs/projects/hello-world/formality/index.md deleted file mode 100644 index 08fa443b5e..0000000000 --- a/docs/projects/hello-world/formality/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-16 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-16 -layout: default -tags: -- formality -- hello-world -title: Hello World in Formality -title1: Hello World -title2: in Formality ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Formality](/languages/formality) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```formality -Main: IO(Unit) - do IO { - IO.print("Hello, World!") - } - -``` - -{% endraw %} - -Hello World in [Formality](/languages/formality) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/forth/index.md b/docs/projects/hello-world/forth/index.md deleted file mode 100644 index 93b85ae8bf..0000000000 --- a/docs/projects/hello-world/forth/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-11-16 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-16 -layout: default -tags: -- forth -- hello-world -title: Hello World in Forth -title1: Hello World -title2: in Forth ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Forth](/languages/forth) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```forth -.( Hello, World!) CR -bye - -``` - -{% endraw %} - -Hello World in [Forth](/languages/forth) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/fortran/index.md b/docs/projects/hello-world/fortran/index.md deleted file mode 100644 index 6d4ef20e75..0000000000 --- a/docs/projects/hello-world/fortran/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-15 -featured-image: hello-world-in-every-language.jpg -last-modified: 2025-10-15 -layout: default -tags: -- fortran -- hello-world -title: Hello World in Fortran -title1: Hello World -title2: in Fortran ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program helloworld - implicit none - print '(A)', 'Hello, World!' -end program helloworld - -``` - -{% endraw %} - -Hello World in [Fortran](/languages/fortran) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/frege/index.md b/docs/projects/hello-world/frege/index.md deleted file mode 100644 index 9ddb3cad29..0000000000 --- a/docs/projects/hello-world/frege/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- joel ibaceta -- rzuckerm -date: 2018-11-14 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-02 -layout: default -tags: -- frege -- hello-world -title: Hello World in Frege -title1: Hello World -title2: in Frege ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Frege](/languages/frege) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```frege -module HelloWorld where - -main :: IO () -main = do putStrLn "Hello, World!" -``` - -{% endraw %} - -Hello World in [Frege](/languages/frege) was written by: - -- joel ibaceta -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/gerbil/index.md b/docs/projects/hello-world/gerbil/index.md deleted file mode 100644 index 85ff3ec6db..0000000000 --- a/docs/projects/hello-world/gerbil/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-07 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-07 -layout: default -tags: -- gerbil -- hello-world -title: Hello World in Gerbil -title1: Hello World -title2: in Gerbil ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Gerbil](/languages/gerbil) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gerbil -(export main) -(def (main . args) - (displayln "Hello, World!") -) - -``` - -{% endraw %} - -Hello World in [Gerbil](/languages/gerbil) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/gluon/index.md b/docs/projects/hello-world/gluon/index.md deleted file mode 100644 index 9b82b80cfa..0000000000 --- a/docs/projects/hello-world/gluon/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2018-12-30 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-16 -layout: default -tags: -- gluon -- hello-world -title: Hello World in Gluon -title1: Hello World -title2: in Gluon ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Gluon](/languages/gluon) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gluon -let io = import! std.io -io.print "Hello, World!\n" - -``` - -{% endraw %} - -Hello World in [Gluon](/languages/gluon) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/gnu-make/index.md b/docs/projects/hello-world/gnu-make/index.md deleted file mode 100644 index faf6c8be68..0000000000 --- a/docs/projects/hello-world/gnu-make/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- Ron Zuckerman -- rzuckerm -date: 2023-07-11 -featured-image: hello-world-in-gnu-make.jpg -last-modified: 2023-07-29 -layout: default -tags: -- gnu-make -- hello-world -title: Hello World in GNU Make -title1: Hello World -title2: in GNU Make ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -$(info Hello, World!) - -.PHONY: all -all: ;@: - -``` - -{% endraw %} - -Hello World in [GNU Make](/languages/gnu-make) was written by: - -- rzuckerm - -This article was written by: - -- Ron Zuckerman -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -The [info][1] function displays the text that follows it, so this just displays -"Hello, World!": - -```make -$(info Hello, World!) -``` - -In general, [all functions in GNU Make][5] have this form: - -```make -$(function arguments) -``` - -Since GNU Make is a build system, it needs something to build, or else it will -give this error: - -``` -make: *** No targets. Stop. -``` - -To give `make` something to do, a "do nothing" target called `all` is provided -like this: - -```make -.PHONY: all -all: ;@: -``` - -The [.PHONY][2] keyword specifies targets that will always be built, whether or -not they exist. In this case, that is the `all` target. This target is written -in the [alternate form][4] for brevity: - -```make -target: ;command -``` - -This means that whenever the target needs to be built, `make` will execute the -command following the semicolon. By default, `make` [echoes each command][3] -that it executes. To suppress this, `@` may be used before the command. The -[colon (:) command][6] just exits with non-error status. - -[1]: https://www.gnu.org/software/make/manual/html_node/Make-Control-Functions.html#index-info -[2]: https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html -[3]: https://www.gnu.org/software/make/manual/html_node/Echoing.html -[4]: https://www.gnu.org/software/make/manual/html_node/Rule-Syntax.html -[5]: https://www.gnu.org/software/make/manual/html_node/Syntax-of-Functions.html -[6]: https://man7.org/linux/man-pages/man1/colon.1p.html - - -## How to Run the Solution - -To run this program, download and install the latest GNU Make using these -instructions: - -* [Windows][7] -* For [Linux][8], see "How to Download" section -* [Mac][9] - -Download a copy of [Hello World in GNU Make][10], and run this command: - -``` -make -sf hello-world.mk -``` - -[7]: https://leangaurav.medium.com/how-to-setup-install-gnu-make-on-windows-324480f1da69 -[8]: https://www.incredibuild.com/integrations/gnu-make -[9]: https://formulae.brew.sh/formula/make -[10]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/g/gnu-make/hello-world.mk diff --git a/docs/projects/hello-world/go/index.md b/docs/projects/hello-world/go/index.md deleted file mode 100644 index 3831aa7e61..0000000000 --- a/docs/projects/hello-world/go/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Parker Johansen -date: 2018-03-25 -featured-image: hello-world-in-go.jpg -last-modified: 2019-04-01 -layout: default -tags: -- go -- hello-world -title: Hello World in Go -title1: Hello World -title2: in Go ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import "fmt" - -func main() { - fmt.Printf("Hello, World!") -} - -``` - -{% endraw %} - -Hello World in [Go](/languages/go) was written by: - -- Jeremy Griffith -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/goby/index.md b/docs/projects/hello-world/goby/index.md deleted file mode 100644 index cd93afa9d4..0000000000 --- a/docs/projects/hello-world/goby/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-20 -featured-image: hello-world-in-goby.jpg -last-modified: 2023-05-15 -layout: default -tags: -- goby -- hello-world -title: Hello World in Goby -title1: Hello World -title2: in Goby ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Goby](/languages/goby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```goby -puts("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Goby](/languages/goby) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -As seen many times in this collection, Hello World in Goby is actually -really simple. In total, it's one line of code which looks a lot like -Ruby. - -Alternatively, we can leave out the parentheses: - -```goby -puts "Hello, World!" -``` - -Naturally, `puts` writes the "Hello, World!" string to the user, and that's it! - - -## How to Run the Solution - -To run this solution, we can take advantage of the samplerunner script -included in the [Sample Programs repo][2]. If our system is setup -correctly, the following command should get the job done: - -```shell -glotter run -s hello-world.gb -``` - -Alternatively, we may want to get a copy of the Goby interpreter. [According -to the documentation][1], there are a few ways to do that, but we won't -dig into that now. - -Unlike many other languages in this collection, Goby does not have an online -interpreter at this time. - -[1]: https://github.com/goby-lang/goby -[2]: https://github.com/TheRenegadeCoder/sample-programs diff --git a/docs/projects/hello-world/golo/index.md b/docs/projects/hello-world/golo/index.md deleted file mode 100644 index a37929c25b..0000000000 --- a/docs/projects/hello-world/golo/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-05-24 -layout: default -tags: -- golo -- hello-world -title: Hello World in Golo -title1: Hello World -title2: in Golo ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Golo](/languages/golo) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```golo -module hello.World - -function main = |args| { - println("Hello, World!") -} - -``` - -{% endraw %} - -Hello World in [Golo](/languages/golo) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/gosu/index.md b/docs/projects/hello-world/gosu/index.md deleted file mode 100644 index f15891ca90..0000000000 --- a/docs/projects/hello-world/gosu/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Prakhar Pande -date: 2020-11-03 -featured-image: hello-world-in-every-language.jpg -last-modified: 2020-11-03 -layout: default -tags: -- gosu -- hello-world -title: Hello World in Gosu -title1: Hello World -title2: in Gosu ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Gosu](/languages/gosu) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gosu -print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Gosu](/languages/gosu) was written by: - -- Prakhar Pande - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/grain/index.md b/docs/projects/hello-world/grain/index.md deleted file mode 100644 index e4c02d3eae..0000000000 --- a/docs/projects/hello-world/grain/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-12-31 -featured-image: hello-world-in-every-language.jpg -last-modified: 2024-12-31 -layout: default -tags: -- grain -- hello-world -title: Hello World in Grain -title1: Hello World -title2: in Grain ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Grain](/languages/grain) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```grain -module Main - -print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Grain](/languages/grain) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/granule/index.md b/docs/projects/hello-world/granule/index.md deleted file mode 100644 index 249f45f1d1..0000000000 --- a/docs/projects/hello-world/granule/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- Dominic Orchard -- rzuckerm -date: 2022-12-06 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-16 -layout: default -tags: -- granule -- hello-world -title: Hello World in Granule -title1: Hello World -title2: in Granule ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Granule](/languages/granule) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```granule -main : () <{Stdout}> -main = toStdout "Hello, World!\n" - -``` - -{% endraw %} - -Hello World in [Granule](/languages/granule) was written by: - -- Dominic Orchard -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/gravity/index.md b/docs/projects/hello-world/gravity/index.md deleted file mode 100644 index 9ff2b86c33..0000000000 --- a/docs/projects/hello-world/gravity/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-04-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-24 -layout: default -tags: -- gravity -- hello-world -title: Hello World in Gravity -title1: Hello World -title2: in Gravity ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Gravity](/languages/gravity) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gravity -func main() { - System.print("Hello, World!"); -} - -``` - -{% endraw %} - -Hello World in [Gravity](/languages/gravity) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/groovy/index.md b/docs/projects/hello-world/groovy/index.md deleted file mode 100644 index 03ec64d8e0..0000000000 --- a/docs/projects/hello-world/groovy/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Griffith -date: 2018-04-19 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-19 -layout: default -tags: -- groovy -- hello-world -title: Hello World in Groovy -title1: Hello World -title2: in Groovy ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -println "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Groovy](/languages/groovy) was written by: - -- Jeremy Griffith - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/hack/index.md b/docs/projects/hello-world/hack/index.md deleted file mode 100644 index 5b9e36b127..0000000000 --- a/docs/projects/hello-world/hack/index.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2019-05-07 -featured-image: hello-world-in-hack.jpg -last-modified: 2023-08-23 -layout: default -tags: -- hack -- hello-world -title: Hello World in Hack -title1: Hello World -title2: in Hack ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Hack](/languages/hack) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```hack -<<__EntryPoint>> -function main(): void { - echo "Hello, World!"; -} - -``` - -{% endraw %} - -Hello World in [Hack](/languages/hack) was written by: - -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -At long last, let's take a stab at Hello World in Hack. - -Although Hack is derived from PHP, this code looks quite -different than PHP. The first thing you'll notice is this: - -```hack -<<__EntryPoint>> -``` - -The `<<...>>` is how Hack defines an attribute. The -[`__EntryPoint` attribute][1] defines a top-level function -where execution is started. That function is `main`, but it -does not have to be called `main`. Any function with the -`__EntryPoint` attribute will be considered the top-level -function. - -Next, the `main` function is defined. For this sample program, -there are no command-line arguments to process, so no arguments are -needed. The function does not return anything, so the return type -is `void`. - -Finally, there is the `echo` statement, which is exactly the same -as Hello World in PHP. However, I will point out that you can't mix -HTML with Hack like you can with PHP, so that's one of the biggest -syntactic differences. Otherwise, both languages perform a similar -function: backend web development. - -[1]: https://docs.hhvm.com/hack/attributes/predefined-attributes#__entrypoint - - -## How to Run the Solution - -If we want to try this code, we can use an [online Hack compiler][2]. - -Alternatively, we can download the Hack Virtual Machine to run -Hack code locally. From there, I recommend reading up on -[how to get started with Hack][3]. Getting everything up and running is -bit out of scope of this article. - -[2]: https://www.jdoodle.com/execute-hack-online/ -[3]: https://docs.hhvm.com/hack/getting-started/getting-started diff --git a/docs/projects/hello-world/haskell/index.md b/docs/projects/hello-world/haskell/index.md deleted file mode 100644 index 6df21856b8..0000000000 --- a/docs/projects/hello-world/haskell/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-08 -featured-image: hello-world-in-haskell.jpg -last-modified: 2023-05-15 -layout: default -tags: -- haskell -- hello-world -title: Hello World in Haskell -title1: Hello World -title2: in Haskell ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -main = putStrLn "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Haskell](/languages/haskell) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -As usual, let's get right to our implementation of Hello World in Haskell. - -First thing we will probably notice is that Haskell syntax is very different -from Lisp and Scheme. Despite all three of those languages being functional, -Haskell seems to have ditched the parentheses. In fact, even function calls -lack parentheses in Haskell. That's a new one for me. - -After the syntax, the next thing we should probably look at is that first line. -As usual, we have a module declaration which basically declares this file as -the main file. In other words, execution begins with this module. We saw -something similar in our Hello World in Go article. - -Finally, we have our `main` function. For someone who has never played with anything -like Haskell, this syntax is a bit bizarre. In fact, the main function doesn't look -like a function definition at all. At least, it doesn't look like what we've come to -expect from this series. - -That said, the `main` function does make a lot of sense if we think about it in terms -of mathematics. After all, math functions follow the exact same form: `f(x) = x`. - -At any rate, let's get back to the code. In this final line, we have the `main` keyword -which indicates the entry point to the program. From there, we compute the expression -on the other side of the equals sign. In this case, we have a print function (`putStrLn`) and our -string, and that's it. Pretty simple! - - -## How to Run the Solution - -If we want to run the snippets above, we can use an [online Haskell compiler][1]. All we -have to do is drop the code into the editor and hit run. - -Of course, we can also run the code locally if we just grab a copy of the latest Glasgow -Haskell Compiler. While we're downloading stuff, we should probably get a copy of the -solution. - -Assuming Haskell is now in the path, we can compile and run our solution using the -following commands: - -```shell -ghc hello-world.hs -hello-world.exe # Windows -./hello-world # Unix/Linux/Mac -``` - -And, that's it! The "Hello, World!" string should print straight to the console. - -[1]: https://www.onlinegdb.com/online_haskell_compiler diff --git a/docs/projects/hello-world/haxe/index.md b/docs/projects/hello-world/haxe/index.md deleted file mode 100644 index 749c02f9ab..0000000000 --- a/docs/projects/hello-world/haxe/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-08-12 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-08-12 -layout: default -tags: -- haxe -- hello-world -title: Hello World in Haxe -title1: Hello World -title2: in Haxe ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Haxe](/languages/haxe) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haxe -class HelloWorld { - static public function main() { - trace("Hello, World!"); - } -} - -``` - -{% endraw %} - -Hello World in [Haxe](/languages/haxe) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/hobbes/index.md b/docs/projects/hello-world/hobbes/index.md deleted file mode 100644 index e4729903da..0000000000 --- a/docs/projects/hello-world/hobbes/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-11-18 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-18 -layout: default -tags: -- hello-world -- hobbes -title: Hello World in Hobbes -title1: Hello World -title2: in Hobbes ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Hobbes](/languages/hobbes) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```hobbes -putStrLn("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Hobbes](/languages/hobbes) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/idris/index.md b/docs/projects/hello-world/idris/index.md deleted file mode 100644 index 0e67b61f8e..0000000000 --- a/docs/projects/hello-world/idris/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-11-21 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-11-21 -layout: default -tags: -- hello-world -- idris -title: Hello World in Idris -title1: Hello World -title2: in Idris ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Idris](/languages/idris) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```idris -module Main - -main : IO () -main = putStrLn "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Idris](/languages/idris) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/index.md b/docs/projects/hello-world/index.md deleted file mode 100644 index 47e6e8d235..0000000000 --- a/docs/projects/hello-world/index.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -date: 2018-03-15 -featured-image: hello-world-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- hello-world -title: Hello World -title1: Hello -title2: World ---- - - - -Welcome to the Hello World page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Hello World is a standard program used to introduce a programming language. -As a result, the rules are pretty simple: print "Hello, World!" to standard -output. Ideally, the solution should be as simple as possible. - - -## Requirements - -To properly implement Hello World, submit a file called Hello World using the -appropriate naming conventions for your language of choice. Upon execution, this -file should print "Hello, World!" to standard output. That's it! - - -## Testing - -Verify that the actual output matches the expected output -(see [Requirements](#requirements)). - - -## Articles - -There are 158 articles: - -- [Hello World in ALGOL 60](/projects/hello-world/algol60) -- [Hello World in ALGOL 68](/projects/hello-world/algol68) -- [Hello World in AWK](/projects/hello-world/awk) -- [Hello World in Ada](/projects/hello-world/ada) -- [Hello World in Agda](/projects/hello-world/agda) -- [Hello World in ArkScript](/projects/hello-world/arkscript) -- [Hello World in BAIK](/projects/hello-world/baik) -- [Hello World in Ballerina](/projects/hello-world/ballerina) -- [Hello World in Bash](/projects/hello-world/bash) -- [Hello World in Batch](/projects/hello-world/batch) -- [Hello World in Beef](/projects/hello-world/beef) -- [Hello World in Befunge](/projects/hello-world/befunge) -- [Hello World in Boo](/projects/hello-world/boo) -- [Hello World in Bracmat](/projects/hello-world/bracmat) -- [Hello World in Brainfuck](/projects/hello-world/brainfuck) -- [Hello World in C](/projects/hello-world/c) -- [Hello World in C#](/projects/hello-world/c-sharp) -- [Hello World in C\*](/projects/hello-world/c-star) -- [Hello World in C++](/projects/hello-world/c-plus-plus) -- [Hello World in C2](/projects/hello-world/c2) -- [Hello World in COBOL](/projects/hello-world/cobol) -- [Hello World in Carp](/projects/hello-world/carp) -- [Hello World in ChaiScript](/projects/hello-world/chaiscript) -- [Hello World in Chapel](/projects/hello-world/chapel) -- [Hello World in Clojure](/projects/hello-world/clojure) -- [Hello World in CoffeeScript](/projects/hello-world/coffeescript) -- [Hello World in Commodore BASIC](/projects/hello-world/commodore-basic) -- [Hello World in Crystal](/projects/hello-world/crystal) -- [Hello World in Cyclone](/projects/hello-world/cyclone) -- [Hello World in Cython](/projects/hello-world/cython) -- [Hello World in D](/projects/hello-world/d) -- [Hello World in Dale](/projects/hello-world/dale) -- [Hello World in Dart](/projects/hello-world/dart) -- [Hello World in Dg](/projects/hello-world/dg) -- [Hello World in Discus](/projects/hello-world/discus) -- [Hello World in Dusk](/projects/hello-world/dusk) -- [Hello World in Egison](/projects/hello-world/egison) -- [Hello World in Eiffel](/projects/hello-world/eiffel) -- [Hello World in Elena](/projects/hello-world/elena) -- [Hello World in Elixir](/projects/hello-world/elixir) -- [Hello World in Elvish](/projects/hello-world/elvish) -- [Hello World in Emojicode](/projects/hello-world/emojicode) -- [Hello World in Erlang](/projects/hello-world/erlang) -- [Hello World in Eta](/projects/hello-world/eta) -- [Hello World in Euphoria](/projects/hello-world/euphoria) -- [Hello World in F#](/projects/hello-world/f-sharp) -- [Hello World in F\*](/projects/hello-world/f-star) -- [Hello World in Factor](/projects/hello-world/factor) -- [Hello World in Felix](/projects/hello-world/felix) -- [Hello World in Fennel](/projects/hello-world/fennel) -- [Hello World in Ferret](/projects/hello-world/ferret) -- [Hello World in Fetlang](/projects/hello-world/fetlang) -- [Hello World in Flix](/projects/hello-world/flix) -- [Hello World in Formality](/projects/hello-world/formality) -- [Hello World in Forth](/projects/hello-world/forth) -- [Hello World in Fortran](/projects/hello-world/fortran) -- [Hello World in Frege](/projects/hello-world/frege) -- [Hello World in GNU Make](/projects/hello-world/gnu-make) -- [Hello World in Gerbil](/projects/hello-world/gerbil) -- [Hello World in Gluon](/projects/hello-world/gluon) -- [Hello World in Go](/projects/hello-world/go) -- [Hello World in Goby](/projects/hello-world/goby) -- [Hello World in Golo](/projects/hello-world/golo) -- [Hello World in Gosu](/projects/hello-world/gosu) -- [Hello World in Grain](/projects/hello-world/grain) -- [Hello World in Granule](/projects/hello-world/granule) -- [Hello World in Gravity](/projects/hello-world/gravity) -- [Hello World in Groovy](/projects/hello-world/groovy) -- [Hello World in Hack](/projects/hello-world/hack) -- [Hello World in Haskell](/projects/hello-world/haskell) -- [Hello World in Haxe](/projects/hello-world/haxe) -- [Hello World in Hobbes](/projects/hello-world/hobbes) -- [Hello World in Idris](/projects/hello-world/idris) -- [Hello World in Io](/projects/hello-world/io) -- [Hello World in Janet](/projects/hello-world/janet) -- [Hello World in Java](/projects/hello-world/java) -- [Hello World in JavaScript](/projects/hello-world/javascript) -- [Hello World in Julia](/projects/hello-world/julia) -- [Hello World in Kitten](/projects/hello-world/kitten) -- [Hello World in Koka](/projects/hello-world/koka) -- [Hello World in Kotlin](/projects/hello-world/kotlin) -- [Hello World in LOLCODE](/projects/hello-world/lolcode) -- [Hello World in Latte](/projects/hello-world/latte) -- [Hello World in Lily](/projects/hello-world/lily) -- [Hello World in Lisp](/projects/hello-world/lisp) -- [Hello World in Little](/projects/hello-world/little) -- [Hello World in LiveScript](/projects/hello-world/livescript) -- [Hello World in Lobster](/projects/hello-world/lobster) -- [Hello World in Lua](/projects/hello-world/lua) -- [Hello World in Lucee](/projects/hello-world/lucee) -- [Hello World in Malbolge](/projects/hello-world/malbolge) -- [Hello World in Mathematica](/projects/hello-world/mathematica) -- [Hello World in Mirth](/projects/hello-world/mirth) -- [Hello World in Modula-2](/projects/hello-world/modula2) -- [Hello World in MojiScript](/projects/hello-world/mojiscript) -- [Hello World in MoonScript](/projects/hello-world/moonscript) -- [Hello World in Never](/projects/hello-world/never) -- [Hello World in Nim](/projects/hello-world/nim) -- [Hello World in Nit](/projects/hello-world/nit) -- [Hello World in OCaml](/projects/hello-world/ocaml) -- [Hello World in Objective-C](/projects/hello-world/objective-c) -- [Hello World in Octave](/projects/hello-world/octave) -- [Hello World in Odin](/projects/hello-world/odin) -- [Hello World in Opa](/projects/hello-world/opa) -- [Hello World in Orc](/projects/hello-world/orc) -- [Hello World in Owl Lisp](/projects/hello-world/owl-lisp) -- [Hello World in PHP](/projects/hello-world/php) -- [Hello World in Pascal](/projects/hello-world/pascal) -- [Hello World in Perl](/projects/hello-world/perl) -- [Hello World in Phix](/projects/hello-world/phix) -- [Hello World in PicoLisp](/projects/hello-world/picolisp) -- [Hello World in Piet](/projects/hello-world/piet) -- [Hello World in Pineapple](/projects/hello-world/pineapple) -- [Hello World in Pinecone](/projects/hello-world/pinecone) -- [Hello World in Pony](/projects/hello-world/pony) -- [Hello World in PowerShell](/projects/hello-world/powershell) -- [Hello World in Prolog](/projects/hello-world/prolog) -- [Hello World in PureScript](/projects/hello-world/purescript) -- [Hello World in Pyret](/projects/hello-world/pyret) -- [Hello World in Python](/projects/hello-world/python) -- [Hello World in Quackery](/projects/hello-world/quackery) -- [Hello World in R](/projects/hello-world/r) -- [Hello World in Racket](/projects/hello-world/racket) -- [Hello World in Raku](/projects/hello-world/raku) -- [Hello World in Red](/projects/hello-world/red) -- [Hello World in Rexx](/projects/hello-world/rexx) -- [Hello World in Ring](/projects/hello-world/ring) -- [Hello World in Ruby](/projects/hello-world/ruby) -- [Hello World in Rust](/projects/hello-world/rust) -- [Hello World in Sather](/projects/hello-world/sather) -- [Hello World in Scala](/projects/hello-world/scala) -- [Hello World in Scheme](/projects/hello-world/scheme) -- [Hello World in Scilab](/projects/hello-world/scilab) -- [Hello World in Shen](/projects/hello-world/shen) -- [Hello World in Smalltalk](/projects/hello-world/smalltalk) -- [Hello World in Solidity](/projects/hello-world/solidity) -- [Hello World in Solisp](/projects/hello-world/solisp) -- [Hello World in Spry](/projects/hello-world/spry) -- [Hello World in Swift](/projects/hello-world/swift) -- [Hello World in TI-BASIC](/projects/hello-world/ti-basic) -- [Hello World in Tcl](/projects/hello-world/tcl) -- [Hello World in TeX](/projects/hello-world/tex) -- [Hello World in Terra](/projects/hello-world/terra) -- [Hello World in TypeScript](/projects/hello-world/typescript) -- [Hello World in Unicat](/projects/hello-world/unicat) -- [Hello World in V](/projects/hello-world/v) -- [Hello World in Verilog](/projects/hello-world/verilog) -- [Hello World in Verve](/projects/hello-world/verve) -- [Hello World in Vimscript](/projects/hello-world/vimscript) -- [Hello World in Visual Basic](/projects/hello-world/visual-basic) -- [Hello World in Whitespace](/projects/hello-world/whitespace) -- [Hello World in Wren](/projects/hello-world/wren) -- [Hello World in Wu](/projects/hello-world/wu) -- [Hello World in Wyvern](/projects/hello-world/wyvern) -- [Hello World in Yoix](/projects/hello-world/yoix) -- [Hello World in Zig](/projects/hello-world/zig) -- [Hello World in m4](/projects/hello-world/m4) -- [Hello World in x86-64](/projects/hello-world/x86-64) - -*** - - \ No newline at end of file diff --git a/docs/projects/hello-world/io/index.md b/docs/projects/hello-world/io/index.md deleted file mode 100644 index 2a9ade15c6..0000000000 --- a/docs/projects/hello-world/io/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-24 -layout: default -tags: -- hello-world -- io -title: Hello World in Io -title1: Hello World -title2: in Io ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Io](/languages/io) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```io -"Hello, World!" println - -``` - -{% endraw %} - -Hello World in [Io](/languages/io) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/janet/index.md b/docs/projects/hello-world/janet/index.md deleted file mode 100644 index 8f1e572a32..0000000000 --- a/docs/projects/hello-world/janet/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Chris Nord -date: 2019-10-02 -featured-image: hello-world-in-every-language.jpg -last-modified: 2019-10-02 -layout: default -tags: -- hello-world -- janet -title: Hello World in Janet -title1: Hello World -title2: in Janet ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Janet](/languages/janet) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```janet -(print "Hello, World!") - -``` - -{% endraw %} - -Hello World in [Janet](/languages/janet) was written by: - -- Chris Nord - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/java/index.md b/docs/projects/hello-world/java/index.md deleted file mode 100644 index fc2ee5d1cd..0000000000 --- a/docs/projects/hello-world/java/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- vivmost -date: 2018-03-15 -featured-image: hello-world-in-java.jpg -last-modified: 2022-10-10 -layout: default -tags: -- hello-world -- java -title: Hello World in Java -title1: Hello World -title2: in Java ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -class HelloWorld { - public static void main(String[] args) { - System.out.println("Hello, World!"); - } -} -``` - -{% endraw %} - -Hello World in [Java](/languages/java) was written by: - -- Jeremy Griffith -- Jeremy Grifski -- vivmost - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/javascript/index.md b/docs/projects/hello-world/javascript/index.md deleted file mode 100644 index 9ba474d455..0000000000 --- a/docs/projects/hello-world/javascript/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-05-04 -featured-image: hello-world-in-javascript.jpg -last-modified: 2025-05-04 -layout: default -tags: -- hello-world -- javascript -title: Hello World in JavaScript -title1: Hello World -title2: in JavaScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -console.log("Hello, World!"); - -``` - -{% endraw %} - -Hello World in [JavaScript](/languages/javascript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/julia/index.md b/docs/projects/hello-world/julia/index.md deleted file mode 100644 index cc2ccd8e53..0000000000 --- a/docs/projects/hello-world/julia/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-11 -featured-image: hello-world-in-julia.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- julia -title: Hello World in Julia -title1: Hello World -title2: in Julia ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -println("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Julia](/languages/julia) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -With the background out of the way, let's get right into our -implementation of Hello World in Julia. - -And unsurprisingly, that's it! We can implement Hello World -in Julia in a single line. - -Despite how easy the print functionality seems in Julia, there's -actually a lot going on. First of all, `println` makes a call to -print with an added newline character. - -The print function handles any sort of IO, so we could theoretically -pass our string to any IO stream. In this case, we leave the default -standard output. - -Regardless, print makes a call to a function named show. At that -point, I'm not sure what happens, but I suspect there's some C-level -call to `printf`. - - -## How to Run the Solution - -With our solution ready, we probably want to run it. Perhaps the easiest -thing to do would be to take advantage of [Julia's online editor][1]. -Unfortunately, it appears sign up is required to use it, but it's great -for running some code snippets. - -Alternatively, we can [download the latest version of Julia][2]. While we're -at it, we should probably get a copy of the Hello World in Julia solution. -With everything read to go, navigate the command line to the folder -containing the solution. Then, run the following: - -```shell -julia hello-world.jl -``` - -That should execute the script. Don't be afraid to leverage the Julia -documentation if you get stuck. - -[1]: https://www.tutorialspoint.com/execute_julia_online.php -[2]: https://julialang.org/downloads/ diff --git a/docs/projects/hello-world/kitten/index.md b/docs/projects/hello-world/kitten/index.md deleted file mode 100644 index 70c9f5fd06..0000000000 --- a/docs/projects/hello-world/kitten/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-05-03 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-05-03 -layout: default -tags: -- hello-world -- kitten -title: Hello World in Kitten -title1: Hello World -title2: in Kitten ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Kitten](/languages/kitten) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kitten -"Hello, World!" say - -``` - -{% endraw %} - -Hello World in [Kitten](/languages/kitten) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/koka/index.md b/docs/projects/hello-world/koka/index.md deleted file mode 100644 index 5dd48738cf..0000000000 --- a/docs/projects/hello-world/koka/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2022-04-28 -featured-image: hello-world-in-koka.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- koka -title: Hello World in Koka -title1: Hello World -title2: in Koka ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Koka](/languages/koka) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```koka -fun main() -{ - println("Hello, World!") -} - -``` - -{% endraw %} - -Hello World in [Koka](/languages/koka) was written by: - -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Now, let's see how we can print a simple "Hello World" in Koka. - -Just like many other programming languages, the `main` function is the starting -point of the code execution. To print, we use `println`, a built-in method that -prints a given string or variable to the console. - -Like many of the high-level language implementations in this series, this one -wasn't too bad. Wanna try it out? Check out this [online Koka editor][1]. - -[1]: https://tio.run/#koka - - -## How to Run the Solution - -If you want to run Koka at your local machine, you can always install the [Koka compiler][2] -and try the snippet locally. Then, run the following: - -```console -koka hello_world.kk -``` - -Also, you can check out the [Koka the documentation][3]. - -[2]: https://koka-lang.github.io/koka/doc/index.html#install -[3]: https://koka-lang.github.io/koka/doc/book.html diff --git a/docs/projects/hello-world/kotlin/index.md b/docs/projects/hello-world/kotlin/index.md deleted file mode 100644 index 26bbe72717..0000000000 --- a/docs/projects/hello-world/kotlin/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-10 -featured-image: hello-world-in-kotlin.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- kotlin -title: Hello World in Kotlin -title1: Hello World -title2: in Kotlin ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) { - println("Hello, World!") -} - -``` - -{% endraw %} - -Hello World in [Kotlin](/languages/kotlin) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's get down to business, Hello World in Kotlin. - -On the first line, we have the `package` declaration. Like most -languages, this basically declares the package or module name -of this file. If anyone needed to use a function in this file, -they could access it via the package name. - -Next, we have the function definition. In this first line, we -can see we define the `main` function which receives an array of -`String`s as input. In a lot of languages, types are declared in -type-var order, not in Kotlin. In Kotlin, we declare the variable -name before giving it a type. - -Finally, we print Hello World in Kotlin. Like many languages, -we use a simple call to the `println` function, so no surprises there. - - -## How to Run the Solution - -At this point, we probably want to actually run the Hello World in -Kotlin code snippet. Perhaps the easiest way to do so is to leverage -the online Kotlin editor. - -Alternatively, we can use the latest [standalone compiler][1]. Of course, -we'll want to get a copy of [Hello World in Kotlin][2] while we're at it. -With both in hand, all we need to do is navigate to the folder containing -our files and run the following: - -```shell -kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar -java -jar HelloWorld.jar -``` - -The standalone Kotlin compiler compiles Kotlin down to a -runnable Java Archive (`jar`) which we can then execute using the Java Runtime -Environment. - -[1]: https://kotlinlang.org/docs/command-line.html#manual-install -[2]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/k/kotlin/HelloWorld.kt diff --git a/docs/projects/hello-world/latte/index.md b/docs/projects/hello-world/latte/index.md deleted file mode 100644 index 27459e33c9..0000000000 --- a/docs/projects/hello-world/latte/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-24 -layout: default -tags: -- hello-world -- latte -title: Hello World in Latte -title1: Hello World -title2: in Latte ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Latte](/languages/latte) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```latte -println('Hello, World!') - -``` - -{% endraw %} - -Hello World in [Latte](/languages/latte) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/lily/index.md b/docs/projects/hello-world/lily/index.md deleted file mode 100644 index 058f290c5f..0000000000 --- a/docs/projects/hello-world/lily/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Griffith -date: 2018-04-22 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-22 -layout: default -tags: -- hello-world -- lily -title: Hello World in Lily -title1: Hello World -title2: in Lily ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Lily](/languages/lily) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lily -"Hello, World!" |> print - -``` - -{% endraw %} - -Hello World in [Lily](/languages/lily) was written by: - -- Jeremy Griffith - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/lisp/index.md b/docs/projects/hello-world/lisp/index.md deleted file mode 100644 index 9cfe51122b..0000000000 --- a/docs/projects/hello-world/lisp/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-08 -featured-image: hello-world-in-lisp.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- lisp -title: Hello World in Lisp -title1: Hello World -title2: in Lisp ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(format t "Hello, World!") -``` - -{% endraw %} - -Hello World in [Lisp](/languages/lisp) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Unfortunately, Lisp has many flavors which means the following implementation -of Hello World will likely only be applicable to handful of those flavors: - -That said, I'm happy to dig into this implementation of Hello World in Lisp. - -First things first, we have the `format` keyword. In Common Lisp, `forma`t is -basically the equivalent to `printf` in C. It basically takes some string and -outputs it to some destination. - -That brings us to this mysterious letter `t`. According to gigamonkeys, `t` is -actually the destination of the output. More specifically, `t` indicates standard -output. Another option is `NIL` which causes the string to be returned. - -Finally, we have our Hello World string. This is obviously what gets printed -to standard output. - - -## How to Run the Solution - -If we want to try it ourselves, we can copy the code above into an -[online Common Lisp compiler][1]. The one I linked is in CLISP, but it gets the job done. - -Alternatively, as mentioned before, we can download a copy of -[Steel Bank Common Lisp][2] as well as a [copy of the solution][3]. -Assuming SBCL is in the path, we can run a lisp file like a script as follows: - -```console -sbcl --script hello-world.lsp -``` - -And, that should produce the "Hello, World!" string on the command line. - -[1]: https://ideone.com/l/common-lisp-clisp -[2]: https://www.sbcl.org/platform-table.html -[3]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/l/lisp/hello-world.lsp diff --git a/docs/projects/hello-world/little/index.md b/docs/projects/hello-world/little/index.md deleted file mode 100644 index f0e3b4a56d..0000000000 --- a/docs/projects/hello-world/little/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-08-23 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-08-23 -layout: default -tags: -- hello-world -- little -title: Hello World in Little -title1: Hello World -title2: in Little ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Little](/languages/little) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```little -puts("Hello, World!"); - -``` - -{% endraw %} - -Hello World in [Little](/languages/little) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/livescript/index.md b/docs/projects/hello-world/livescript/index.md deleted file mode 100644 index aab23a9f1d..0000000000 --- a/docs/projects/hello-world/livescript/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-14 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-14 -layout: default -tags: -- hello-world -- livescript -title: Hello World in LiveScript -title1: Hello World -title2: in LiveScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [LiveScript](/languages/livescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```livescript -console.log 'Hello, World!' - -``` - -{% endraw %} - -Hello World in [LiveScript](/languages/livescript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/lobster/index.md b/docs/projects/hello-world/lobster/index.md deleted file mode 100644 index c61afe8e9e..0000000000 --- a/docs/projects/hello-world/lobster/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-14 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-14 -layout: default -tags: -- hello-world -- lobster -title: Hello World in Lobster -title1: Hello World -title2: in Lobster ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Lobster](/languages/lobster) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lobster -print "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Lobster](/languages/lobster) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/lolcode/index.md b/docs/projects/hello-world/lolcode/index.md deleted file mode 100644 index c183d75be4..0000000000 --- a/docs/projects/hello-world/lolcode/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Muhammad -date: 2018-05-11 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-08-10 -layout: default -tags: -- hello-world -- lolcode -title: Hello World in LOLCODE -title1: Hello World -title2: in LOLCODE ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [LOLCODE](/languages/lolcode) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lolcode -HAI 1.2 -VISIBLE "Hello, World!" -KTHXBYE - -``` - -{% endraw %} - -Hello World in [LOLCODE](/languages/lolcode) was written by: - -- Jeremy Grifski -- Muhammad - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/lua/index.md b/docs/projects/hello-world/lua/index.md deleted file mode 100644 index 454f11ae13..0000000000 --- a/docs/projects/hello-world/lua/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-19 -featured-image: hello-world-in-lua.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- lua -title: Hello World in Lua -title1: Hello World -title2: in Lua ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Lua](/languages/lua) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's get down to business. - -As we'll quickly notice, Hello World in Lua is not that exciting. In fact, there -are only a handful of languages with this boring of an implementation. For -instance, both Ruby and Python can perform Hello World in a similar fashion. -As a result, there's not a ton of explaining that needs to be done. - -Essentially, Lua has a native printing function which can be used to write a -string to stdout. In this case, it's called `print`, but the developers could -have just as easily called it `put`, `write`, `println`, or `puts`. - -As usual, we pass a string to the `print` function, and the function handles the -rest. - - -## How to Run the Solution - -Well, perhaps running the script will be more interesting. Fortunately for us, -there's [an online REPL for Lua][2], so we don't have to worry about downloading -anything. Once inside, drop the [code snippet][4] from above into the editor and hit -run. That's it! - -Alternatively, we could [download a copy of Lua][3], and run the solution locally. -Even better, we could build a Docker image, so we don't clutter our machine with -dependencies. If you want to help with the Docker initiative, head on over to -the Sample Programs repository and fork it. We appreciate the help! - -[2]: https://www.lua.org/cgi-bin/demo -[3]: https://www.lua.org/download.html -[4]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/l/lua/hello-world.lua diff --git a/docs/projects/hello-world/lucee/index.md b/docs/projects/hello-world/lucee/index.md deleted file mode 100644 index 56748bbcd3..0000000000 --- a/docs/projects/hello-world/lucee/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Genki Oji -- rzuckerm -date: 2019-10-02 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-16 -layout: default -tags: -- hello-world -- lucee -title: Hello World in Lucee -title1: Hello World -title2: in Lucee ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Lucee](/languages/lucee) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lucee - - - My first page - - - -
Hello, World!
-
- - - -``` - -{% endraw %} - -Hello World in [Lucee](/languages/lucee) was written by: - -- Genki Oji -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/m4/index.md b/docs/projects/hello-world/m4/index.md deleted file mode 100644 index 04b43e974c..0000000000 --- a/docs/projects/hello-world/m4/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-04 -featured-image: hello-world-in-every-language.jpg -last-modified: 2025-08-04 -layout: default -tags: -- hello-world -- m4 -title: Hello World in m4 -title1: Hello World -title2: in m4 ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -Hello, World! - -``` - -{% endraw %} - -Hello World in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/malbolge/index.md b/docs/projects/hello-world/malbolge/index.md deleted file mode 100644 index 1f97d18c9c..0000000000 --- a/docs/projects/hello-world/malbolge/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- Auberon López -date: 2024-10-23 -featured-image: hello-world-in-every-language.jpg -last-modified: 2024-10-23 -layout: default -tags: -- hello-world -- malbolge -title: Hello World in Malbolge -title1: Hello World -title2: in Malbolge ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Malbolge](/languages/malbolge) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```malbolge -('&%:9]!~}|z2Vxwv-,POqponl$Hjihf|B@@>,= - -Welcome to the [Hello World](/projects/hello-world) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -Print["Hello, World!"]; - -``` - -{% endraw %} - -Hello World in [Mathematica](/languages/mathematica) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/mirth/index.md b/docs/projects/hello-world/mirth/index.md deleted file mode 100644 index 78c9b196a2..0000000000 --- a/docs/projects/hello-world/mirth/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-11-18 -featured-image: hello-world-in-every-language.jpg -last-modified: 2025-01-25 -layout: default -tags: -- hello-world -- mirth -title: Hello World in Mirth -title1: Hello World -title2: in Mirth ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Mirth](/languages/mirth) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mirth -module sample-programs.hello-world - -import std.prelude -import std.world - -def main { - "Hello, World!" print -} - -``` - -{% endraw %} - -Hello World in [Mirth](/languages/mirth) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/modula2/index.md b/docs/projects/hello-world/modula2/index.md deleted file mode 100644 index 05cffd128a..0000000000 --- a/docs/projects/hello-world/modula2/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-14 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-14 -layout: default -tags: -- hello-world -- modula2 -title: Hello World in Modula-2 -title1: Hello World -title2: in Modula-2 ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Modula-2](/languages/modula2) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```modula-2 -MODULE HelloWorld; - -FROM StrIO IMPORT WriteString, WriteLn; - -BEGIN - WriteString('Hello, World!'); - WriteLn; -END HelloWorld. - -``` - -{% endraw %} - -Hello World in [Modula-2](/languages/modula2) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/mojiscript/index.md b/docs/projects/hello-world/mojiscript/index.md deleted file mode 100644 index 18ff586cd8..0000000000 --- a/docs/projects/hello-world/mojiscript/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Noah Nichols -- Patrick Biffle -date: 2018-10-15 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-10-17 -layout: default -tags: -- hello-world -- mojiscript -title: Hello World in MojiScript -title1: Hello World -title2: in MojiScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [MojiScript](/languages/mojiscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mojiscript -import log from 'mojiscript/console/log' -import pipe from 'mojiscript/core/pipe' -import run from 'mojiscript/core/run' - -const state = 'Hello, World!' - -const main = pipe ([ - log -]) - -run ({ state, main }) -``` - -{% endraw %} - -Hello World in [MojiScript](/languages/mojiscript) was written by: - -- Noah Nichols -- Patrick Biffle - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/moonscript/index.md b/docs/projects/hello-world/moonscript/index.md deleted file mode 100644 index 2a3f2f0577..0000000000 --- a/docs/projects/hello-world/moonscript/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- bassemmohamed1994 -- Jeremy Grifski -- rzuckerm -date: 2018-08-28 -featured-image: hello-world-in-moonscript.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- moonscript -title: Hello World in MoonScript -title1: Hello World -title2: in MoonScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [MoonScript](/languages/moonscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```moonscript -print "Hello, World!" - -``` - -{% endraw %} - -Hello World in [MoonScript](/languages/moonscript) was written by: - -- bassemmohamed1994 - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Hello World in MoonScript has a relatively simple implementation. - -All we have to do is call the built-in Moonscript function `print`, and that's it. -Behind the scenes, the code is compiled into Lua which is, in this case, -exactly the same. - -In other cases, it could be different. For instance, we could have an -implementation of some arithmetic which we print to the user: - -```moonscript -x = 10 -y = 15 -z = x + y -print y -``` - -The code is then compiled into Lua like this: - -```lua -local x = 10 -local y = 15 -local z = x + y -return print(y) -``` - -How cool is that? - - -## How to Run the Solution - -If your feeling adventurous today, You can quickly install MoonScript using one -of the following methods: - -**For Windows users**, you can [try installing the windows binaries][4]. - -**For Linux users**, install [LuaRocks][5] which is a package manager for Lua modules. -Then run the following command: - -```console -luarocks install moonscript -``` - -With the moon executable and Lua modules on your device, run your .moon file -with this command: - -```console -moon ./YOURFILE.moon -``` - -Also, you can compile your .moon file into Lua by using this command: - -```console -moonc ./YOURFILE.moon -``` - -Alternatively, you can always [run MoonScript using an online compiler][6]. - -[4]: https://moonscript.org/#windows_binaries -[5]: http://www.luarocks.org/ -[6]: https://moonscript.org/compiler/ diff --git a/docs/projects/hello-world/never/index.md b/docs/projects/hello-world/never/index.md deleted file mode 100644 index eeab497ec6..0000000000 --- a/docs/projects/hello-world/never/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- Ron Zuckerman -- smaludzi -date: 2018-09-20 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-23 -layout: default -tags: -- hello-world -- never -title: Hello World in Never -title1: Hello World -title2: in Never ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Never](/languages/never) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```never -func main() -> int { - prints("Hello, World!\n"); - 0 -} - -``` - -{% endraw %} - -Hello World in [Never](/languages/never) was written by: - -- Ron Zuckerman -- smaludzi - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/nim/index.md b/docs/projects/hello-world/nim/index.md deleted file mode 100644 index d2095ac17c..0000000000 --- a/docs/projects/hello-world/nim/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Michael Olson -date: 2019-10-16 -featured-image: hello-world-in-every-language.jpg -last-modified: 2019-10-16 -layout: default -tags: -- hello-world -- nim -title: Hello World in Nim -title1: Hello World -title2: in Nim ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Nim](/languages/nim) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nim -echo "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Nim](/languages/nim) was written by: - -- Michael Olson - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/nit/index.md b/docs/projects/hello-world/nit/index.md deleted file mode 100644 index 5c4e89fc6b..0000000000 --- a/docs/projects/hello-world/nit/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-25 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-25 -layout: default -tags: -- hello-world -- nit -title: Hello World in Nit -title1: Hello World -title2: in Nit ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Nit](/languages/nit) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nit -print "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Nit](/languages/nit) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/objective-c/index.md b/docs/projects/hello-world/objective-c/index.md deleted file mode 100644 index 912719d636..0000000000 --- a/docs/projects/hello-world/objective-c/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Ștefan-Iulian Alecu -date: 2018-03-21 -featured-image: hello-world-in-objective-c.jpg -last-modified: 2026-04-30 -layout: default -tags: -- hello-world -- objective-c -title: Hello World in Objective-C -title1: Hello World in -title2: Objective-C ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -int main() { - @autoreleasepool { - NSString* message = @"Hello, World!\n"; - printf("%s", message.UTF8String); - } -} -``` - -{% endraw %} - -Hello World in [Objective-C](/languages/objective-c) was written by: - -- Jeremy Griffith -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/ocaml/index.md b/docs/projects/hello-world/ocaml/index.md deleted file mode 100644 index 3d85f2fecc..0000000000 --- a/docs/projects/hello-world/ocaml/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-10-17 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-10-17 -layout: default -tags: -- hello-world -- ocaml -title: Hello World in OCaml -title1: Hello World -title2: in OCaml ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -print_string "Hello, World!\n";; - -``` - -{% endraw %} - -Hello World in [OCaml](/languages/ocaml) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/octave/index.md b/docs/projects/hello-world/octave/index.md deleted file mode 100644 index 42009e052c..0000000000 --- a/docs/projects/hello-world/octave/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-11 -featured-image: hello-world-in-octave.jpg -last-modified: 2023-12-11 -layout: default -tags: -- hello-world -- octave -title: Hello World in Octave -title1: Hello World -title2: in Octave ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -disp('Hello, World!'); - -``` - -{% endraw %} - -Hello World in [Octave](/languages/octave) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Syntax in [Octave][1] is based on its Octave scripting language. - -One line is all it takes! The "details-hidden" nature of the languages removes -the need to declare variables or classes before the fun begins. `disp` is the -command in Octave that formats data and displays it in the command window. In -this case, the data is the string "Hello, World!" (denoted by the -quotations). - -[1]: https://wiki.octave.org/GNU_Octave_Wiki - - -## How to Run the Solution - -If you want to try this out yourself: - -- Visit the [Octave Download page][2], and download the version for your Operating System (OS). -- Follow the installation instructions for your OS. -- Download the [program sample file][3]. - -Run the script like this: - -``` -octave -qf hello-world.m -``` - -Alternatively, you can use [Octave Online][4]. Just copy/paste the script into the input -command prompt and press Enter. - -[2]: https://octave.org/download -[3]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/o/octave/hello_world.m -[4]: https://octave-online.net/ diff --git a/docs/projects/hello-world/odin/index.md b/docs/projects/hello-world/odin/index.md deleted file mode 100644 index ad726fad03..0000000000 --- a/docs/projects/hello-world/odin/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2018-06-15 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-22 -layout: default -tags: -- hello-world -- odin -title: Hello World in Odin -title1: Hello World -title2: in Odin ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main; - -import "core:fmt"; - -main :: proc() { - fmt.println("Hello, World!"); -} - -``` - -{% endraw %} - -Hello World in [Odin](/languages/odin) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/opa/index.md b/docs/projects/hello-world/opa/index.md deleted file mode 100644 index 77e50ac6cf..0000000000 --- a/docs/projects/hello-world/opa/index.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Nico Villanueva -- rzuckerm -date: 2018-07-16 -featured-image: hello-world-in-opa.jpg -last-modified: 2023-12-09 -layout: default -tags: -- hello-world -- opa -title: Hello World in Opa -title1: Hello World -title2: in Opa ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Opa](/languages/opa) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```opa -function page() { -
Hello, World!
-} - -Server.start( - Server.http, - {~page, title: "SPEPL"} -) - -``` - -{% endraw %} - -Hello World in [Opa](/languages/opa) was written by: - -- Nico Villanueva -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Dec 09 2023 12:43:52. The solution was first committed on Jul 16 2018 16:34:59. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -As we mentioned, Opa code contains both front-end and server-side code. - -Notice how we define a function that returns raw HTML (a la JSX) and also set -up the server, all in the same file. The `Server.start` would be analogous to a -`main()` function. In this case, it's parameters take the server's settings -(default http server in this case) and a component to render. - -Also, we do not define imports of any kind. Everything is picked up off the -standard library. - - -## How to Run the Solution - -Typically at this point, we would cover a couple methods for running the solution. -For instance, we might share a link to an online editor. If that isn't available, -sometimes we'll even offer a way to run the solution locally on your PC. And, -you can do that with Opa, but we've opted instead to run Opa using Docker. - -### But First, Lemme Explain Docker - -To give a small overview of Docker and containers, imagine a virtual machine that -can boot up in less than a second, and the cost of provisioning, screwing up and -starting from scratch, is negligible. (Disclaimer: it's totally not like that, -but let's go with it.) - -I absolutely despise installing stuff, using it once or twice, and then forgetting -about it. I rarely remember to uninstall such things, and you can never be too -sure that it hasn't spread it's 1kB-sized temp/config files all over. That's why -I use containers. - -Would you like to see what happens when you create a thousand random files -in / ? Or how the system screws up when deleting /var ? Or even try out a -fork-bomb (Disclaimer 2: It's sorta dangerous in a container too)? - -Well now you can! You can spin up a container with a fresh Ubuntu in it, toy -around with it, and have it deleted upon exit. - -Containers are like VMs, except they share the kernel, network stack, and more, -with your own OS. They also can be constraint via cgroups (hard/soft CPU/memory -limits, and more). The root filesystem they use is mapped to folders in your -own machine, and whatever harm you do to them, does nothing on your system. - -So, you can "easily" install Opa (or any other language/thing) in a container, -play around, stop it, and when you delete the container, your OS is still as -clean as before. - -### How to Run Opa in Docker - -Finally, we can actually dig into the execution of Hello World in Opa. - -#### Image Setup - -For my next trick, I built a Dockerfile. It contains the definition of all -which needs to be installed and set up in order to run Opa, on Ubuntu. - -A Dockerfile is the definition/blueprint for an image, and an image is the -blueprint for a container. Applications run in containers. - -This is mostly not reversible: While you can commit a container into an image, -you cannot extract the Dockerfile from an image. - -So, if you want to build your own, local image, you can build it off the -Dockerfile, like so: - -```console -~/devel/SPEPL/archive/o/opa master -❯ ls -Dockerfile hello-world.opa README.md -~/devel/SPEPL/archive/o/opa master -❯ docker build --tag opalang:1.1.1 . -Sending build context to Docker daemon 5.12kB -Step 1/6 : FROM ubuntu ----> 113a43faa138 -[...] -Step 6/6 : RUN sudo npm install -g opabsl.opp intl-messageformat intl ----> Using cache ----> 626e6038445b -Successfully built 626e6038445b -Successfully tagged opalang:1.1.1 -``` - -Now you have a working image. Congrats. - -Docker has a "hub", conveniently called Docker Hub, where users can upload -their public images for others to use. So, instead of building your own image, -you could have just used mine: - -```console -~/devel/SPEPL/archive/o/opa master -❯ docker pull ajbetteridge/opa-1.1.1-build4308:opa-1.1.1-build4308 -Using tag: opa-1.1.1-build4308 -opa-1.1.1-build4308: Pulling from ajbetteridge/opa-1.1.1-build4308 -... -Status: Downloaded newer image for ajbetteridge/opa-1.1.1-build4308:opa-1.1.1-build4308 -``` - -So, finally, we can run hello-world.opa - -#### How to Run it for Real This Time - -Having the .opa file in the current directory, run: `docker run -it --rm --volume $PWD:/data/ ajbetteridge/opa-1.1.1-build4308:opa-1.1.1-build4308 opa /data/hello-world.opa` - -```console -~/devel/SPEPL/archive/o/opa master 31s -❯ ls -Dockerfile hello-world.opa README.md -~/devel/SPEPL/archive/o/opa master -❯ docker run -it --rm --volume $PWD:/data/ ajbetteridge/opa-1.1.1-build4308:opa-1.1.1-build4308 opa /data/hello-world.opa -~/devel/SPEPL/archive/o/opa master* -❯ ls -Dockerfile hello-world.js hello-world.opa package.json README.md -``` - -What we just did was run my image (if you want to use your own, replace -"ajbetteridge/opa-1.1.1-build4308" for what your provided as --tag in your docker build), -mapping the current directory ($PWD) to /data inside the container. - -This allows the Opa container to pick up the .opa file and compile it, inside -the container. It gave no output, but notice that there's a new hello-world.js - -As this .js has some npm dependencies, we can also run it inside a container, -using the same image: - -```console -~/devel/SPEPL/archive/o/opa master* 15m 22s -❯ docker run -it --rm -v $PWD:/data/ --publish 8080:8080 ajbetteridge/opa-1.1.1-build4308:opa-1.1.1-build4308 sh -c '/data/hello-world.js' -Http serving on http://380924f6ba29:8080 -``` - -Now we also `--published` the 8080 port. This maps your own 8080 port, to the -container's 8080. Having this up, if you fire up your browser and navigate -to http://localhost:8080, you'll see "Hello, World!", printed using Opa. diff --git a/docs/projects/hello-world/orc/index.md b/docs/projects/hello-world/orc/index.md deleted file mode 100644 index 66dbf47947..0000000000 --- a/docs/projects/hello-world/orc/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- Bassem Mohamed -date: 2018-08-28 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-08-28 -layout: default -tags: -- hello-world -- orc -title: Hello World in Orc -title1: Hello World -title2: in Orc ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Orc](/languages/orc) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```orc -Println("Hello, World!") >> -stop - -``` - -{% endraw %} - -Hello World in [Orc](/languages/orc) was written by: - -- Bassem Mohamed - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/owl-lisp/index.md b/docs/projects/hello-world/owl-lisp/index.md deleted file mode 100644 index 301234b876..0000000000 --- a/docs/projects/hello-world/owl-lisp/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-06-29 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-06-29 -layout: default -tags: -- hello-world -- owl-lisp -title: Hello World in Owl Lisp -title1: Hello World -title2: in Owl Lisp ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Owl Lisp](/languages/owl-lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```owl_lisp -(λ (args) (print "Hello, World!")) - -``` - -{% endraw %} - -Hello World in [Owl Lisp](/languages/owl-lisp) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/pascal/index.md b/docs/projects/hello-world/pascal/index.md deleted file mode 100644 index f9497cf893..0000000000 --- a/docs/projects/hello-world/pascal/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-10 -featured-image: hello-world-in-pascal.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- pascal -title: Hello World in Pascal -title1: Hello World -title2: in Pascal ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program HelloWorld(output); -begin - writeln('Hello, World!'); -end. - -``` - -{% endraw %} - -Hello World in [Pascal](/languages/pascal) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's dig right into Hello World in Pascal. - -As usual, we'll tackle this implementation line by line. Up -first, we have the program line which declares the name of -the program and a list of file descriptors. - -Up next, we have our main block which is denoted by the `begin` -and `end` keywords. Within this block, we have the print statement. -Of course, the function we use in Pascal is called `writeln`. - -Finally, we have a period, also known as a full stop. This -indicates the end of the program. - -As an added tidbit, semicolons mark the ends of statements, but -they are optional on the last statement in a block. In other words, -we could have removed the semicolon after the writeln command. - - -## How to Run the Solution - -If we want to try any of the Pascal code snippets from this article, -we can use an [online Pascal compiler][1]. We just need to drop the snippets -into the online editor and hit run. - -Of course, we can always [download and install Pascal locally][2]. While -we're downloading stuff, we should probably get a copy of the solution. - -Assuming Pascal is now in our path, we can navigate to our folder -containing the solution and run the following commands from the terminal: - -```shell -fpc hello-world.p -hello-world.exe # Windows -./hello-world # Unix/Linux/Mac -``` - -Since Pascal is a compiled language, we first need to compile our script. -After compilation, we'll have an executable we can run. When we run it, the -"Hello, World!" string should print to the console. - -[1]: https://www.onlinegdb.com/online_pascal_compiler -[2]: https://www.freepascal.org/download.html diff --git a/docs/projects/hello-world/perl/index.md b/docs/projects/hello-world/perl/index.md deleted file mode 100644 index d9cfcc1022..0000000000 --- a/docs/projects/hello-world/perl/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-08 -featured-image: hello-world-in-perl.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- perl -title: Hello World in Perl -title1: Hello World -title2: in Perl ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -print "Hello, World!"; - -``` - -{% endraw %} - -Hello World in [Perl](/languages/perl) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Without further ado, let's dive straight into our implementation -of Hello World in Perl. - -Well, that was anticlimactic. In fact, it was about as disappointing -as our implementations of Hello World in Python and Ruby. That said, -who doesn't love a simple implementation (talking to you, Java). - -At any rate, let's dig into this a little bit. For starters, we'll -notice there are no parentheses required for Perl's print function. -I use the word "required" because we can actually call print with them: - -```perl -print("Hello, World!"); -``` - -However, from my understanding, it's good Perl style to omit the parentheses -for built-in functions. - -Oh, I should probably clarify something. In Perl, they're not called -functions. Instead, they're called subroutines, and you can declare one -of your own using the sub keyword. That's a new one for me! - - -## How to Run the Solution - -As usual, we can try the solution using an [online Perl interpreter][1]. All we -have to do is drop the code into the editor and hit run. - -As an alternative, we can always run Perl locally. First, we'll need to get -the latest version of Perl from the [official website][2]. After that, we should -probably get a copy of the solution. Assuming Perl is now in our path, we can -get to work: - -```shell -perl hello-world.pl -``` - -Since Perl is a scripting language, we can quickly run the script with the -command above. If successful, "Hello, World!" should print to the console. - -[1]: https://www.onlinegdb.com/online_perl_compiler -[2]: https://www.perl.org/get.html diff --git a/docs/projects/hello-world/phix/index.md b/docs/projects/hello-world/phix/index.md deleted file mode 100644 index a7a4559de4..0000000000 --- a/docs/projects/hello-world/phix/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-17 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-04-17 -layout: default -tags: -- hello-world -- phix -title: Hello World in Phix -title1: Hello World -title2: in Phix ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Phix](/languages/phix) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```phix -puts(1, "Hello, World!") - -``` - -{% endraw %} - -Hello World in [Phix](/languages/phix) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/php/index.md b/docs/projects/hello-world/php/index.md deleted file mode 100644 index 4d31646c01..0000000000 --- a/docs/projects/hello-world/php/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Griffith -date: 2018-03-31 -featured-image: hello-world-in-php.jpg -last-modified: 2018-03-31 -layout: default -tags: -- hello-world -- php -title: Hello World in PHP -title1: Hello World -title2: in PHP ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Hello World](/projects/hello-world) in [PicoLisp](/languages/picolisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```picolisp -(prinl "Hello, World!") -(bye) - -``` - -{% endraw %} - -Hello World in [PicoLisp](/languages/picolisp) was written by: - -- Jeremy Grifski -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's break down what's happening. Since PicoLisp is a dialect of -Lisp, we can expect a ton of parentheses. In fact, our solution requires a single -set of parentheses at a minimum. - -Inside the parentheses, we have a function call. In this case, the print function -is named `prinl`, and the input is our "Hello, World!" string. When executed, our -string will print to the console. The `bye` function is required to exit the program. - - -## How to Run the Solution - -If we want to run the solution, we can try an [online editor][1]. However, I ran into some -problems with this particular editor. - -Alternatively, if we have access to a Unix, Linux, or Mac machine, we can easily -[download and install the latest version of PicoLisp][2]. That said, @cess11 has a great -video proving that this solution works: - -[![asciicast](https://asciinema.org/a/HdFjKizOUYKdcyFoG6h4RPhjn.svg)](https://asciinema.org/a/HdFjKizOUYKdcyFoG6h4RPhjn) - -And, that's it! If implemented correctly, the solution should print "Hello, World!" to the console. - -[1]: https://www.jdoodle.com/execute-picolisp-online/ -[2]: https://software-lab.de/down.html diff --git a/docs/projects/hello-world/piet/hello-world.png b/docs/projects/hello-world/piet/hello-world.png deleted file mode 100644 index 4ec6cdd3a5..0000000000 Binary files a/docs/projects/hello-world/piet/hello-world.png and /dev/null differ diff --git a/docs/projects/hello-world/piet/index.md b/docs/projects/hello-world/piet/index.md deleted file mode 100644 index 724427f62c..0000000000 --- a/docs/projects/hello-world/piet/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -authors: -- alope107 -date: 2023-04-25 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-04-25 -layout: default -tags: -- hello-world -- piet -title: Hello World in Piet -title1: Hello World -title2: in Piet ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Piet](/languages/piet) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -Hello World in Piet - -Hello World in [Piet](/languages/piet) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/pineapple/index.md b/docs/projects/hello-world/pineapple/index.md deleted file mode 100644 index 9f784b16e5..0000000000 --- a/docs/projects/hello-world/pineapple/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-19 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-19 -layout: default -tags: -- hello-world -- pineapple -title: Hello World in Pineapple -title1: Hello World -title2: in Pineapple ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Pineapple](/languages/pineapple) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pineapple -def .main - "Hello, World!".show - -``` - -{% endraw %} - -Hello World in [Pineapple](/languages/pineapple) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/pinecone/index.md b/docs/projects/hello-world/pinecone/index.md deleted file mode 100644 index b6e95d7cd8..0000000000 --- a/docs/projects/hello-world/pinecone/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- iwishiwasaneagle -date: 2020-10-04 -featured-image: hello-world-in-every-language.jpg -last-modified: 2020-10-04 -layout: default -tags: -- hello-world -- pinecone -title: Hello World in Pinecone -title1: Hello World -title2: in Pinecone ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Pinecone](/languages/pinecone) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pinecone -print: "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Pinecone](/languages/pinecone) was written by: - -- iwishiwasaneagle - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/pony/index.md b/docs/projects/hello-world/pony/index.md deleted file mode 100644 index d1dbb95bf5..0000000000 --- a/docs/projects/hello-world/pony/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-04-26 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-26 -layout: default -tags: -- hello-world -- pony -title: Hello World in Pony -title1: Hello World -title2: in Pony ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Pony](/languages/pony) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pony -actor Main - new create(env: Env) => - env.out.print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Pony](/languages/pony) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/powershell/index.md b/docs/projects/hello-world/powershell/index.md deleted file mode 100644 index 5f6a5dd643..0000000000 --- a/docs/projects/hello-world/powershell/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Devin Leaman -- Jeremy Grifski -- rzuckerm -date: 2018-05-28 -featured-image: hello-world-in-powershell.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- powershell -title: Hello World in PowerShell -title1: Hello World -title2: in PowerShell ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -Write-Host "Hello, World!" - -``` - -{% endraw %} - -Hello World in [PowerShell](/languages/powershell) was written by: - -- Devin Leaman - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's get something working! 😊 - -To execute this code, open a [PowerShell][1] console on any Windows machine as it -comes installed by default. You'll see the reply output in the window like so: - -```console -[20:35:40]:Alcha$ Write-Host 'Hello, World!' -Hello, World! -[20:35:56]:Alcha$ -``` - -As is the case with most modern scripting languages, getting a Hello World -sample running is really easy. - -[1]: https://learn.microsoft.com/en-us/powershell/ - - -## How to Run the Solution - -Instead of running the commands directly within the console though, write your -scripts in a file and call the file when necessary. Download a copy of the -[HelloWorld.ps1][2] file from the repository and open a console. - -Now, navigate to wherever you downloaded the script and execute it by calling -it like so: - -```console -.\HelloWorld.ps1 -``` - -This calls the script and returns the output to the console: - -```console -[20:35:40]:powershell$ .\HelloWorld.ps1 -Hello, World! -[20:35:56]:powershell$ -``` - -And, that's it! - -[2]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/powershell/HelloWorld.ps1 diff --git a/docs/projects/hello-world/prolog/index.md b/docs/projects/hello-world/prolog/index.md deleted file mode 100644 index 8224e09c8f..0000000000 --- a/docs/projects/hello-world/prolog/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-05-26 -featured-image: hello-world-in-every-language.jpg -last-modified: 2024-05-26 -layout: default -tags: -- hello-world -- prolog -title: Hello World in Prolog -title1: Hello World -title2: in Prolog ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Prolog](/languages/prolog) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```prolog -:- initialization(main). -main():- - write("Hello, World!\n"), - halt. - -``` - -{% endraw %} - -Hello World in [Prolog](/languages/prolog) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/purescript/index.md b/docs/projects/hello-world/purescript/index.md deleted file mode 100644 index 0b3d8baa9b..0000000000 --- a/docs/projects/hello-world/purescript/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Parker Johansen -- rzuckerm -date: 2018-12-22 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-20 -layout: default -tags: -- hello-world -- purescript -title: Hello World in PureScript -title1: Hello World -title2: in PureScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [PureScript](/languages/purescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```purescript -module Main where - -import Prelude -import Effect (Effect) -import Effect.Console (log) - -main :: Effect Unit -main = do - log "Hello, World!" - -``` - -{% endraw %} - -Hello World in [PureScript](/languages/purescript) was written by: - -- Parker Johansen -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/pyret/index.md b/docs/projects/hello-world/pyret/index.md deleted file mode 100644 index b8b857ae4f..0000000000 --- a/docs/projects/hello-world/pyret/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Griffith -date: 2018-04-23 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-23 -layout: default -tags: -- hello-world -- pyret -title: Hello World in Pyret -title1: Hello World -title2: in Pyret ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Pyret](/languages/pyret) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pyret -print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Pyret](/languages/pyret) was written by: - -- Jeremy Griffith - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/python/index.md b/docs/projects/hello-world/python/index.md deleted file mode 100644 index a771dbf89e..0000000000 --- a/docs/projects/hello-world/python/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-03-15 -featured-image: hello-world-in-python.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- python -title: Hello World in Python -title1: Hello World -title2: in Python ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -print('Hello, World!') - -``` - -{% endraw %} - -Hello World in [Python](/languages/python) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -I chose Python to start as it has probably the easiest and most readable -Hello World implementation in the realm of programming languages. - -We don't even have to compile anything. If we're in -the interpreter, we'll print right away. Otherwise, we can easily call the -script from the command line to get our result. - -As you can probably imagine, this code works because Python has a built-in -function called *print*. By passing that function a string, the interpreter -is able to call the Python libraries that make the print possible. - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of -[Hello World in Python][1]. After that, we should make sure we have the -[latest Python interpreter][2]. From there, we can simply run the following -command in the terminal: - -```console -python hello-world.py -``` - -Alternatively, we can copy the solution into an [online Python interpreter][3] -and hit run. - -[1]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/hello_world.py -[2]: https://www.python.org/downloads/ -[3]: https://www.online-python.com/ diff --git a/docs/projects/hello-world/quackery/index.md b/docs/projects/hello-world/quackery/index.md deleted file mode 100644 index c4902ea3ff..0000000000 --- a/docs/projects/hello-world/quackery/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- hello-world -- quackery -title: Hello World in Quackery -title1: Hello World -title2: in Quackery ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Quackery](/languages/quackery) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```quackery -say "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Quackery](/languages/quackery) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/r/index.md b/docs/projects/hello-world/r/index.md deleted file mode 100644 index 8e7e359949..0000000000 --- a/docs/projects/hello-world/r/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2018-04-27 -featured-image: hello-world-in-r.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- r -title: Hello World in R -title1: Hello World -title2: in R ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -cat("Hello, World!") - -``` - -{% endraw %} - -Hello World in [R](/languages/r) was written by: - -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Fortunately, this task can be solved in a concise one-liner. - -You can see the string "Hello, World!" as the argument of the function `cat`. -This function does all the work. If you are familiar with Bash, you may already -know the `cat` tool which prints the content of one or several files. - -Analogously, you can pass one or several strings to the `cat` function which prints -the input to the standard output. The function allows an optional argument `sep` -that represents the separator to use when you pass multiple strings. As a -consequence, the following is an equivalent alternative to the solution above: - -```r -cat("Hello", "World!", sep=", ") -``` - -In this call, "Hello" and "World!" are glued together by placing the specified -separator ", " between the two strings, resulting in the desired output -"Hello, World!". - -Now, we know what we need to produce the output. The next section explains how -we can also see the output of our program. - - -## How to Run the Solution - -In order to run the solution we need an [R compiler][3] first. Furthermore, we need -a copy of Hello World in [R][1]. From within the directory in which we saved the copy, -we run the following command on the command line: - -```console -Rscript hello-world.R # Linux/Unix -R.exe hello-world.R # Windows -``` - -Alternatively, you can try an [online compiler][4] if you want to save the time -required for installing the R environment locally. - -[3]: https://cran.r-project.org/ -[4]: https://www.mycompiler.io/new/r diff --git a/docs/projects/hello-world/racket/index.md b/docs/projects/hello-world/racket/index.md deleted file mode 100644 index f8148d7320..0000000000 --- a/docs/projects/hello-world/racket/index.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-08 -featured-image: hello-world-in-racket.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- racket -title: Hello World in Racket -title1: Hello World -title2: in Racket ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Racket](/languages/racket) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```racket -#lang racket/base -"Hello, World!" - -``` - -{% endraw %} - -Hello World in [Racket](/languages/racket) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's go ahead and dig into our implementation of Hello World in Racket. - -Up first, we have this peculiar line that looks kind of like a comment in Python -or an import in C. As it turns out, the `lang` line specifies the language used by -the interpreter. In fact, I already mentioned that there's a module which -provides syntax for static typing in Racket. - -In this case, the language we have chosen is `racket/base`. This only provides us -the core Racket functionality. As an alternative, we could have easily specified -racket alone. - -Finally, we have our print line. To be honest, we could have used the print -functionality: - -```racket -#lang racket/base -(print "Hello, World!) -``` - -However, I wanted to show that you can implement Hello World without the mess of -parentheses. That's because Racket automatically prints constants. If we had a -slightly more complicated expression: - -```racket -#lang racket -+ 2 2 -``` - -We would see the three constants returned to us in their stack order: - -```racket -# -2 -2 -``` - -We would need parentheses to actually evaluate this expression. - - -## How to Run the Solution - -At any rate, I think we're done here. If we want to try to run the solution, we -can plug some of this code into an [online Racket interpreter][1]. - -Alternatively, we can [download the latest version of Racket][2] and [get a copy of -the solution][3]. Assuming Racket is now in the path, we can just run the following -to execute Hello World in Racket: - -```shell -racket hello-world.rkt -``` - -And, that's it. If successful, the "Hello, World!" string should print to the console. - -[1]: https://onecompiler.com/racket/ -[2]: https://download.racket-lang.org/ -[3]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/r/racket/hello-world.rkt diff --git a/docs/projects/hello-world/raku/index.md b/docs/projects/hello-world/raku/index.md deleted file mode 100644 index cb51539979..0000000000 --- a/docs/projects/hello-world/raku/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2020-11-02 -featured-image: hello-world-in-every-language.jpg -last-modified: 2020-11-02 -layout: default -tags: -- hello-world -- raku -title: Hello World in Raku -title1: Hello World -title2: in Raku ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Raku](/languages/raku) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```raku -say 'Hello, World!' - -``` - -{% endraw %} - -Hello World in [Raku](/languages/raku) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/red/index.md b/docs/projects/hello-world/red/index.md deleted file mode 100644 index b38b1774e0..0000000000 --- a/docs/projects/hello-world/red/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- Johnny Fang -- rzuckerm -- shubhragupta-code -date: 2018-04-20 -featured-image: hello-world-in-red.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- red -title: Hello World in Red -title1: Hello World -title2: in Red ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Red](/languages/red) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```red -Red [Title: "Hello World in Red"] - -print "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Red](/languages/red) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- Johnny Fang -- rzuckerm -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's get right to our implementation of Hello World in Red. - -Honestly, this is about the weirdest syntax I've ever seen, so I really -had to dig into the docs. - -[According to Helpin'Red][1], the first line in our solution is the header, -and it's absolutely necessary for all scripts. The header is composed of two -parts: the `Red` keyword and the block.. - -Now, every script will have the `Red` keyword. As for the block, well, that -will vary per script. Honestly, the information in that block is largely -optional, but it can be used to declare script information such as a title, -a description, a version, and an author. In this case, I simply gave the -script a title. - -In addition to arbitrary information, the first block can also be used to -import libraries. For example, we could have implemented Hello World in -Red as a GUI: - -```red -Red [needs: 'view] - -view [ - text "Hello, World!" -] -``` - -Here, we use the header block to import the graphics view library. Then, -we use that library to display a window containing "Hello, World!" - -At any rate, the last line in our original implementation clearly prints -"Hello, World!" to the user. We've seen this plenty of times already so -no need to dig into it. - -[1]: https://helpin.red/Helloworld-runandcompile.html - - -## How to Run the Solution - -If we're looking to run this solution, perhaps the easiest way to do so -is to [download the latest Red toolchain][2]. Of course, we'll also want -to grab a copy of the [Hello World script from GitHub][3]. - -Now, drop both of those files in the same folder and run the following: - -```console -red hello-world.red -``` - -If you're a Windows user, you may need to call the executable directly. - -In addition, we can compile our script using the following command: - -```console -red -c hello-world.red -``` - -At this point, I would usually share some online editor you could use to test -code, but Red doesn't appear to have one. If one exists, let me know in -the comments. - -[2]: https://www.red-lang.org/p/download.html -[3]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/r/red/hello-world.red - diff --git a/docs/projects/hello-world/rexx/index.md b/docs/projects/hello-world/rexx/index.md deleted file mode 100644 index 0d6ea3f918..0000000000 --- a/docs/projects/hello-world/rexx/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-19 -featured-image: hello-world-in-rexx.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- rexx -title: Hello World in Rexx -title1: Hello World -title2: in Rexx ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Rexx](/languages/rexx) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rexx -say "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Rexx](/languages/rexx) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -To print 'Hello World!' in Rexx, we need to take note of two points: - -- the program starts with a comment line to identify it as a REXX program. Hence, comments are added between `/* */`. -- use `SAY` command before the desired output or value - -So, let's get to the point and see how to implement the solution: - -```rexx -/* Print 'Hello-World!' sample program in REXX */ -SAY 'Hello World!' -``` - -And that's it! It is a very simple one-liner program with a few specifications. The comments tell us what the program does and the intruction 'say' is used to print the program 'Hello World!'. - -`SAY` is a basic command to print output on the same lines as `PRINT` from Python. It remains constant regardless of the version. - - -## How to Run the Solution - -In order to run this program, you can install REXX through [online sources](https://www.tutorialspoint.com/rexx/rexx_installation.htm) and run it. Alternatively, you can directly run it on [online interpreters](https://www.tutorialspoint.com/execute_rexx_online.php). diff --git a/docs/projects/hello-world/ring/index.md b/docs/projects/hello-world/ring/index.md deleted file mode 100644 index 0656318116..0000000000 --- a/docs/projects/hello-world/ring/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Griffith -date: 2018-04-23 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-23 -layout: default -tags: -- hello-world -- ring -title: Hello World in Ring -title1: Hello World -title2: in Ring ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Ring](/languages/ring) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ring -see "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Ring](/languages/ring) was written by: - -- Jeremy Griffith - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/ruby/index.md b/docs/projects/hello-world/ruby/index.md deleted file mode 100644 index 1eb61c8c0f..0000000000 --- a/docs/projects/hello-world/ruby/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Griffith -date: 2018-03-21 -featured-image: hello-world-in-ruby.jpg -last-modified: 2018-03-21 -layout: default -tags: -- hello-world -- ruby -title: Hello World in Ruby -title1: Hello World -title2: in Ruby ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -puts 'Hello, World!' - -``` - -{% endraw %} - -Hello World in [Ruby](/languages/ruby) was written by: - -- Jeremy Griffith - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/rust/index.md b/docs/projects/hello-world/rust/index.md deleted file mode 100644 index 7ee967bc54..0000000000 --- a/docs/projects/hello-world/rust/index.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- Johnny Fang -- rzuckerm -- shubhragupta-code -date: 2018-03-31 -featured-image: hello-world-in-rust.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- rust -title: Hello World in Rust -title1: Hello World -title2: in Rust ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -fn main() { - println!("Hello, World!"); -} - -``` - -{% endraw %} - -Hello World in [Rust](/languages/rust) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- Johnny Fang -- rzuckerm -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -In fact, Rust's implementation is even easier. There's no need to import -any IO packages to get access to _println_. We just need to create our `main` -function, add our print code, and we're done. - -But, wait a minute. That __print line__ seems a little off. What's with the bang `!`? -To be honest, I had to do a bit of digging for this. As it turns out, _println_ is -not a function at all. __It's a built-in macro__. That's a new term for me, so let's -learn a little more about it. - -According to [the Rust Programming Language book][2], macros are a language feature -that allow you to abstract syntax. In other words, macros allow you to do some -metaprogramming by adding grammar to Rust's abstract syntax tree. Perhaps an example -would make more sense: - -{% raw %} -```rust -macro_rules! println { - () => { - $crate::print!("\n") - }; - ($($arg:tt)*) => {{ - $crate::io::_print($crate::format_args_nl!($($arg)*)); - }}; -} -``` -{% endraw %} - -This is the actual [definition of the _println_ macro in Rust][3] (click on "source"). -I won't go into exactly what's happening, but basically we have defined two available patterns -for _println_: empty and variable arguments. Rust functions don't -have support for variable arguments, so you can add the functionality with macros. - -That said, I'm only just learning macros for the first time, so I recommend an -article by Kasper Andersen called [why Rust has macros][4]. It's quite thorough, -and I think it does a better job than Rust's documentation. - -[2]: https://doc.rust-lang.org/book/ -[3]: https://doc.rust-lang.org/std/macro.println.html -[4]: https://kasma1990.gitlab.io/2018/03/04/why-rust-has-macros/ - - -## How to Run the Solution - -As always, we can try out this code using an [online Rust compiler][5]. All we -need to do is drop the code into the editor and hit run. - -Alternatively, we can [download the latest Rust compiler][6] and a [copy of the solution][7]. -Then, assuming the compiler is in the path, navigate to folder with the solution and run -the following in Windows: - -```console -rustc hello-world.rs -hello-world.exe -``` - -Of course, in Unix-based environments, the following will run the new binary: - -```console -./hello-world -``` - -And, that's it! "Hello, World!" should print directly to the console. - -[5]: https://play.rust-lang.org/ -[6]: https://www.rust-lang.org/tools/install -[7]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/r/rust/hello-world.rs diff --git a/docs/projects/hello-world/sather/index.md b/docs/projects/hello-world/sather/index.md deleted file mode 100644 index 7fda0a1523..0000000000 --- a/docs/projects/hello-world/sather/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Prakhar Pande -date: 2020-10-02 -featured-image: hello-world-in-every-language.jpg -last-modified: 2020-10-02 -layout: default -tags: -- hello-world -- sather -title: Hello World in Sather -title1: Hello World -title2: in Sather ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Sather](/languages/sather) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```sather -class HELLO_WORLD is - main is - #OUT+"Hello, World!"; - end; -end; - -``` - -{% endraw %} - -Hello World in [Sather](/languages/sather) was written by: - -- Prakhar Pande - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/scala/index.md b/docs/projects/hello-world/scala/index.md deleted file mode 100644 index 00d6655888..0000000000 --- a/docs/projects/hello-world/scala/index.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Ștefan-Iulian Alecu -date: 2019-05-08 -featured-image: hello-world-in-scala.jpg -last-modified: 2026-04-11 -layout: default -tags: -- hello-world -- scala -title: Hello World in Scala -title1: Hello World -title2: in Scala ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -object HelloWorld: - def main(args: Array[String]): Unit = - println("Hello, World!") -``` - -{% endraw %} - -Hello World in [Scala](/languages/scala) was written by: - -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Up first, we have the `class` definition much like Java. However, -there are two interesting keywords here: `object` and `extends`. - -In Java, we would typically define a class using the `class` keyword. -In fact, we normally even do that in Scala, so what's with this -`object` keyword? Well, as it turns out, object is used when we want -to define a singleton. - -In object-oriented languages, a singleton is an object which has a -one and only one policy. In other words, only one instance of the -object will ever exist. Personally, I've only ever used the singleton -design pattern to track state in a video game. Beyond that, I would -consider it an anti-pattern. - -That said, singletons are a feature in Scala, and they're typically -used to define static functions. In other words, singletons can be -used to generate utility classes that don't need to be instantiated -to access their functionality. - -In addition, singletons in Scala are often used as companion objects, -but I can't say I totally understand what that is. Let me know in the -comments. - -Anyway, in this case, our singleton also extends App. This allows us -to bypass the creation of a main method. We could have just as easily -implemented Hello World in Scala as follows: - -```scala -object HelloWorld { - def main(args: Array[String]): Unit = { - println("Hello, World!"); - } -} -``` - -At this point, we have something reminiscent of Java. Of course, the syntax -is a bit different, but it looks about the same if we squint hard enough. - -Finally, the only thing we have left is the print statement which is pretty -typical at this point. Not much of a surprise there! - - -## How to Run the Solution - -If we want to try the code above, we can use an online Scala compiler. Just -take the code above and drop it into the editor before hitting run. - -Alternatively, we can always try to run the code locally. First, we'll need -to follow the directions when downloading and installing Scala. Then, we'll -probably want to get a copy of the solution. - -With the heavy lifting out of the way, we should be able to simply run the -following commands from the command line: - -```shell -scalac hello-world.scala -scala hello-world -``` - -As we can see, Scala can be executed in pretty much the same way as Java. If -all goes well, the last command should print the "Hello, World!" string. diff --git a/docs/projects/hello-world/scheme/index.md b/docs/projects/hello-world/scheme/index.md deleted file mode 100644 index ab41845238..0000000000 --- a/docs/projects/hello-world/scheme/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-08 -featured-image: hello-world-in-scheme.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- scheme -title: Hello World in Scheme -title1: Hello World -title2: in Scheme ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Scheme](/languages/scheme) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scheme -(display "Hello, World!") - -``` - -{% endraw %} - -Hello World in [Scheme](/languages/scheme) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -If you checked out the tutorial on Hello World in Lisp, then this should be easy. First things first, we have the *display* function. The *display* function works exactly as you would expect. It takes some input and displays it to the user. - -As a result, it's natural to expect that the input in this case is Hello World. All we do is pass the Hello World string to display, and we're done. - - -## How to Run the Solution - -As usual, we can give it a go with an [online Scheme interpreter][1]. Just drop the code above into the editor and hit run. - -Alternatively, we can download [CHICKEN Scheme][2] and a copy of the solution. Assuming CHICKEN Scheme is on our path, we can run the following from a command line: - -```bash -csi -s hello-world.scm -``` -That will run the Scheme file as a script which will quickly print the "Hello, World!" string. - -[1]: https://www.jdoodle.com/execute-scheme-online/ -[2]: https://call-cc.org/ diff --git a/docs/projects/hello-world/scilab/index.md b/docs/projects/hello-world/scilab/index.md deleted file mode 100644 index 7e5155c431..0000000000 --- a/docs/projects/hello-world/scilab/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-11-20 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-20 -layout: default -tags: -- hello-world -- scilab -title: Hello World in Scilab -title1: Hello World -title2: in Scilab ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Scilab](/languages/scilab) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scilab -mprintf('%s', 'Hello, World!') - -``` - -{% endraw %} - -Hello World in [Scilab](/languages/scilab) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/shen/index.md b/docs/projects/hello-world/shen/index.md deleted file mode 100644 index 0429ff1f6b..0000000000 --- a/docs/projects/hello-world/shen/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-11-20 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-11-20 -layout: default -tags: -- hello-world -- shen -title: Hello World in Shen -title1: Hello World -title2: in Shen ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Shen](/languages/shen) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```shen -(output "Hello, World!~%") - -``` - -{% endraw %} - -Hello World in [Shen](/languages/shen) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/smalltalk/index.md b/docs/projects/hello-world/smalltalk/index.md deleted file mode 100644 index 5de656e87d..0000000000 --- a/docs/projects/hello-world/smalltalk/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-04-26 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-26 -layout: default -tags: -- hello-world -- smalltalk -title: Hello World in Smalltalk -title1: Hello World -title2: in Smalltalk ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Smalltalk](/languages/smalltalk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```smalltalk -Transcript show: 'Hello, World!'. - -``` - -{% endraw %} - -Hello World in [Smalltalk](/languages/smalltalk) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/solidity/index.md b/docs/projects/hello-world/solidity/index.md deleted file mode 100644 index 4792857529..0000000000 --- a/docs/projects/hello-world/solidity/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2022-04-28 -featured-image: hello-world-in-solidity.jpg -last-modified: 2023-12-16 -layout: default -tags: -- hello-world -- solidity -title: Hello World in Solidity -title1: Hello World -title2: in Solidity ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Solidity](/languages/solidity) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```solidity -// SPDX-License-Identifier: MIT -pragma solidity ^0.8; - -contract HelloWorld { - function main (string memory) public pure returns (string memory) { - return 'Hello, World!\n'; - } -} - -``` - -{% endraw %} - -Hello World in [Solidity](/languages/solidity) was written by: - -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -While the format of Solidity looks a bit different from the more popular -programming languages today, what's happening behind is fairly straightforward. - -First we import the version of Solidity we'd like to use. Then we create a -function and specify we'd only like to return a string. And, voila! - - -## How to Run the Solution - -If you want to run the solution, remix provides an [IDE][5] you can visit to write -and execute the smart contract. Every piece of code written in Solidity, or any -blockchain programming language, is considered a smart contract. - -[5]: https://remix-project.org/ diff --git a/docs/projects/hello-world/solisp/index.md b/docs/projects/hello-world/solisp/index.md deleted file mode 100644 index 9a3729e328..0000000000 --- a/docs/projects/hello-world/solisp/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- Stuart Irwin -date: 2020-03-05 -featured-image: hello-world-in-every-language.jpg -last-modified: 2020-03-05 -layout: default -tags: -- hello-world -- solisp -title: Hello World in Solisp -title1: Hello World -title2: in Solisp ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Solisp](/languages/solisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```solisp -"Hello, World!" -``` - -{% endraw %} - -Hello World in [Solisp](/languages/solisp) was written by: - -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/spry/index.md b/docs/projects/hello-world/spry/index.md deleted file mode 100644 index a364a40134..0000000000 --- a/docs/projects/hello-world/spry/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-24 -layout: default -tags: -- hello-world -- spry -title: Hello World in Spry -title1: Hello World -title2: in Spry ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Spry](/languages/spry) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```spry -echo "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Spry](/languages/spry) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/swift/index.md b/docs/projects/hello-world/swift/index.md deleted file mode 100644 index 2b73326acc..0000000000 --- a/docs/projects/hello-world/swift/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Griffith -date: 2018-03-25 -featured-image: hello-world-in-swift.jpg -last-modified: 2018-03-25 -layout: default -tags: -- hello-world -- swift -title: Hello World in Swift -title1: Hello World -title2: in Swift ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Swift](/languages/swift) was written by: - -- Jeremy Griffith - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/tcl/index.md b/docs/projects/hello-world/tcl/index.md deleted file mode 100644 index 34033ecc36..0000000000 --- a/docs/projects/hello-world/tcl/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Griffith -date: 2018-04-19 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-04-19 -layout: default -tags: -- hello-world -- tcl -title: Hello World in Tcl -title1: Hello World -title2: in Tcl ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -puts "Hello, World!" - -``` - -{% endraw %} - -Hello World in [Tcl](/languages/tcl) was written by: - -- Jeremy Griffith - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/terra/index.md b/docs/projects/hello-world/terra/index.md deleted file mode 100644 index 09597801f6..0000000000 --- a/docs/projects/hello-world/terra/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-24 -layout: default -tags: -- hello-world -- terra -title: Hello World in Terra -title1: Hello World -title2: in Terra ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Terra](/languages/terra) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```terra -print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Terra](/languages/terra) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/tex/index.md b/docs/projects/hello-world/tex/index.md deleted file mode 100644 index 8d8af25ce1..0000000000 --- a/docs/projects/hello-world/tex/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- Jeremy Grifski -- rzuckerm -date: 2018-08-28 -featured-image: hello-world-in-tex.jpg -last-modified: 2025-01-30 -layout: default -tags: -- hello-world -- tex -title: Hello World in TeX -title1: Hello World -title2: in TeX ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [TeX](/languages/tex) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tex -\newwrite\out -\immediate\openout\out=hello-world.txt -\immediate\write\out{Hello, World!} -\end - -``` - -{% endraw %} - -Hello World in [TeX](/languages/tex) was written by: - -- Christoph Böhmwalder -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's dive right into Hello World in Tex. - -It is much simpler in Tex due to the fact the Tex is a markup language. - -```tex -\newwrite\out -\immediate\openout\out=hello-world.txt -``` - -This first two lines create an output file called `hello-world.txt`. - -```tex -\immediate\write\out{Hello, World!} -``` - -This writes `Hello, World!` to the output file. - -```tex -\end -``` - -Finally, this is saying the document has ended by declaring (`\`) an `end`. - - -## How to Run the Solution - -There are many options for running Tex files both online and offline. This said my personal favorite option is running it online through [Overleaf][1]. Here is what you will need to do: - -1. You will need to create an account (if you do not already have one). -2. Click on the `Project` button. -3. Select `Create New Project`, and select `Blank Project`. -4. Call the project `Hello World`, and click the `Create` button. -5. Select all the code in the `Code Editor` field, and delete it. -6. Copy the [Hello World in Tex][3] sample and paste it into the `Code Editor` field. -7. Click the `Recompile` button. -8. Since this sample does not generate a PDF file, you will have to scroll down to the bottom, click - on the `Other Files` button, and select `hello-world.txt`. This will download the file to your - computer. If you open that file, you will see `Hello, World!`. - -[Overleaf][1] even covers the other options including themselves on their website [here][2]. - -[1]: https://www.overleaf.com/ -[2]: https://www.overleaf.com/learn -[3]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/t/tex/hello-world.tex diff --git a/docs/projects/hello-world/ti-basic/index.md b/docs/projects/hello-world/ti-basic/index.md deleted file mode 100644 index 145274d4a2..0000000000 --- a/docs/projects/hello-world/ti-basic/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-16 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-16 -layout: default -tags: -- hello-world -- ti-basic -title: Hello World in TI-BASIC -title1: Hello World -title2: in TI-BASIC ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Disp "Hello, World!" - -``` - -{% endraw %} - -Hello World in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/typescript/index.md b/docs/projects/hello-world/typescript/index.md deleted file mode 100644 index 066df89c09..0000000000 --- a/docs/projects/hello-world/typescript/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2018-06-22 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- typescript -title: Hello World in TypeScript -title1: Hello World -title2: in TypeScript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -console.log("Hello, World!"); - -``` - -{% endraw %} - -Hello World in [TypeScript](/languages/typescript) was written by: - -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -This is quite possibly the smallest Hello World out there and it just so happens to be identical to Hello World in javascript (the language TypeScript is built on). - -Simply put it logs the phrase `Hello, World!` to the console in your browser. - - -## How to Run the Solution - - -Quite possibly the easiest way to run this is to open developer tools in your browser of choice, however, do note that the following is based on Chrome. This is often done by the shortcut "CRTL-SHIFT-I". Clicking on console at the top of the screen. Where the arrow is at the bottom of the console output is a text entry box and in there type the code from above(`console.log("Hello, World!");`). Finally, press enter and see `Hello, World!` in the Console output. diff --git a/docs/projects/hello-world/unicat/index.md b/docs/projects/hello-world/unicat/index.md deleted file mode 100644 index bf015d381d..0000000000 --- a/docs/projects/hello-world/unicat/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-23 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-23 -layout: default -tags: -- hello-world -- unicat -title: Hello World in Unicat -title1: Hello World -title2: in Unicat ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Unicat](/languages/unicat) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```unicat -😻😹😸🙀🙀😹😹😸🙀🙀 Memory 0 = 0o110 (72 = 'H') -😽😼😸🙀🙀 Output memory 0 -😻😹😸🙀🙀😹😼😽🙀🙀 Memory 0 = 0o145 (101 = 'e') -😽😼😸🙀🙀 Output memory 0 -😻😹😸🙀🙀😹😽😼🙀🙀 Memory 0 = 0o154 (108 = 'l') -😽😼😸🙀🙀 Output memory 0 -😽😼😸🙀🙀 Output memory 0 -😻😹😹🙀🙀😹😽😿🙀🙀 Memory 1 = 0o157 (111 = 'o') -😽😼😹🙀🙀 Output memory 1 -😻😹😺🙀🙀😽😼🙀🙀 Memory 2 = 0o54 (44 = ',') -😽😼😺🙀🙀 Output memory 2 -😻😹😺🙀🙀😼😸🙀🙀 Memory 2 = 0o40 (32 = ' ') -😽😼😺🙀🙀 Output memory 2 -😻😹😺🙀🙀😹😺😿🙀🙀 Memory 2 = 0o127 (87 = 'W') -😽😼😺🙀🙀 Output memory 2 -😽😼😹🙀🙀 Output memory 1 ('o') -😻😹😺🙀🙀😹😾😺🙀🙀 Memory 2 = 0o162 (114 = 'r') -😽😼😺🙀🙀 Output memory 2 -😽😼😸🙀🙀 Output memory 0 ('l') -😻😹😺🙀🙀😹😼😼🙀🙀 Memory 2 = 0o144 (100 = 'd') -😽😼😺🙀🙀 Output memory 2 -😻😹😺🙀🙀😼😹🙀🙀 Memory 2 = 0o41 (33 = '!') -😽😼😺🙀🙀 Output memory 2 -😻😹😺🙀🙀😹😺🙀🙀 Memory 2 = 0o12 (10 = '\n') -😽😼😺🙀🙀 Output memory 2 -🙀🙀 Exit - -``` - -{% endraw %} - -Hello World in [Unicat](/languages/unicat) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/v/index.md b/docs/projects/hello-world/v/index.md deleted file mode 100644 index cd80d61155..0000000000 --- a/docs/projects/hello-world/v/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- ToyireuDev -date: 2023-06-17 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-06-17 -layout: default -tags: -- hello-world -- v -title: Hello World in V -title1: Hello World -title2: in V ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [V](/languages/v) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```v -module main - -fn main(){ - println('Hello, World!') -} - -``` - -{% endraw %} - -Hello World in [V](/languages/v) was written by: - -- ToyireuDev - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/verilog/index.md b/docs/projects/hello-world/verilog/index.md deleted file mode 100644 index b9401679b8..0000000000 --- a/docs/projects/hello-world/verilog/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -date: 2018-04-27 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-19 -layout: default -tags: -- hello-world -- verilog -title: Hello World in Verilog -title1: Hello World -title2: in Verilog ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Verilog](/languages/verilog) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```verilog -module main; - initial - begin - $display("Hello, World!"); - $finish(0); - end -endmodule - -``` - -{% endraw %} - -Hello World in [Verilog](/languages/verilog) was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/verve/index.md b/docs/projects/hello-world/verve/index.md deleted file mode 100644 index 1d3954c489..0000000000 --- a/docs/projects/hello-world/verve/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2021-05-24 -featured-image: hello-world-in-every-language.jpg -last-modified: 2021-05-24 -layout: default -tags: -- hello-world -- verve -title: Hello World in Verve -title1: Hello World -title2: in Verve ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Verve](/languages/verve) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```verve -print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Verve](/languages/verve) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/vimscript/index.md b/docs/projects/hello-world/vimscript/index.md deleted file mode 100644 index f26d07d84a..0000000000 --- a/docs/projects/hello-world/vimscript/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- rzuckerm -date: 2018-08-27 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-12-21 -layout: default -tags: -- hello-world -- vimscript -title: Hello World in Vimscript -title1: Hello World -title2: in Vimscript ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Vimscript](/languages/vimscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```vimscript -func! Main() - echo "Hello, World!" -endfunc - -``` - -{% endraw %} - -Hello World in [Vimscript](/languages/vimscript) was written by: - -- Christoph Böhmwalder -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/visual-basic/index.md b/docs/projects/hello-world/visual-basic/index.md deleted file mode 100644 index d87430c85a..0000000000 --- a/docs/projects/hello-world/visual-basic/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- AaronLenoir -- Jeremy Grifski -- rzuckerm -date: 2018-05-04 -featured-image: hello-world-in-visual-basic.jpg -last-modified: 2023-05-15 -layout: default -tags: -- hello-world -- visual-basic -title: Hello World in Visual Basic -title1: Hello World in -title2: Visual Basic ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module HelloWorld - Public Sub Main() - System.Console.WriteLine("Hello, World!") - End Sub -End Module - -``` - -{% endraw %} - -Hello World in [Visual Basic](/languages/visual-basic) was written by: - -- AaronLenoir -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's dive right into Hello World in Visual Basic .NET. - -As we can see, VB.NET is a structured language. In other words, there's a very -strong focus on code blocks and control flow structures. - -Our first code block is the module declaration. In this case, we've declared a -public module called `HelloWorld`. If other libraries needed access to this module, -they could simply import it by name. - -Next, we have our typical `main` function declaration. Of course, in VB.NET, we -call them subroutines rather than functions, as indicated by the `Sub` keyword. - -Finally, we have our print line. Much like languages like Java, we have to string -together a few references before we can actually write to the console. In other -words, we have to call `WriteLine` after we get a reference to the standard output -class from the `System` namespace. - - -## How to Run the Solution - -With our solution implemented, we should probably give it a run. Perhaps the easiest -way to run the solution is to copy it into an [online VB.NET compiler][1]. - -Alternatively, we can run the solution using Microsoft's very own Visual Studio. -Of course, I'm not sure of it's support on platforms beyond Windows. Don't forget -to grab a copy of the [Hello World in Visual Basic .NET][2] solution. - -[1]: https://www.jdoodle.com/compile-vb-dot-net-online/ -[2]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/v/visual-basic/hello-world.vb diff --git a/docs/projects/hello-world/whitespace/index.md b/docs/projects/hello-world/whitespace/index.md deleted file mode 100644 index f1a2023208..0000000000 --- a/docs/projects/hello-world/whitespace/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Jayden Thrasher -date: 2019-10-04 -featured-image: hello-world-in-every-language.jpg -last-modified: 2019-10-04 -layout: default -tags: -- hello-world -- whitespace -title: Hello World in Whitespace -title1: Hello World -title2: in Whitespace ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Whitespace](/languages/whitespace) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```whitespace -S S S T S S T S S S L -T L -S S S S S T T S S T S T L -T L -S S S S S T T S T T S S L -T L -S S S S S T T S T T S S L -T L -S S S S S T T S T T T T L -T L -S S S S S T S T T S S L -T L -S S S S S T S S S S S L -T L -S S S S S T S T S T T T L -T L -S S S S S T T S T T T T L -T L -S S S S S T T T S S T S L -T L -S S S S S T T S T T S S L -T L -S S S S S T T S S T S S L -T L -S S S S S T S S S S T L -T L -S S L -L -L - -``` - -{% endraw %} - -Hello World in [Whitespace](/languages/whitespace) was written by: - -- Jayden Thrasher - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/wren/index.md b/docs/projects/hello-world/wren/index.md deleted file mode 100644 index 645cae5870..0000000000 --- a/docs/projects/hello-world/wren/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-20 -featured-image: hello-world-in-wren.jpg -last-modified: 2023-05-16 -layout: default -tags: -- hello-world -- wren -title: Hello World in Wren -title1: Hello World -title2: in Wren ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -System.print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Wren](/languages/wren) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Personally, I'm getting hints of Java and -Python here just in terms of syntax. - -At any rate, let's break it down. Obviously, we only have -one line, but it's at least a little more interesting than -most scripting languages. - -For starters, we have the built-in `System` class. This class -comes with the core module along with a few other goodies like -`String`, `Sequence`, `Fiber`, and `Bool`. - -Now, one of the functions of `System` is `print`. Obviously, `print` -writes text to standard output. But, I find Wren's `print` -functionality particularly interesting because it's similar to -Java. In fact, it accepts any object as input. If the input is -not a `String`, `print` will convert it to a `String` using the -`toString` functionality, a method available to all objects. - -So, basically we call the static method print of the `System` class -which prints the input to the user. How cool is that? - - -## How to Run the Solution - -You can [download a copy of Wren][1] to your local machine, grab a copy of -[Hello World in Wren][2], and then run this: - -``` -wren_cli hello-world.wren -``` - -Alternatively, you can use an [online Wren interpreter][3]. - -[1]: https://github.com/wren-lang/wren-cli/releases -[2]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/w/wren/hello-world.wren -[3]: https://wren.io/try/ diff --git a/docs/projects/hello-world/wu/index.md b/docs/projects/hello-world/wu/index.md deleted file mode 100644 index 91aabacdac..0000000000 --- a/docs/projects/hello-world/wu/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-22 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-22 -layout: default -tags: -- hello-world -- wu -title: Hello World in Wu -title1: Hello World -title2: in Wu ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Wu](/languages/wu) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wu -print("Hello, World!\n") - -``` - -{% endraw %} - -Hello World in [Wu](/languages/wu) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/wyvern/index.md b/docs/projects/hello-world/wyvern/index.md deleted file mode 100644 index 0833751194..0000000000 --- a/docs/projects/hello-world/wyvern/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-06-21 -featured-image: hello-world-in-every-language.jpg -last-modified: 2018-06-21 -layout: default -tags: -- hello-world -- wyvern -title: Hello World in Wyvern -title1: Hello World -title2: in Wyvern ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Wyvern](/languages/wyvern) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wyvern -require stdout - -stdout.print("Hello, World!") - -``` - -{% endraw %} - -Hello World in [Wyvern](/languages/wyvern) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/x86-64/index.md b/docs/projects/hello-world/x86-64/index.md deleted file mode 100644 index e0eeecb4e3..0000000000 --- a/docs/projects/hello-world/x86-64/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- alope107 -date: 2023-05-04 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-05-04 -layout: default -tags: -- hello-world -- x86-64 -title: Hello World in x86-64 -title1: Hello World -title2: in x86-64 ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [x86-64](/languages/x86-64) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```x86-64 -section .rodata - message db 'Hello, World!' - message_len equ $-message - -section .text - global _start - -_start: - ; write message to stdout - mov rax, 1 ; 1 is the system call number for write - mov rdi, 1 ; 1 is the file descriptor for stdout - mov rsi, message ; address of the message to print - mov rdx, message_len ; number of bytes to print - syscall ; invoke the system call - - ; exit program with 0 - mov rax, 60 ; 60 is the system call number for exit - xor rdi, rdi ; the exit status is stored in rdi. Use xor to zero it out - syscall ; invoke the system call -``` - -{% endraw %} - -Hello World in [x86-64](/languages/x86-64) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/hello-world/yoix/index.md b/docs/projects/hello-world/yoix/index.md deleted file mode 100644 index 2aca3cebb1..0000000000 --- a/docs/projects/hello-world/yoix/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-06-19 -featured-image: hello-world-in-yoix.jpg -last-modified: 2023-06-20 -layout: default -tags: -- hello-world -- yoix -title: Hello World in Yoix -title1: Hello World -title2: in Yoix ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Yoix](/languages/yoix) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```yoix -import yoix.stdio.printf; - -printf("Hello, World!\n"); - -``` - -{% endraw %} - -Hello World in [Yoix](/languages/yoix) was written by: - -- rzuckerm - -This article was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Yoix requires you to import every system function that you use. All the -`import` statements start with `yoix`, followed by the module where the -function is located, followed by the function name. Since `printf` is in -the `stdio` module, the `import` statement is `yoix.stdio.printf`. -The `printf` statement is same as Java, which is not surprising since -[the Yoix interpreter runs in Java][1]. - -[1]: https://en.wikipedia.org/wiki/Yoix - - -## How to Run the Solution - -You can [download a copy of Yoix JAR file][2] to your local machine, grab a copy of -[Hello World in Yoix][3], and then run this: - -``` -java -jar yoix.jar hello_world.yx -``` - -[2]: https://raw.githubusercontent.com/att/yoix/master/yoix.jar -[3]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/y/yoix/hello_world.yx diff --git a/docs/projects/hello-world/zig/index.md b/docs/projects/hello-world/zig/index.md deleted file mode 100644 index 9be1a1caa1..0000000000 --- a/docs/projects/hello-world/zig/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Palash Dubey -- rzuckerm -date: 2020-10-09 -featured-image: hello-world-in-every-language.jpg -last-modified: 2023-08-22 -layout: default -tags: -- hello-world -- zig -title: Hello World in Zig -title1: Hello World -title2: in Zig ---- - - - -Welcome to the [Hello World](/projects/hello-world) in [Zig](/languages/zig) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```zig -const std = @import("std"); - -pub fn main() !void { - const stdout = std.io.getStdOut().writer(); - try stdout.writeAll("Hello, World!\n"); -} - -``` - -{% endraw %} - -Hello World in [Zig](/languages/zig) was written by: - -- Palash Dubey -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/index.md b/docs/projects/index.md deleted file mode 100644 index f9fc7a5c35..0000000000 --- a/docs/projects/index.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -date: 2018-03-15 -featured-image: programming-projects-in-every-language.jpg -last-modified: 2026-05-23 -layout: default -title: Programming Projects in Every Language -title1: Programming Projects -title2: in Every Language ---- - -Welcome to the Projects page! Here, you'll find a list of all of the projects represented in the collection. At this time, the repo supports 38 projects, of which 38 are tested. - -## Projects List - -To help you navigate the collection, the following projects are organized alphabetically. - -- [Baklava](/projects/baklava) -- [Base64 Encode Decode](/projects/base64-encode-decode) -- [Binary Search](/projects/binary-search) -- [Bubble Sort](/projects/bubble-sort) -- [Capitalize](/projects/capitalize) -- [Convex Hull](/projects/convex-hull) -- [Depth First Search](/projects/depth-first-search) -- [Dijkstra](/projects/dijkstra) -- [Duplicate Character Counter](/projects/duplicate-character-counter) -- [Even Odd](/projects/even-odd) -- [Factorial](/projects/factorial) -- [Fibonacci](/projects/fibonacci) -- [File Input Output](/projects/file-input-output) -- [Fizz Buzz](/projects/fizz-buzz) -- [Fraction Math](/projects/fraction-math) -- [Hello World](/projects/hello-world) -- [Insertion Sort](/projects/insertion-sort) -- [Job Sequencing](/projects/job-sequencing) -- [Josephus Problem](/projects/josephus-problem) -- [Linear Search](/projects/linear-search) -- [Longest Common Subsequence](/projects/longest-common-subsequence) -- [Longest Palindromic Substring](/projects/longest-palindromic-substring) -- [Longest Word](/projects/longest-word) -- [Maximum Array Rotation](/projects/maximum-array-rotation) -- [Maximum Subarray](/projects/maximum-subarray) -- [Merge Sort](/projects/merge-sort) -- [Minimum Spanning Tree](/projects/minimum-spanning-tree) -- [Palindromic Number](/projects/palindromic-number) -- [Prime Number](/projects/prime-number) -- [Quick Sort](/projects/quick-sort) -- [Quine](/projects/quine) -- [Remove All Whitespace](/projects/remove-all-whitespace) -- [Reverse String](/projects/reverse-string) -- [Roman Numeral](/projects/roman-numeral) -- [Rot13](/projects/rot13) -- [Selection Sort](/projects/selection-sort) -- [Transpose Matrix](/projects/transpose-matrix) -- [Zeckendorf](/projects/zeckendorf) \ No newline at end of file diff --git a/docs/projects/insertion-sort/ada/index.md b/docs/projects/insertion-sort/ada/index.md deleted file mode 100644 index d2a2f272f4..0000000000 --- a/docs/projects/insertion-sort/ada/index.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-10 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-05-10 -layout: default -tags: -- ada -- insertion-sort -title: Insertion Sort in Ada -title1: Insertion -title2: Sort in Ada ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Containers.Vectors; - -procedure Insertion_Sort is - use Ada.Containers; - - Parse_Error : exception; - - package Int_Vec is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - subtype Vec is Int_Vec.Vector; - use Int_Vec; - - procedure Insertion_Sort (V : in out Vec) is - Key : Integer; - Low : Natural; - High : Natural; - Mid : Natural; - Pos : Natural; - begin - if V.Length <= 1 then - return; - end if; - - for I in V.First_Index + 1 .. V.Last_Index loop - Key := V (I); - - Low := V.First_Index; - High := I; - - while Low < High loop - Mid := Low + (High - Low) / 2; - - if V (Mid) <= Key then - Low := Mid + 1; - else - High := Mid; - end if; - end loop; - - Pos := Low; - - for J in reverse Pos .. I - 1 loop - V (J + 1) := V (J); - end loop; - - V (Pos) := Key; - end loop; - end Insertion_Sort; - - function Parse_Int (S : String) return Integer is - T : constant String := Trim (S, Ada.Strings.Both); - begin - return Integer'Value (T); - exception - when Constraint_Error => - raise Parse_Error; - end Parse_Int; - - function Parse_List (S : String) return Vec is - V : Vec; - Start : Positive := S'First; - begin - if S'Length = 0 then - raise Parse_Error; - end if; - - for I in S'Range loop - if S (I) = ',' then - if I = Start then - raise Parse_Error; - end if; - - Append (V, Parse_Int (S (Start .. I - 1))); - Start := I + 1; - end if; - end loop; - - Append (V, Parse_Int (S (Start .. S'Last))); - - if V.Length < 2 then - raise Parse_Error; - end if; - - return V; - end Parse_List; - - procedure Print_Vector (V : Vec) is - First : constant Natural := V.First_Index; - Last : constant Natural := V.Last_Index; - - function Img (X : Integer) return String - is (Trim (Integer'Image (X), Ada.Strings.Left)); - begin - for I in First .. Last loop - Put (Img (V (I))); - if I /= Last then - Put (", "); - end if; - end loop; - New_Line; - end Print_Vector; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide a list of at least two integers to sort in the format ""1, 2, 3, 4, 5"""); - end Print_Usage; - -begin - if Argument_Count /= 1 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - declare - V : Vec; - begin - V := Parse_List (Argument (1)); - Insertion_Sort (V); - Print_Vector (V); - - exception - when Parse_Error => - Print_Usage; - Set_Exit_Status (Failure); - end; -end Insertion_Sort; - -``` - -{% endraw %} - -Insertion Sort in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/algol60/index.md b/docs/projects/insertion-sort/algol60/index.md deleted file mode 100644 index 286e52df24..0000000000 --- a/docs/projects/insertion-sort/algol60/index.md +++ /dev/null @@ -1,270 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-17 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- insertion-sort -title: Insertion Sort in ALGOL 60 -title1: Insertion Sort -title2: in ALGOL 60 ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of at least two integers " - "to sort in the format \"1, 2, 3, 4, 5\"\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Output integer array; - procedure outIntegerArray(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i; - for i := 1 step 1 until arrLen do - begin - if i > 1 then outstring(1, ", "); - outIntegerNoSpace(arr[i]) - end; - - if arrLen > 0 then outstring(1, "\n") - end outIntegerArray; - - comment Source https://en.wikipedia.org/wiki/Insertion_sort#Algorithm; - procedure insertionSort(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i, j, temp; - - for i := 2 step 1 until arrLen do - begin - temp := arr[i]; - j := i - 1; - sortloop: - if j >= 1 then - begin - if arr[j] > temp then - begin - arr[j + 1] := arr[j]; - j := j - 1; - goto sortloop - end - end; - - arr[j + 1] := temp - end - end insertionSort; - - integer argc, arrLen; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 2 then usage; - - comment Insertion sort input and output result; - insertionSort(arr, arrLen); - outIntegerArray(arr, arrLen) -end - -``` - -{% endraw %} - -Insertion Sort in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/algol68/index.md b/docs/projects/insertion-sort/algol68/index.md deleted file mode 100644 index 1caff0fdb3..0000000000 --- a/docs/projects/insertion-sort/algol68/index.md +++ /dev/null @@ -1,201 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-29 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- insertion-sort -title: Insertion Sort in ALGOL 68 -title1: Insertion Sort -title2: in ALGOL 68 ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a list of at least two integers to sort in the format ""1, 2, 3, 4, 5""")) -); - -PROC insertion sort = (REF []INT values) VOID: -( - COMMENT - Source: https://en.wikipedia.org/wiki/Insertion_sort#Algorithm - COMMENT - - INT temp; - INT j; - FOR i FROM 2 TO UPB values - DO - temp := values[i]; - j := i - 1; - WHILE j >= 1 ANDF values[j] > temp - DO - values[j + 1] := values[j]; - j -:= 1 - OD; - values[j + 1] := temp - OD -); - -PROC show list values = (REF []INT values) VOID: -( - INT n = UPB values; - FOR k TO n - DO - IF k > 1 - THEN - print(", ") - FI; - - print(whole(values[k], 0)) - OD; - - IF n > 0 - THEN - print(newline) - FI -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result OR UPB values < 2 -THEN - usage; - stop -FI; - -# Do insertion sort and show results # -insertion sort(values); -show list values(values) - -``` - -{% endraw %} - -Insertion Sort in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/awk/index.md b/docs/projects/insertion-sort/awk/index.md deleted file mode 100644 index 58b6642960..0000000000 --- a/docs/projects/insertion-sort/awk/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-21 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2025-04-21 -layout: default -tags: -- awk -- insertion-sort -title: Insertion Sort in AWK -title1: Insertion -title2: Sort in AWK ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -# Source: https://en.wikipedia.org/wiki/Insertion_sort#Algorithm -function insertion_sort(arr, arr_len, i, j, t) { - for (i = 2; i <= arr_len; i++) { - t = arr[i] - j = i - 1 - while (j >= 1 && arr[j] > t) { - arr[j + 1] = arr[j] - j-- - } - - arr[j + 1] = t - } -} - -function show_array(arr, idx, s) { - s = "" - for (idx in arr) { - if (s) { - s = s ", " - } - s = s arr[idx] - } - - print s -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], arr) - arr_len = length(arr) - if (!arr_len || arr_len < 2) { - usage() - } - - insertion_sort(arr, arr_len) - show_array(arr) -} - -``` - -{% endraw %} - -Insertion Sort in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/beef/index.md b/docs/projects/insertion-sort/beef/index.md deleted file mode 100644 index b2192d4a60..0000000000 --- a/docs/projects/insertion-sort/beef/index.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-02 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2024-02-02 -layout: default -tags: -- beef -- insertion-sort -title: Insertion Sort in Beef -title1: Insertion -title2: Sort in Beef ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace InsertionSort; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Reference: https://en.wikipedia.org/wiki/Insertion_sort#Algorithm - public static void InsertionSort(List arr) - where int : operator T <=> T - { - int n = arr.Count; - for (int i in 1..< n) - { - T temp = arr[i]; - int j = i; - while (j > 0 && arr[j - 1] > temp) - { - arr[j] = arr[j - 1]; - j--; - } - - arr[j] = temp; - } - } - - public static void ShowList(List arr) - { - String line = scope .(); - for (T val in arr) - { - if (!line.IsEmpty) - { - line += ", "; - } - - line.AppendF("{}", val); - } - - Console.WriteLine(line); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - List arr = scope .(); - switch (ParseIntList(args[0], arr)) - { - case .Ok: - if (arr.Count < 2) - { - Usage(); - } - case .Err: - Usage(); - } - - InsertionSort(arr); - ShowList(arr); - return 0; - } -} - -``` - -{% endraw %} - -Insertion Sort in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/c-plus-plus/index.md b/docs/projects/insertion-sort/c-plus-plus/index.md deleted file mode 100644 index 14510da0ed..0000000000 --- a/docs/projects/insertion-sort/c-plus-plus/index.md +++ /dev/null @@ -1,489 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Prasun Kumar -- rzuckerm -- sun-fox -- SUNNY KUMAR SINGH -- Ștefan-Iulian Alecu -date: 2019-10-09 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- insertion-sort -title: Insertion Sort in C++ -title1: Insertion -title2: Sort in C++ ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5")" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - s = trim(s); - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -template - requires std::sortable> -void insertion_sort(R&& r) { - auto first = ranges::begin(r); - auto last = ranges::end(r); - - for (auto it = first; it != last; ++it) { - auto pos = std::upper_bound(first, it, *it); - std::rotate(pos, it, std::next(it)); - } -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - const std::string_view input{argv[1]}; - auto ints_view = input | views::split(',') | - views::transform([](auto&& rng) { - return std::string_view(rng.begin(), rng.end()); - }) | - views::transform(to_int) | - views::filter([](auto&& opt) { return opt.has_value(); }) | - views::transform([](auto&& opt) { return *opt; }); - - std::vector numbers; - ranges::copy(ints_view, std::back_inserter(numbers)); - - if (numbers.size() < 2) usage(); - - insertion_sort(numbers); - - for (const char* sep = ""; int val : numbers) { - std::cout << std::exchange(sep, ", ") << val; - } - std::cout << "\n"; -} - -``` - -{% endraw %} - -Insertion Sort in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Prasun Kumar -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- sun-fox -- SUNNY KUMAR SINGH - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of May 05 2026 15:57:54. The solution was first committed on Oct 09 2019 21:10:56. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Let's walk through each line of code. - -### Includes - -In our sample, we include a single standard library utility: - -```c++ -#include -#include - -using namespace std; -``` - -Here, we can see that we include of `iostream` which contains the standard I/O -functions for printing messages onto the screen and for taking the inputs from the user. -The `bits/stdc++.h` includes common C++ header files. - -### Handle Errors - -This function is called when the command-line arguments are invalid. It displays the -usage statement and exits the program. - -```c++ -void handle_error() -{ - cout << "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" << endl; - exit(0); -} -``` - -### Convert String to Array of Integers - -```c++ -vector convert(string s) -{ - - vector v; - string num = ""; - for (int i = 0; i < s.size(); i++) - { - if ((int)s[i] >= 48 && (int)s[i] <= 57 || s[i] == ' ') - { - num += s[i]; - } - else if (s[i] == ',') - { - v.push_back(check(num)); - num = ""; - } - else - { - handle_error(); - } - } - - if (num.size() > 0) - { - v.push_back(check(num)); - } - - return v; -} -``` - -This function take a string containing a comma-separated list of integers -to sort and validate it. The `for` loop go through each character in the -string. When a number (from 48 to 57 -- from ASCII `0` to ASCII `9`) or a space is -detected, it appended to the `num` variable. When a comma is detected the -`check` function is called to convert it to an integer, and `push_back` is -called to append the integer to the vector `v`. If any other character is -detected, `handle_error` is called. - -When the loop exits, `num` will either be empty, or it will contain the last -value. If `num is not empty, the last number is converted to an integer and -appended to the vector `v`. - -Finally, the vector is returned to the caller. - -### Check Function - -```c+ -int check(string s) -{ - int x1 = 0, x2 = s.size() - 1; - - for (int i = 0; i < s.size(); i++) - { - if (s[i] != ' ') - { - x1 = i; - break; - } - } - - for (int i = s.size() - 1; i >= x1; i--) - { - if (s[i] != ' ') - { - x2 = i; - break; - } - } - - for (int i = x1; i <= x2; i++) - { - if (s[i] == ' ') - { - handle_error(); - } - } - - return stoi(s); -} -``` - -This function is giving a string containing an individual value. It strips -off leading and trailing spaces. If there is no valid value, `handle_error` -is called. - -### Insertion-Sort Function - -In our sample, this function is responsible for sorting the array according -to the insertion sort algorithm: - -```c++ -void insertion_sort(string str, vector arr) -{ - - stringstream ss; - ss << str; - string temp; - int found; - while (!ss.eof()) - { - ss >> temp; - if (stringstream(temp) >> found) - { - arr.push_back(found); - } - temp = ""; - } - - int t,j; - for(int i=1;i= 0 && t<=arr[j]){ - arr[j+1] = arr[j]; - j--; - } - arr[j+1] = t; - } - - int i; - for (i = 0; i < arr.size(); i++) - cout << arr[i] << " "; - cout << endl; -} -``` - -Following are the explanation for the respective code snippets. - -```c++ - stringstream ss; - ss << str; - string temp; - int found; - while (!ss.eof()) - { - ss >> temp; - if (stringstream(temp) >> found) - { - arr.push_back(found); - } - temp = ""; - } -``` - -This section is responsible for extracting the numbers from the string and adding them to a vector, -so that easy iterative approach to insertion sort can be used. - -```c++ - int t,j; - for(int i=1;i= 0 && t<=arr[j]){ - arr[j+1] = arr[j]; - j--; - } - arr[j+1] = t; - } -``` - -This section accepts the input array and the size of the array from the `main` function -Here we virtually divide the array into two parts i.e., the sorted and the unsorted part, -initially, the first element in the array is considered as sorted, even if it is not sorted. -Further, each element in the array is checked with the previous elements for the strict -inequality with each iteration, the sorting algorithm removes one element at a time and -finds the appropriate location within the sorted array and inserts it there. The iteration -continues until the unsorted array is empty, and get's it finally sorted. - -Above you can see, that the variable `t` holds the unsorted array's first element and `j` -here keeps track of the index of the last element of the sorted array. Now we iterate -throughout the remaining unsorted array one by one, finding a relevant position for the -the value stored in 't' throughout the sorted array, as soon we get the desired location we -place it there and then increment the sorted array end marker 'i' by unity. -This process continues until the array unsorted array size is reduced to zero. - -### The display section - -It's quite self-explanatory that it displays the new altered array: - -```c++ - int i; - for (i = 0; i < n; i++) - cout << arr[i] << " "; - cout << endl; -``` - -It takes the altered array and then prints it by iterating through it. - -### Swap Function - -This function swaps two values `x` and `y`. It is used for as part of the insertion sort -algorithm: - -```c++ -void swap(int *x, int *y) -{ - int t = *x; - *x = *y; - *y = t; -} -``` - -### The Main Function - -As usual, C++ programs cannot be executed without a `main` function: - -```c++ -int main(int argc, char *argv[]) -{ - ... -} -``` - -#### The Validation and Conversion Section - -The first part of the `main` function validates the number of command-line -arguments. If there are too few, `handle_error` is called. - -```c++ -if (argc < 2) -{ - handle_error(); -} -``` - -Next, the command-line argument is converted to a vector of integer values. -If there are too few values, the usage statement is displayed and the program -exits: - -```c++ -vector v = convert(argv[1]); - -if (v.size() < 2) -{ - cout << "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" << endl; - exit(0); -} -``` - -#### The Insertion Sort Section - -In our sample, this function is responsible for sorting the array according -to the insertion sort algorithm: - -```c++ - int n = v.size(); - int min_idx; - - for (int i = 0; i < n - 1; i++) - { - min_idx = i; - for (int j = i + 1; j < n; j++) - { - if (v[j] < v[min_idx]) - { - min_idx = j; - } - } - swap(v[min_idx], v[i]); - } -``` - -Here we virtually divide the array into two parts: the sorted and the unsorted part. -Initially, the first element in the array is considered as sorted, even if it is not sorted. -Further, each element in the array is checked with the previous elements for the strict -inequality with each iteration, the sorting algorithm removes one element at a time and -finds the appropriate location within the sorted array and inserts it there. The iteration -continues until the unsorted array is empty, and get's it finally sorted. - -Above you can see, that the variable `min_index` starts out as the index of the sorted -array's first element (`i`). The variable `j` loops over the unsorted portion of the array. -By the end of the `for j` loop, `min_index` contains the index of the minimum unsorted -value. The `swap` function swaps the minimum value in the unsorted portion of the array -at `min_index` with the current value in the sorted portion of the array at `i`. - -We continue to iterate `i` until the array is sorted. - -#### The Display Section - -Finally, the sorted vector is displayed: - -```c++ -for (int i = 0; i < n - 1; i++) -{ - cout << v[i] << ", "; -} -cout << v[n - 1]; -``` - -And that's it! - - -## How to Run the Solution - -One can run the code on C++ IDE's like [CodeBlocks][1], [Turboc++][2], [Eclipse for C/C++][3], etc. -Their installation is guided by the setup wizards and once install can allow you to -run the locally on your machine, all these IDE's are available free of cost on their -respective websites. - -Perhaps the easiest way to run the solution is to leverage the online gdb -compiler. - -Alternatively, you can try to run the C++ code in a similar way described in the last article. Honestly, it's pretty easy to write and run C/C++ code -on most platforms: - -```console -gcc -o insertion-sort reverse-string.cpp -``` - -Unfortunately, Windows pretty much requires the use of [Visual Studio][4]. So, -instead of sharing platform-specific directions, I'll fall back on my -[online compiler recommendation][5]. - -[1]: https://www.codeblocks.org/ -[2]: https://developerinsider.co/download-turbo-c-for-windows-7-8-8-1-and-windows-10-32-64-bit-full-screen/ -[3]: https://www.eclipse.org/downloads/packages/release/2023-03/r/eclipse-ide-cc-developers -[4]: https://visualstudio.microsoft.com/downloads/ -[5]: https://www.onlinegdb.com/online_c++_compiler diff --git a/docs/projects/insertion-sort/c-sharp/index.md b/docs/projects/insertion-sort/c-sharp/index.md deleted file mode 100644 index 927374d21a..0000000000 --- a/docs/projects/insertion-sort/c-sharp/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-28 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- insertion-sort -title: Insertion Sort in C# -title1: Insertion -title2: Sort in C# ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Runtime.InteropServices; - -if (args is not [var input] || !TryParseList(input.AsSpan(), out var numbers)) - return Usage(); - -InsertionSort(CollectionsMarshal.AsSpan(numbers)); - -Console.WriteLine(string.Join(", ", numbers)); -return 0; - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return numbers.Count > 1; -} - -static void InsertionSort(Span xs) -{ - for (int i = 1; i < xs.Length; i++) - { - int x = xs[i]; - if (x >= xs[i - 1]) - continue; - - int lo = 0, - hi = i; - - while (lo < hi) - { - int mid = (lo + hi) >> 1; - - if (x >= xs[mid]) - lo = mid + 1; - else - hi = mid; - } - - xs[lo..i].CopyTo(xs[(lo + 1)..]); - xs[lo] = x; - } -} - -static int Usage() -{ - Console.Error.WriteLine( - """ -Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -""" - ); - return 1; -} - -``` - -{% endraw %} - -Insertion Sort in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/c/index.md b/docs/projects/insertion-sort/c/index.md deleted file mode 100644 index 4113d3dfac..0000000000 --- a/docs/projects/insertion-sort/c/index.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -authors: -- sourabbr -- Ștefan-Iulian Alecu -date: 2019-10-18 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- insertion-sort -title: Insertion Sort in C -title1: Insertion -title2: Sort in C ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include - -void insertion_sort(long *, int); // insertion sort function - -size_t parse_list(const char *orig_list, - long **arr) // used for parsing the input in array arr -{ - char *list; - char *token; - size_t num_elements = 0; - int i; - int curr_index = 0; - long temp_num; - - /* find the length of the array */ - for (i = 0; orig_list[i]; i++) - if (orig_list[i] == ',') - num_elements++; - - /* if there are no commas, invalid input */ - if (num_elements == 0) - { - *arr = NULL; - return 0; - } - - /* since there is one more element than commas */ - num_elements++; - - /* allocate memory for the array */ - *arr = malloc(num_elements * sizeof(long)); - - /* store numbers in the array */ - list = strdup(orig_list); - token = strtok(list, ","); - while (token != NULL) - { - errno = 0; - temp_num = strtol(token, NULL, 10); - if (errno != 0) - { - *arr = NULL; - return 0; - } - - (*arr)[curr_index++] = temp_num; - - token = strtok(NULL, ","); - } - - free(list); - - return num_elements; -} - -/* print the elements of array */ -void print_array(long *arr, size_t num_elems) -{ - int i; - - for (i = 0; i < num_elems - 1; i++) - printf("%ld, ", arr[i]); - - printf("%ld\n", arr[num_elems - 1]); -} - -/* error message if input is not in desired format */ -void error_message() -{ - fputs("Usage: please provide a list of at least two integers to sort in " - "the format \"1, 2, 3, 4, 5\"\n", - stderr); -} - -int main(int argc, char **argv) -{ - long *arr; - long num_elements; - - if (argc < 2) - { - error_message(); - return 1; - } - - num_elements = parse_list(argv[1], &arr); - if (num_elements == 0) - { - error_message(); - return 1; - } - - insertion_sort(arr, num_elements); - print_array(arr, num_elements); - - free(arr); -} - -void insertion_sort(long *arr_sort, int n) -{ - int i, j; - int tmp; - - /* insertion sort logic */ - for (i = 1; i < n; i++) - { - tmp = arr_sort[i]; - for (j = i; j > 0 && arr_sort[j - 1] > tmp; j--) - arr_sort[j] = arr_sort[j - 1]; - arr_sort[j] = tmp; - } -} -``` - -{% endraw %} - -Insertion Sort in [C](/languages/c) was written by: - -- sourabbr -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/cobol/index.md b/docs/projects/insertion-sort/cobol/index.md deleted file mode 100644 index d7b5482f55..0000000000 --- a/docs/projects/insertion-sort/cobol/index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-21 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-04-21 -layout: default -tags: -- cobol -- insertion-sort -title: Insertion Sort in COBOL -title1: Insertion -title2: Sort in COBOL ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. insertion-sort. - -data division. -working-storage section. - -01 max-entries constant as 1000. - -01 argument-string pic x(32768). -01 current-token pic x(128). -01 scan-ptr binary-long. - -01 sort-table. - 05 list-size binary-long value 0. - 05 entry-value pic s9(9) occurs 0 to max-entries - depending on list-size. - -01 work-vars. - 05 i binary-long. - 05 j binary-long. - 05 key-val pic s9(9). - -01 flags. - 05 swap-flag pic x. - 88 has-swapped value 'Y'. - 88 no-swaps value 'N'. - -01 output-formatting. - 05 display-num pic ---------9. - 05 separator pic x(2) value ", ". - -procedure division. - -main. - perform validate-input - perform parse-input - perform execute-sort - perform display-results - goback. - -validate-input. - accept argument-string from argument-value - if argument-string = spaces - perform show-usage - end-if. - -parse-input. - move 1 to scan-ptr - - perform until scan-ptr > length of argument-string - move spaces to current-token - - unstring argument-string delimited by "," - into current-token with pointer scan-ptr - end-unstring - - if current-token = spaces - continue - end-if - - if function test-numval(function trim(current-token)) <> 0 - perform show-usage - end-if - - add 1 to list-size - if list-size > max-entries - perform show-usage - end-if - - move function numval(current-token) to entry-value(list-size) - end-perform - - if list-size < 2 perform show-usage end-if. - -execute-sort. - perform varying i from 2 by 1 until i > list-size - move entry-value(i) to key-val - move i to j - - perform until j <= 1 or entry-value(j - 1) <= key-val - move entry-value(j - 1) to entry-value(j) - subtract 1 from j - end-perform - - move key-val to entry-value(j) - end-perform. - -display-results. - perform varying i from 1 by 1 until i > list-size - if i > 1 - display separator with no advancing - end-if - - move entry-value(i) to display-num - display function trim(display-num) with no advancing - end-perform - display space. - -show-usage. - display - 'Usage: please provide a list of at least two integers ' - 'to sort in the format "1, 2, 3, 4, 5"' - stop run. - -``` - -{% endraw %} - -Insertion Sort in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/commodore-basic/index.md b/docs/projects/insertion-sort/commodore-basic/index.md deleted file mode 100644 index d4e84f6a29..0000000000 --- a/docs/projects/insertion-sort/commodore-basic/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-08 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2023-10-15 -layout: default -tags: -- commodore-basic -- insertion-sort -title: Insertion Sort in Commodore BASIC -title1: Insertion Sort in -title2: Commodore BASIC ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -20 GOSUB 2000: REM Get array -25 REM Error if invalid, not end of input/value, or less that 2 items -30 IF V = 0 OR C >= 0 OR NA < 2 THEN GOTO 200 -40 GOSUB 3000: REM Perform insertion sort -50 GOSUB 3500: REM Show array -60 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide a list of at least two integers to sort "; -220 PRINT "in the format "; Q$; "1, 2, 3, 4, 5"; Q$ -230 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Insertion sort -3001 REM Source: https://en.wikipedia.org/wiki/Insertion_sort#Algorithm -3002 REM Inputs: -3003 REM - A contains array to sort -3004 REM - NA contains size of array -3005 REM Outputs: A contains sorted array -3010 I = -1 -3020 I = I + 1 -3030 IF I >= NA THEN GOTO 3120 -3040 T = A(I) -3050 J = I -3060 J = J - 1 -3070 IF J < 0 THEN GOTO 3100 -3075 IF A(J) <= T THEN GOTO 3100 -3080 A(J + 1) = A(J) -3090 GOTO 3060 -3100 A(J + 1) = T -3110 GOTO 3020 -3120 RETURN -3500 REM Display array -3501 REM A contains array -3502 REM NA contains size of array -3510 IF NA < 1 THEN GOTO 3590 -3520 FOR I = 0 TO NA - 1 -3530 S$ = STR$(A(I)) -3540 IF A(I) >= 0 THEN S$ = MID$(S$, 2): REM strip leading space -3550 PRINT S$; -3560 IF I < (NA - 1) THEN PRINT ", "; -3570 NEXT I -3580 PRINT -3590 RETURN - -``` - -{% endraw %} - -Insertion Sort in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/euphoria/index.md b/docs/projects/insertion-sort/euphoria/index.md deleted file mode 100644 index dd994d5ed1..0000000000 --- a/docs/projects/insertion-sort/euphoria/index.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2023-02-26 -layout: default -tags: -- euphoria -- insertion-sort -title: Insertion Sort in Euphoria -title1: Insertion Sort -title2: in Euphoria ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"\n" - ) - abort(0) -end procedure - -procedure show_list_values(sequence values) - if length(values) > 0 - then - sequence format = repeat_pattern("%d, ", length(values)) - sequence s = sprintf(format[1..$-2], values) - printf(STDOUT, "%s\n", {s}) - end if -end procedure - -function insertion_sort(sequence values) - -- Source: https://en.wikipedia.org/wiki/Insertion_sort#Algorithm - - integer n = length(values) - integer temp - integer j - for i = 2 to n - do - temp = values[i] - j = i - 1 - while j >= 1 and values[j] > temp - do - values[j + 1] = values[j] - j -= 1 - end while - - values[j + 1] = temp - end for - - return values -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int_list(argv[4]) -sequence values = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] or length(values) < 2 -then - usage() -end if - --- Do insertion sort and show results -values = insertion_sort(values) -show_list_values(values) - -``` - -{% endraw %} - -Insertion Sort in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/f-sharp/index.md b/docs/projects/insertion-sort/f-sharp/index.md deleted file mode 100644 index 8519a75567..0000000000 --- a/docs/projects/insertion-sort/f-sharp/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- insertion-sort -title: Insertion Sort in F# -title1: Insertion -title2: Sort in F# ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module InsertionSort = - let rec private insert sorted x = - match sorted with - | [] -> [ x ] // Insert at end - | head :: tail when x <= head -> x :: sorted // Found spot - | head :: tail -> head :: insert tail x // Keep traversing - - let run numbers = - numbers |> List.fold insert [] |> List.map string |> String.concat ", " |> Ok - -module Result = - let toOption = - function - | Ok x -> Some x - | Error _ -> None - -module Helpers = - let private (|IntList|_|) (s: string) = - let ns = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) - |> Array.toList - |> List.map (fun p -> - match Int32.TryParse(p.Trim()) with - | true, n -> Ok n - | false, _ -> Error $"Invalid integer: '{p}'") - |> List.choose Result.toOption - - if ns.Length >= 2 then Some ns else None - - let parseArgs argv = - match argv with - | [| IntList numbers |] -> Ok numbers - | _ -> Error "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.bind InsertionSort.run - |> Helpers.handleResult - -``` - -{% endraw %} - -Insertion Sort in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/fortran/index.md b/docs/projects/insertion-sort/fortran/index.md deleted file mode 100644 index bd278f09c3..0000000000 --- a/docs/projects/insertion-sort/fortran/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- leoraggy -date: 2025-11-12 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2025-11-12 -layout: default -tags: -- fortran -- insertion-sort -title: Insertion Sort in Fortran -title1: Insertion Sort -title2: in Fortran ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program insertionsort - implicit none - character(len=256) input1 - character(len=256) output - character(len=10) :: integer_number - integer, allocatable :: numbers(:) - integer :: i - - if(command_argument_count() /= 1) call usage() - call get_command_argument(1, input1) - if(input1 == "") call usage() - call convert_to_array(input1, numbers) - - if(size(numbers) == 1) call usage() - - call insertion_sort(numbers) - - output = "" - do i = 1, size(numbers) - write(integer_number, '(I0)') numbers(i) - if(len_trim(output) == 0) then - output = trim(integer_number) - else - output = trim(output) // ", " // trim(integer_number) - end if - end do - print '(A)', trim(output) - - -contains - subroutine usage() - write(*,'(a)') 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - stop - end subroutine usage - - subroutine convert_to_array(input1, numbers) - implicit none - character(len=*), intent(in) :: input1 - integer, allocatable, intent(out) :: numbers(:) - integer :: i, length, pos, io_status - - length = 1 - do i = 1, len_trim(input1) - if (input1(i:i) == ',') length = length + 1 - end do - - allocate(numbers(length)) - - pos = 1 - do i = 1, length - read(input1(pos:), *, iostat=io_status) numbers(i) - if (io_status /= 0) call usage() - pos = index(input1(pos:), ',') + pos - end do - end subroutine convert_to_array - - subroutine insertion_sort(numbers) - implicit none - integer, intent(inout) :: numbers(:) - integer :: i, j, temp - - do i = 2, size(numbers) - temp = numbers(i) - j = i - 1 - - do while (j >= 0 .and. numbers(j) > temp) - numbers(j+1) = numbers(j) - j = j - 1 - end do - numbers(j+1) = temp - end do - - end subroutine insertion_sort -end program insertionsort -``` - -{% endraw %} - -Insertion Sort in [Fortran](/languages/fortran) was written by: - -- leoraggy - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/go/index.md b/docs/projects/insertion-sort/go/index.md deleted file mode 100644 index 54f5b8d74a..0000000000 --- a/docs/projects/insertion-sort/go/index.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-03-15 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2019-03-25 -layout: default -tags: -- go -- insertion-sort -title: Insertion Sort in Go -title1: Insertion -title2: Sort in Go ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "encoding/json" - "fmt" - "os" - "regexp" - "strconv" - "strings" -) - -func insertionSort(unsorted []int, sorted ...int) []int { - if len(unsorted) <= 0 { - return sorted - } - return insertionSort(unsorted[1:], insert(unsorted[0], sorted)...) -} - -func insert(n int, list []int) []int { - if len(list) <= 0 || n < list[0] { - return append([]int{n}, list...) - } - return append([]int{list[0]}, insert(n, list[1:])...) -} - -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - if len(list) < 2 { - exitWithError() - } - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} - -func sliceIntToString(list []int) (out string) { - bytes, _ := json.Marshal(list) - out = strings.Replace(string(bytes), ",", ", ", -1) - out = strings.Trim(out, "[]") - return -} - -func exitWithError() { - fmt.Println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - nums := strToSliceInt(os.Args[1]) - nums = insertionSort(nums) - fmt.Println(sliceIntToString(nums)) -} - -``` - -{% endraw %} - -Insertion Sort in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/haskell/index.md b/docs/projects/insertion-sort/haskell/index.md deleted file mode 100644 index 05db3bbb3d..0000000000 --- a/docs/projects/insertion-sort/haskell/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-12-18 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2019-03-26 -layout: default -tags: -- haskell -- insertion-sort -title: Insertion Sort in Haskell -title1: Insertion Sort -title2: in Haskell ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Text.Read -import System.Environment -import System.Exit (exitWith, ExitCode(ExitFailure)) -import Data.List (intercalate) - - -insertion :: Ord a => [a] -> [a] -insertion = go [] - where go sorted [] = sorted - go sorted (x:xs) = go (insert x sorted) xs - - -insert :: Ord a => a -> [a] -> [a] -insert a [] = [a] -insert a (x:xs) - | a > x = x:insert a xs - | otherwise = a:x:xs - - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - --- Ensure that a list contains at least two elements -verifyListLength :: Ord a => [a] -> Maybe [a] -verifyListLength [] = Nothing -verifyListLength [x] = Nothing -verifyListLength (x:xs) = Just (x:xs) - -listToString :: [Int] -> String -listToString = intercalate ", " . map show - - -main :: IO () -main = do - args <- getArgs - let xs = headMaybe args >>= stringToListMaybe >>= verifyListLength - case xs of - Nothing -> do - putStrLn "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exitWith $ ExitFailure 1 - Just xs -> putStrLn $ listToString $ insertion xs - - -``` - -{% endraw %} - -Insertion Sort in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/index.md b/docs/projects/insertion-sort/index.md deleted file mode 100644 index 5b68fb20c8..0000000000 --- a/docs/projects/insertion-sort/index.md +++ /dev/null @@ -1,194 +0,0 @@ ---- -date: 2018-12-18 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- insertion-sort -title: Insertion Sort -title1: Insertion -title2: Sort ---- - - - -Welcome to the Insertion Sort page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Insertion sort is an algorithm that generally operates on a single list in place. -It tracks a pointer that iterates through the list a single time, takes each -item and inserts it sorted at the beginning of the list. At any given point -all elements, from the beginning of the list up through the pointer, are in order. -Once the pointer has iterated through the entire list, all elements have been inserted -in order at the front of the list, and the list is now fully sorted. - -### Performance - -The performance of sorting algorithms is generally defined in "Big O notation". -If you are not familiar with such notations, please refer to the relevant -article by [Rob Bell][1] or the [Wikipedia][2] entry listed in further readings below. - -| Cases | Big O Notatation | -| ------------ | ---------------- | -| Best case | O(n) | -| Average case | O(n2) | -| Worst case | O(n2) | - -Although the main pointer of insertion sort only iterates through the list once -it must also iterate through the existing sorted items at the beginning of the list -every time an element is inserted. Thus the average case is O(n2), but so -is the worst case. - - -### Examples - -In the examples below, each row inserts the element from the main pointer -into the front of the list and moves the main pointer to the next element. -The element in __bold__ is the main pointer. - -#### "4, 5, 3, 1, 2" - -- __4__ 5 3 1 2 -- 4 __5__ 3 1 2 -- 4 5 __3__ 1 2 -- 3 4 5 __1__ 2 -- 1 3 4 5 __2__ -- 1 2 3 4 5 - -#### "3, 5, 4, 1, 2" - -- __3__ 5 4 1 2 -- 3 __5__ 4 1 2 -- 3 5 __4__ 1 2 -- 3 4 5 __1__ 2 -- 1 3 4 5 __2__ -- 1 2 3 4 5 - -[1]: https://robbell.io/2009/06/a-beginners-guide-to-big-o-notation -[2]: https://en.wikipedia.org/wiki/Big_O_notation - - -## Requirements - -Write a sample program that takes a list of numbers in the format "4, 5, 3, 1, 2". -It should then sort the numbers and output them: - -```console -$ ./insertion-sort.lang "4, 5, 3, 1, 2" -1, 2, 3, 4, 5 -``` - -The solution should handle duplicate elements - -```console -$ ./insertion-sort.lang "4, 5, 3, 1, 4, 2" -1, 2, 3, 4, 4, 5 -``` - -In addition, there should be some error handling for situations where the user -doesn't supply correct input. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Insertion Sort. -In order to keep things simple, we split up the testing as follows: - -- Insertion Sort Valid Tests -- Insertion Sort Invalid Tests - -### Insertion Sort Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input | "4, 5, 3, 1, 2" | "1, 2, 3, 4, 5" | -| Sample Input: With Duplicate | "4, 5, 3, 1, 4, 2" | "1, 2, 3, 4, 4, 5" | -| Sample Input: Already Sorted | "1, 2, 3, 4, 5" | "1, 2, 3, 4, 5" | -| Sample Input: Reverse Sorted | "9, 8, 7, 6, 5, 4, 3, 2, 1" | "1, 2, 3, 4, 5, 6, 7, 8, 9" | - -### Insertion Sort Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A List | "1" | -| Invalid Input: Wrong Format | "4 5 3" | - -All of these tests should output the following: - -``` -Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -``` - - -## Articles - -There are 32 articles: - -- [Insertion Sort in ALGOL 60](/projects/insertion-sort/algol60) -- [Insertion Sort in ALGOL 68](/projects/insertion-sort/algol68) -- [Insertion Sort in AWK](/projects/insertion-sort/awk) -- [Insertion Sort in Ada](/projects/insertion-sort/ada) -- [Insertion Sort in Beef](/projects/insertion-sort/beef) -- [Insertion Sort in C](/projects/insertion-sort/c) -- [Insertion Sort in C#](/projects/insertion-sort/c-sharp) -- [Insertion Sort in C++](/projects/insertion-sort/c-plus-plus) -- [Insertion Sort in COBOL](/projects/insertion-sort/cobol) -- [Insertion Sort in Commodore BASIC](/projects/insertion-sort/commodore-basic) -- [Insertion Sort in Euphoria](/projects/insertion-sort/euphoria) -- [Insertion Sort in F#](/projects/insertion-sort/f-sharp) -- [Insertion Sort in Fortran](/projects/insertion-sort/fortran) -- [Insertion Sort in Go](/projects/insertion-sort/go) -- [Insertion Sort in Haskell](/projects/insertion-sort/haskell) -- [Insertion Sort in Java](/projects/insertion-sort/java) -- [Insertion Sort in JavaScript](/projects/insertion-sort/javascript) -- [Insertion Sort in Kotlin](/projects/insertion-sort/kotlin) -- [Insertion Sort in Mathematica](/projects/insertion-sort/mathematica) -- [Insertion Sort in Octave](/projects/insertion-sort/octave) -- [Insertion Sort in PHP](/projects/insertion-sort/php) -- [Insertion Sort in Pascal](/projects/insertion-sort/pascal) -- [Insertion Sort in Perl](/projects/insertion-sort/perl) -- [Insertion Sort in PowerShell](/projects/insertion-sort/powershell) -- [Insertion Sort in Python](/projects/insertion-sort/python) -- [Insertion Sort in Ruby](/projects/insertion-sort/ruby) -- [Insertion Sort in Rust](/projects/insertion-sort/rust) -- [Insertion Sort in Swift](/projects/insertion-sort/swift) -- [Insertion Sort in Tcl](/projects/insertion-sort/tcl) -- [Insertion Sort in TypeScript](/projects/insertion-sort/typescript) -- [Insertion Sort in Visual Basic](/projects/insertion-sort/visual-basic) -- [Insertion Sort in m4](/projects/insertion-sort/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/insertion-sort/java/index.md b/docs/projects/insertion-sort/java/index.md deleted file mode 100644 index 847e449b47..0000000000 --- a/docs/projects/insertion-sort/java/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Ganesh Naik -- Jeremy Grifski -- Shubham Raj -date: 2019-10-15 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- insertion-sort -- java -title: Insertion Sort in Java -title1: Insertion -title2: Sort in Java ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.ArrayList; - -public class InsertionSort { - - public static void main(String[] args) { - - ArrayList numList = new ArrayList<>(); - - if (args.length < 1) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } - - else if (args[0].length() < 2) { - - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - String[] stringList = args[0].split(","); - - if (stringList.length < 2) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - - for (int i = 0; i < stringList.length; i++) { - numList.add(Integer.parseInt(stringList[i].trim())); - } - - if (numList.size() < 2) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - insertionSort(numList); - } - } - - } - - } - - public static void insertionSort(ArrayList numList) { - for (int j = 1; j < numList.size(); j++) { - int k = j - 1, val = numList.get(j); - while (k >= 0 && numList.get(k) > val) { - - numList.set(k + 1, numList.get(k)); - k--; - } - numList.set(k + 1, val); - } - for (int i = 0; i < numList.size() - 1; i++) { - System.out.print(numList.get(i) + ", "); - } - System.out.print(numList.get(numList.size() - 1)); - - } - -} - -``` - -{% endraw %} - -Insertion Sort in [Java](/languages/java) was written by: - -- Ganesh Naik -- Jeremy Grifski -- Shubham Raj - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/javascript/index.md b/docs/projects/insertion-sort/javascript/index.md deleted file mode 100644 index 7f57dccbe7..0000000000 --- a/docs/projects/insertion-sort/javascript/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Eliver L -- EliverLara -- rzuckerm -date: 2019-10-10 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- insertion-sort -- javascript -title: Insertion Sort in JavaScript -title1: Insertion Sort -title2: in JavaScript ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const insertionSort = (arr) => { - for (let i = 1; i < arr.length; i++){ - let key = arr[i]; - let j = i - 1; - while (j >= 0 && arr[j] > key) { - arr[j + 1] = arr[j]; - j--; - } - arr[j + 1] = key; - } - return arr; -} - -sanitizeArray = (list) => { - return list.split(',').map(e => { - _e = parseInt(e.replace(" ","")); - if (!_e){ throw new Error();} - return _e; - }); - } - - const exit = () => { - const usage = 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - console.log(usage) - process.exit(); - } - -const main = (input) => { - try { - arr = sanitizeArray(input); - arr.length <= 1 ? exit() : console.log(insertionSort(arr).join(", ")); - } catch(err) { - exit(); - } -} - -main(process.argv[2]) - -``` - -{% endraw %} - -Insertion Sort in [JavaScript](/languages/javascript) was written by: - -- Eliver L -- EliverLara -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/kotlin/index.md b/docs/projects/insertion-sort/kotlin/index.md deleted file mode 100644 index 2cae8088b3..0000000000 --- a/docs/projects/insertion-sort/kotlin/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2025-10-06 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2025-10-06 -layout: default -tags: -- insertion-sort -- kotlin -title: Insertion Sort in Kotlin -title1: Insertion Sort -title2: in Kotlin ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -import kotlin.system.exitProcess - -fun main(args: Array) { - val nums: IntArray = errorChecking(args) - insertionSort(nums) - outputList(nums) -} - -fun usageError() { - println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") -} - -fun errorChecking(args: Array): IntArray { - val nums: IntArray - try { - nums = args[0].split(", ").map { it.toInt() }.toIntArray() - } catch (e: Exception) { - usageError() - exitProcess(1) - } - if (nums.size < 2) { - usageError() - exitProcess(1) - } - return nums -} - -fun insertionSort(nums: IntArray) { - for (i in 1 until nums.count()) { - val toMove: Int = nums[i] - var j: Int = i - 1 - - while (j >= 0 && nums[j] > toMove) { - nums[j + 1] = nums[j] - j = j - 1 - } - - nums[j + 1] = toMove - } -} - -fun outputList(nums: IntArray) { - for (i in nums.indices) { - if (i == nums.count() - 1) { - println("${nums[i]}") - return - } - print("${nums[i]}, ") - } -} - -``` - -{% endraw %} - -Insertion Sort in [Kotlin](/languages/kotlin) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/m4/index.md b/docs/projects/insertion-sort/m4/index.md deleted file mode 100644 index b5c388d08a..0000000000 --- a/docs/projects/insertion-sort/m4/index.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-03 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2025-10-03 -layout: default -tags: -- insertion-sort -- m4 -title: Insertion Sort in m4 -title1: Insertion -title2: Sort in m4 ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl show_int_list(varname): -dnl for i = 0 to n-1: -dnl if i > 0: -dnl Output ", " -dnl Output varname[i] -define(`show_int_list', `_show_int_list(`$1', 0)') -define(`_show_int_list', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`ifelse(eval($2 > 0), 1, `, ')dnl -array_get(`$1', $2)`'dnl -_show_int_list(`$1', incr($2))'`'dnl -)'dnl -) - -dnl Reference: https://en.wikipedia.org/wiki/Insertion_sort#Algorithm -dnl for i = 1 to n-1: -dnl x = varname[i] -dnl j = i -dnl while j > 0 and varname[j-1] > x: -dnl varname[j] = varname[j-1] -dnl j = j - 1 -dnl varname[j] = x -define(`insertion_sort',`_insertion_sort_outer(`$1', 1)') -define(`_insertion_sort_outer', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`_insertion_sort_inner(`$1', $2, array_get(`$1', $2))dnl -_insertion_sort_outer(`$1', incr($2))'dnl -)'dnl -) - -define(`_insertion_sort_inner', -`ifelse(eval($2 <= 0), 1, `array_set(`$1', `$2', `$3')', -`ifelse(eval(array_get(`$1', decr($2)) < $3), 1, `array_set(`$1', `$2', `$3')', -`array_set(`$1', $2, array_get(`$1', decr($2)))dnl -_insertion_sort_inner(`$1', decr($2), `$3')'dnl -)'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !parse_int_list(`arr', ARGV1)), 1, `show_usage()')dnl -ifelse(eval(array_get(`arr', `length') < 2), 1, `show_usage()')dnl -insertion_sort(`arr')dnl -show_int_list(`arr') - -``` - -{% endraw %} - -Insertion Sort in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/mathematica/index.md b/docs/projects/insertion-sort/mathematica/index.md deleted file mode 100644 index a9faa0a441..0000000000 --- a/docs/projects/insertion-sort/mathematica/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- insertion-sort -- mathematica -title: Insertion Sort in Mathematica -title1: Insertion Sort -title2: in Mathematica ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual insertion sort which takes and returns a Mathematica list is easy: *) - -insertionSort = l \[Function] NestWhile[ - (* insert a single element *) - Module[{li = Length[#] + 1}, - Insert[ - #, (* sorted list so far *) - l[[li]],(* next element to insert *) - First[FirstPosition[#, (* at what index to insert it *) - v_ /; v > l[[li]], (* element that is greater than the element to insert *) - {li},(* or else insert at end *) - {1}, Heads -> False](* only look at list elements *)]]] &, - - (* start with an empty sorted list *) - {}, - - (* while there are still elements left to insert into the sorted list *) - Length[#] < Length[l] &]; - -(* The outer function provides the 'user interface': *) - -insertionSortMain = Function[{l}, - Module[{e = "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""}, - Catch[ - StringRiffle[(* format output as required *) - insertionSort @@ Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments to insertion sort: list of items *) - {If[Length[#] > 1, #, Throw[e]] &[StringSplit[l, ", "]]}, - {-1} (* at each leaf *)], - ", "]]]]; - - -(* Valid Tests *) - -Print /@ insertionSortMain /@ { - "4, 5, 3, 1, 2", - "4, 5, 3, 1, 4, 2", - "1, 2, 3, 4, 5", - "9, 8, 7, 6, 5, 4, 3, 2, 1" - }; - - -(* Invalid Tests *) - -insertionSortMain[""] -insertionSortMain["1"] -insertionSortMain["4 5 3"] - -``` - -{% endraw %} - -Insertion Sort in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/octave/index.md b/docs/projects/insertion-sort/octave/index.md deleted file mode 100644 index 629367748c..0000000000 --- a/docs/projects/insertion-sort/octave/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- insertion-sort -- octave -title: Insertion Sort in Octave -title1: Insertion Sort -title2: in Octave ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function insertion_sort() - %input validation - usage = 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - arg_list = argv(); - nargin = length(arg_list); - if nargin == 0 - %if there was no input - disp(usage); - return; - end - - array_string = arg_list{1}; - array_size = sum(array_string == ',') + 1; - if array_size < 2 - disp(usage); - return; - end - - %build array - array = str2num(array_string); - if length(array) ~= array_size || any(mod(array, 1) ~= 0) - disp(usage); - return; - end - - %insertion sort in ascending order - for i = 2:array_size - d = i; - while d > 1 && array(d) < array(d-1) - temp = array(d); - array(d) = array(d-1); - array(d-1) = temp; - d = d - 1; - end - end - - %convert to string - result_string = num2str(array); - - %replace space with ', ' - result_string = regexprep(result_string, '\s+', ', '); - disp(result_string); -end - -``` - -{% endraw %} - -Insertion Sort in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/pascal/index.md b/docs/projects/insertion-sort/pascal/index.md deleted file mode 100644 index 22c4b536ca..0000000000 --- a/docs/projects/insertion-sort/pascal/index.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- insertion-sort -- pascal -title: Insertion Sort in Pascal -title1: Insertion Sort -title2: in Pascal ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program InsertionSort; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - StrUtils, - SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) < 2 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function FormatIntegerList(const List: TIntegerList): string; -var - i: integer; -begin - Result := ''; - for i := 0 to List.Count - 1 do - begin - if i > 0 then - Result += ', '; - Result += IntToStr(List[i]); - end; -end; - -procedure InsertionSort(List: TIntegerList); -var - i, j, key, insertPos: integer; - AlreadySorted: boolean; - -// This is an optional optimization on insertion sort, reducing the number of -// comparisons needed. Essentially, we're using binary search to find the -// appropiate position. Binary search is O(log n), so the number of -// comparisons will be O(n log n) as opposed to O(n²). The time complexity -// is still O(n²). - function FindInsertPosition(const Key: integer; HighBound: integer): integer; - var - Low, High, Mid: integer; - begin - Low := 0; - High := HighBound - 1; // search only within sorted portion (0..i-1) - - while Low <= High do - begin - Mid := Low + (High - Low) shr 1; - if List[Mid] < Key then - Low := Mid + 1 - else - High := Mid - 1; - end; - - Result := Low; - end; - -begin - if List.Count <= 1 then - Exit; - - for i := 1 to List.Count - 1 do - begin - key := List[i]; - - // Optimization: skip if key is already greater or equal to previous element - if key >= List[i - 1] then - Continue; - - // Find insertion position in sorted subarray [0..i-1] - insertPos := FindInsertPosition(key, i); - - // Shift elements to the right to make room for key - j := i; - while j > insertPos do - begin - List[j] := List[j - 1]; - Dec(j); - end; - - List[insertPos] := key; - end; -end; - -var - rawArg: string; - numbers: TIntegerList; -begin - if ParamCount <> 1 then - ShowUsage; - - rawArg := ParamStr(1); - numbers := ParseIntegerList(rawArg); - try - InsertionSort(numbers); - Writeln(FormatIntegerList(numbers)); - finally - numbers.Free; - end; -end. - -``` - -{% endraw %} - -Insertion Sort in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/perl/index.md b/docs/projects/insertion-sort/perl/index.md deleted file mode 100644 index 1fade9cead..0000000000 --- a/docs/projects/insertion-sort/perl/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- SourabhBadhya -- Ștefan-Iulian Alecu -date: 2020-10-02 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- insertion-sort -- perl -title: Insertion Sort in Perl -title1: Insertion -title2: Sort in Perl ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -use feature qw/keyword_any/; -no warnings 'experimental::keyword_any'; - -sub usage { - say 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - exit; -} - -sub parse_list ($s) { - return undef unless defined $s; - - my @vals = split /\s*,\s*/, $s; - - return undef if @vals < 2; - return undef if any { $_ !~ /\A-?\d+\z/ } @vals; - - return [ map 0 + $_, @vals ]; -} - -sub insertion_sort ($a) { - for my $i ( 1 .. $#$a ) { - my $key = $a->[$i]; - my $j = $i - 1; - - $a->[ $j + 1 ] = $a->[$j], $j-- while $j >= 0 && $a->[$j] > $key; - $a->[ $j + 1 ] = $key; - } - - return $a; -} - -my ($input) = @ARGV; -my $a = parse_list($input) or usage(); - -insertion_sort($a); -say join ', ', @$a; - -``` - -{% endraw %} - -Insertion Sort in [Perl](/languages/perl) was written by: - -- SourabhBadhya -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/php/index.md b/docs/projects/insertion-sort/php/index.md deleted file mode 100644 index 02088fc8e8..0000000000 --- a/docs/projects/insertion-sort/php/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -- sljtheultima -date: 2019-10-13 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- insertion-sort -- php -title: Insertion Sort in PHP -title1: Insertion -title2: Sort in PHP ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php -= 0 && $my_array[$j] > $val) { - $my_array[$j + 1] = $my_array[$j]; - $j--; - } - $my_array[$j + 1] = $val; - } - return $my_array; -} - -if (empty($argv[1])) { - exit('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); -} - -$test_array = array_map('intval', explode(',', $argv[1])); -$array_size = count($test_array); - -if ($array_size <= 1) { - exit('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); -} - -$out = insertion_Sort($test_array); -echo implode(', ', $out); - -``` - -{% endraw %} - -Insertion Sort in [PHP](/languages/php) was written by: - -- Jeremy Grifski -- Parker Johansen -- sljtheultima - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/powershell/index.md b/docs/projects/insertion-sort/powershell/index.md deleted file mode 100644 index 1324514afd..0000000000 --- a/docs/projects/insertion-sort/powershell/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-14 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2025-07-14 -layout: default -tags: -- insertion-sort -- powershell -title: Insertion Sort in PowerShell -title1: Insertion Sort -title2: in PowerShell ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -# https://en.wikipedia.org/wiki/Insertion_sort#Algorithm -function Invoke-InsertionSort([array]$Values) { - $n = $Values.Length - $i = 1 - for ($i = 1; $i -lt $n; $i++) { - $x = $Values[$i] - $j = $i - while ($j -gt 0 -and $Values[$j - 1] -gt $x) { - $Values[$j] = $Values[$j - 1] - $j-- - } - - $Values[$j] = $x - } -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $values = Parse-IntList $args[0] - if ($values.Length -lt 2) { - Show-Usage - } -} catch { - Show-Usage -} - -Invoke-InsertionSort $values -Write-Host ($values -join ', ') - -``` - -{% endraw %} - -Insertion Sort in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/python/index.md b/docs/projects/insertion-sort/python/index.md deleted file mode 100644 index f80f5ef0d6..0000000000 --- a/docs/projects/insertion-sort/python/index.md +++ /dev/null @@ -1,255 +0,0 @@ ---- -authors: -- Haseeb Majid -- Jeremy Grifski -- Parker Johansen -- rzuckerm -date: 2018-12-22 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- insertion-sort -- python -title: Insertion Sort in Python -title1: Insertion Sort -title2: in Python ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys -from itertools import takewhile - - -def insertion_sort(xs): - new_xs = [] - for x in xs: - new_xs = insert(x, new_xs) - return new_xs - - -def insert(x, xs): - left = list(takewhile(lambda i: i < x, xs)) - right = xs[len(left):] - return left + [x] + right - - -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] - - -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) - - -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(insertion_sort(xs)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Insertion Sort in [Python](/languages/python) was written by: - -- Haseeb Majid -- Jeremy Grifski -- Parker Johansen - -This article was written by: - -- Haseeb Majid -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's dig into the code a bit. The following sections break -down the Insertion Sort in Python functionality. - -### The Main Function - -Breaking down this solution bottom up: - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -This bit of code checks to see if this is the `main` module run. If it is, it then calls the `main` -function and passes user input to it. In this case the user input would be a string of numbers to sort -like so: `"2, 1, 10, 5, 3"`. - -```python -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(insertion_sort(xs)) - except (IndexError, ValueError): - exit_with_error() -``` - -This is the `main` function of this file. It parses the input, then calls our insertion sort -function (and prints the results). It also deals with any errors raised. - -### Transform Input Parameters - -```python -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] -``` - -This function takes a string like `"2, 1, 10, 5, 3"`, and turns into a list of numbers. -It does this using a list comprehension. First, we need to convert our string into a -list `list_str.split(',')` which is a list of strings split by comma (`,`). -So our original input string becomes `["2", " 1", " 10", " 5", " 3"]`. Then for each -element in the list `for x in ...` , we do something to it. - -In this example we convert it into a decimal integer, `int(x.strip(" "), 10)`. Then, `x.strip(" ")` -removes any whitespace so `" 1"` becomes `"1"`. After that, `int("1", 10)` -converts the string `"1"` into a decimal number in this case `1`. This is done -for every item in the list so our original input of `"2, 1, 10, 5, 3"` becomes `[2, 1, 10, 5, 3]`. - -### Throw Errors - -```python -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) -``` - -This function prints a message and then exits the script with an error, `sys.exit(1)`. -If any non-zero value is returned then the program didn't complete properly. This function is called -if the user input isn't correct. - -### Insertion Sort - -```python -def insertion_sort(xs): - new_xs = [] - for x in xs: - new_xs = insert(x, new_xs) - return new_xs -``` - -Let's take a look at the part of the program that sorts our list. The unsorted list is passed to the -`insertion_sort` method as the parameter `xs`. Meanwhile, `new_xs = []` is our new sorted listed which is -empty to begin with. - -We loop through every element in the unsorted list `for x in xs`. Then we call the `insert()` -function to add `x` to the `new_xs` (the sorted list) in the correct position. -Each time the `insert()` function is called it returns a sorted list which we assign -to `new_xs`. Finally, when we've looped through every item in `xs`, we return the sorted list -`new_xs` which will then get printed on the terminal to the user. - -Taking a look at an example where `xs = [5, 3, 10]` - -1st - -* `x = 5` -* `insert(5, [])` -* `new_xs = [5]` - -2nd - -* `x = 3` -* `insert(3, [5])` -* `new_xs = [3, 5]` - -3rd - -* `x = 10` -* `insert(10, [3, 5])` -* `new_xs = [3, 5, 10]` - -### Insert - -```python -def insert(x, xs): - left = list(takewhile(lambda i: i < x, xs)) - right = xs[len(left):] - return left + [x] + right -``` - -This function takes two parameters `x`, which is an element from our unsorted list, and -`xs`, which is the list to add `x` to such that `xs` remains sorted. -A High-level overview of this function is that the `left` variable will be a list that stores -all elements less than `x` from `xs` and `right` will store all elements greater than (or equal) -to `x`. That way we can "insert" `x` between these two lists. Hence the return statement -looking like `return left + [x] + right` and this returned list will therefore be sorted. - -Let's take a look at the first line `left = list(takewhile(lambda i: i < x, xs))` it looks a bit -complicated so let's break it down. The first part `lambda i: i < x, xs` is a lambda function -which is a small anonymous unnamed function. -In this case `i` is an element of `xs` and we want all `i`'s less than `x`. - -Then, we call `takewhile(lambda i: i < x, xs)` which takes a predicate (our lambda function) and a list. -It stops iterating over our list as soon as the lambda function evaluates to False. It then returns -all the elements up to that index. - -Lets take a look at an example where `xs = [4, 7, 10]` and `x = 8`. -The first two items of `xs` would evaluate as True since 4 and 7 are -less than 8, so takewhile would store 4 and 7 but not 10. -The `takewhile()` function returns a `takewhile` object but we want a list so we convert that into a -list hence `list(takewhile(lambda i: i < x, xs))`. So the `left` variable will store all numbers -less than `x`, since `xs` is already sorted. - -Moving onto `right = xs[len(left):]`, `len(left)` returns the length of the left list. -Then we do some index splicing; you can learn more about that -[here](https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/). -Index splicing is used to get part of a list in Python. In this case we are getting every element in -the list that's not already in `left`. We can do this because we know `xs` is already sorted. - -If `xs = [1, 4, 6, 8]` and `x = 7` then `left = [1, 4, 6]` (all elements < 7). Then `len(left) = 3` -and `right = xs[3:]`. Where `[3:]` gets all elements from `xs` not including the first `3` elements, -so therefore `right = [8]`. Finally, we `return left + [x] + right` as we can simply "slot" `x` into the -correct position. We convert `x` to a list `[x]` first so we can do list concatenation using the -plus operator `+`. - -Lets take a look at an example, `xs = [3, 4, 6, 8, 11, 15, 18]` and `x` is `5`. The variable `left` -will add consecutive elements from `xs` until `lambda i: i < x` (i < x) evaluates as False. -In this case `left = [3, 4]` as 6 > 5. Then we get the length of `left` which is `len(left) = 2`, -slice so we don't include the first two elements `xs[2:] = [6, 8, 11, 15, 18]`. Then we return -the following `left + [x] + right = [3, 4] + [5] + [6, 8, 11, 15, 18]` or -`[3, 4, 5, 6, 8, 11, 15, 18]`. - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Insertion Sort in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/insertion_sort.py). -After that, we should make sure we have the latest Python interpreter. From there, we can run the following command in the terminal: - -`python insertion-sort.py "3, 2, 10, 6, 1, 7"` - -Alternatively, we can copy the solution into an [online Python interpreter](https://www.online-python.com/) and hit run. diff --git a/docs/projects/insertion-sort/ruby/index.md b/docs/projects/insertion-sort/ruby/index.md deleted file mode 100644 index cb315cf411..0000000000 --- a/docs/projects/insertion-sort/ruby/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- insertion-sort -- ruby -title: Insertion Sort in Ruby -title1: Insertion -title2: Sort in Ruby ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -class Array - def insertion_sort! - (1...length).each do |i| - value = self[i] - j = i - 1 - - while j >= 0 && self[j] > value - self[j + 1] = self[j] - j -= 1 - end - - self[j + 1] = value - end - - self - end -end - -def usage! - abort %(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5") -end - -def parse_input - raw = ARGV.first - usage! if raw.nil? || raw.strip.empty? - - numbers = raw.split(",").map { Integer(it.strip) } - usage! if numbers.length < 2 - - numbers -rescue ArgumentError - usage! -end - -puts parse_input.insertion_sort!.join(", ") - -``` - -{% endraw %} - -Insertion Sort in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/rust/index.md b/docs/projects/insertion-sort/rust/index.md deleted file mode 100644 index 83fa5cee89..0000000000 --- a/docs/projects/insertion-sort/rust/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Andrew Johnson -- rzuckerm -date: 2020-10-03 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- insertion-sort -- rust -title: Insertion Sort in Rust -title1: Insertion -title2: Sort in Rust ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -fn insertion_sort(arr: &mut Vec) { - for i in 0..arr.len() { - for j in (0..i).rev() { - if arr[j] >= arr[j+1] { - arr.swap(j, j+1); - } else { - break; - } - } - } -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let mut arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if list too small - if arr.len() < 2 { - usage(); - } - - insertion_sort(&mut arr); - println!("{arr:?}"); -} - -``` - -{% endraw %} - -Insertion Sort in [Rust](/languages/rust) was written by: - -- Andrew Johnson -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/swift/index.md b/docs/projects/insertion-sort/swift/index.md deleted file mode 100644 index 28a6b9afc9..0000000000 --- a/docs/projects/insertion-sort/swift/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- insertion-sort -- swift -title: Insertion Sort in Swift -title1: Insertion -title2: Sort in Swift ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseIntegers(from args: [String]) -> [Int]? { - guard args.count == 2 else { return nil } - - let parts = args[1].split(separator: ",", omittingEmptySubsequences: false) - let values = parts.compactMap { Int($0.trimmed) } - - guard values.count == parts.count, - values.count >= 2 - else { - return nil - } - - return values -} - -extension MutableCollection where Self: BidirectionalCollection { - mutating func insertionSort(by areInIncreasingOrder: (Element, Element) -> Bool) { - guard count > 1 else { return } - - var i = index(after: startIndex) - - while i < endIndex { - let key = self[i] - var j = i - - while j > startIndex { - let prev = index(before: j) - - if areInIncreasingOrder(key, self[prev]) { - self[j] = self[prev] - j = prev - } else { - break - } - } - - self[j] = key - i = index(after: i) - } - } -} - -guard var numbers = parseIntegers(from: CommandLine.arguments) else { - print(usage) - exit(1) -} - -numbers.insertionSort(by: <) - -print(numbers.map(String.init).joined(separator: ", ")) - -``` - -{% endraw %} - -Insertion Sort in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/tcl/index.md b/docs/projects/insertion-sort/tcl/index.md deleted file mode 100644 index 3347b11e63..0000000000 --- a/docs/projects/insertion-sort/tcl/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- insertion-sort -- tcl -title: Insertion Sort in Tcl -title1: Insertion -title2: Sort in Tcl ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"} - exit 1 -} - -proc parseList {s} { - set tokens [split [string trim $s] ","] - if {[llength $tokens] < 2} { usage } - - set result {} - - set result {} - foreach token $tokens { - set t [string trim $token] - if {$t eq "" || [catch {expr {int($t)}} val]} usage - lappend result $val - } - return $result -} - -proc isSorted {lst} { - set prev [lindex $lst 0] - foreach x [lrange $lst 1 end] { - if {$x < $prev} {return 0} - set prev $x - } - return 1 -} - -proc insertionSort {lstVar} { - upvar 1 $lstVar lst - set n [llength $lst] - if {$n <= 1} {return} - - set findInsertPos [list {lst key high} { - set low 0 - incr high -1 - while {$low <= $high} { - set mid [expr {($low + $high) / 2}] - if {[lindex $lst $mid] < $key} { - incr low - } else { - incr high -1 - } - } - return $low - }] - - for {set i 1} {$i < $n} {incr i} { - set key [lindex $lst $i] - - if {$key >= [lindex $lst [expr {$i - 1}]]} { - continue - } - - set pos [apply $findInsertPos $lst $key $i] - - set before [lrange $lst 0 [expr {$pos - 1}]] - set middle [list $key] - set after [lrange $lst $pos [expr {$i - 1}]] - set rest [lrange $lst [expr {$i + 1}] end] - - set lst [concat $before $middle $after $rest] - } -} - -proc formatList {lst} { return [join $lst ", "] } - -if {$argc != 1} { usage } - -set numbers [parseList [lindex $argv 0]] - -if {![isSorted $numbers]} { - insertionSort numbers -} - -puts [formatList $numbers] - -``` - -{% endraw %} - -Insertion Sort in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/typescript/index.md b/docs/projects/insertion-sort/typescript/index.md deleted file mode 100644 index 02747ec475..0000000000 --- a/docs/projects/insertion-sort/typescript/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- Raakesh.R -date: 2023-10-22 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2023-10-22 -layout: default -tags: -- insertion-sort -- typescript -title: Insertion Sort in TypeScript -title1: Insertion Sort -title2: in TypeScript ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function insertionSort(arr: number[]): number[] { - const n = arr.length; - - for (let i = 1; i < n; i++) { - const currentElement = arr[i]; - let j = i - 1; - - while (j >= 0 && arr[j] > currentElement) { - arr[j + 1] = arr[j]; - j--; - } - - arr[j + 1] = currentElement; - } - - return arr; -} - -const error_msg: string = - 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - -if (process.argv.length != 3) { - console.log(error_msg); - process.exit(1); -} - -let list_str: string = process.argv[2]; - -if (list_str.length == 0) { - console.log(error_msg); - process.exit(1); -} -let list: number[] = list_str.split(",").map((x: string) => parseInt(x)); -if (list.length < 2) { - console.log(error_msg); - process.exit(1); -} -const sortedArray: number[] = insertionSort(list); -console.log(sortedArray.join(", ")); -``` - -{% endraw %} - -Insertion Sort in [TypeScript](/languages/typescript) was written by: - -- Raakesh.R - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/insertion-sort/visual-basic/index.md b/docs/projects/insertion-sort/visual-basic/index.md deleted file mode 100644 index 2c4d3501f3..0000000000 --- a/docs/projects/insertion-sort/visual-basic/index.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: insertion-sort-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- insertion-sort -- visual-basic -title: Insertion Sort in Visual Basic -title1: Insertion Sort -title2: in Visual Basic ---- - - - -Welcome to the [Insertion Sort](/projects/insertion-sort) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module InsertionSort - - Public Function Sort(Of T)(input As IEnumerable(Of T), - Optional compare As IComparer(Of T) = Nothing) As List(Of T) - - If compare Is Nothing Then - compare = Comparer(Of T).Default - End If - - Dim result As New List(Of T) - - For Each item In input - Insert(result, item, compare) - Next - - Return result - - End Function - - - Private Sub Insert(Of T)(list As List(Of T), - value As T, - comparer As IComparer(Of T)) - - Dim low As Integer = 0 - Dim high As Integer = list.Count - 1 - - While low <= high - - Dim mid As Integer = low + ((high - low) \ 2) - - If comparer.Compare(list(mid), value) < 0 Then - low = mid + 1 - Else - high = mid - 1 - End If - - End While - - list.Insert(low, value) - - End Sub - - - Private Sub ShowUsage() - - Console.WriteLine( - "Usage: please provide a list of at least two integers to sort " & - "in the format ""1, 2, 3, 4, 5""" - ) - - Environment.Exit(1) - - End Sub - - - Public Sub Main(args As String()) - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim parts = args(0).Split(","c, StringSplitOptions.RemoveEmptyEntries) - - Dim numbers As New List(Of Integer) - - For Each p In parts - - Dim value As Integer - - If Not Integer.TryParse(p.Trim(), value) Then - ShowUsage() - End If - - numbers.Add(value) - - Next - - If numbers.Count < 2 Then - ShowUsage() - End If - - Dim sorted = Sort(numbers) - - Console.WriteLine(String.Join(", ", sorted)) - - End Sub - -End Module -``` - -{% endraw %} - -Insertion Sort in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/ada/index.md b/docs/projects/job-sequencing/ada/index.md deleted file mode 100644 index acb696549f..0000000000 --- a/docs/projects/job-sequencing/ada/index.md +++ /dev/null @@ -1,228 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-10 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-10 -layout: default -tags: -- ada -- job-sequencing -title: Job Sequencing in Ada -title1: Job Sequencing -title2: in Ada ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -pragma Ada_2022; - -with Ada.Text_IO; -with Ada.Command_Line; -with Ada.Strings.Fixed; -with Ada.Containers.Vectors; - -procedure Job_Sequencing is - package IO renames Ada.Text_IO; - package CL renames Ada.Command_Line; - package SF renames Ada.Strings.Fixed; - - Parse_Error : exception; - - package Job_Vec is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - type Job is record - Profit : Integer; - Deadline : Natural; - end record; - - package Jobs_Vec is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Job); - - function To_Int (S : String) return Integer is - begin - return Integer'Value (SF.Trim (S, Ada.Strings.Both)); - exception - when others => - raise Parse_Error; - end To_Int; - - procedure Next_Token - (S : String; - Pos : in out Positive; - First : out Positive; - Last : out Natural; - Done : out Boolean) is - begin - First := Pos; - - while Pos <= S'Last and then S (Pos) /= ',' loop - Pos := Pos + 1; - end loop; - - Last := Pos - 1; - Done := Pos > S'Last; - - if not Done then - Pos := Pos + 1; -- skip comma - - end if; - end Next_Token; - - function Parse_Jobs (Profits_S, Deadlines_S : String) return Jobs_Vec.Vector - is - use Ada.Containers; - Jobs : Jobs_Vec.Vector; - - PI : Positive := Profits_S'First; - DI : Positive := Deadlines_S'First; - - Done_P, Done_D : Boolean; - P_First, P_Last : Positive; - D_First, D_Last : Positive; - - function Next_Token - (S : String; - Pos : in out Positive; - First : out Positive; - Last : out Natural; - Done : out Boolean) return Boolean is - begin - First := Pos; - - while Pos <= S'Last and then S (Pos) /= ',' loop - Pos := Pos + 1; - end loop; - - Last := Pos - 1; - Done := Pos > S'Last; - - if not Done then - Pos := Pos + 1; - end if; - - return Done; - end Next_Token; - - begin - if Profits_S'Length = 0 or else Deadlines_S'Length = 0 then - raise Parse_Error; - end if; - - loop - Next_Token (Profits_S, PI, P_First, P_Last, Done_P); - Next_Token (Deadlines_S, DI, D_First, D_Last, Done_D); - - if Done_P /= Done_D then - raise Parse_Error; - end if; - - declare - Profit : Integer := Integer'Value (Profits_S (P_First .. P_Last)); - - Deadline : Natural := - Natural (Integer'Value (Deadlines_S (D_First .. D_Last))); - begin - Jobs.Append (Job'(Profit => Profit, Deadline => Deadline)); - end; - - exit when Done_P; - end loop; - - if Jobs.Length < 2 then - raise Parse_Error; - end if; - - return Jobs; - end Parse_Jobs; - - function By_Profit (L, R : Job) return Boolean - is (L.Profit > R.Profit); - - package Job_Sort is new Jobs_Vec.Generic_Sorting (By_Profit); - - function Max_Profit (Jobs : Jobs_Vec.Vector) return Integer is - Max_D : Natural := 0; - Sum : Integer := 0; - begin - for J of Jobs loop - Max_D := Natural'Max (Max_D, J.Deadline); - end loop; - - declare - Slots : array (1 .. Max_D) of Boolean := (others => False); - begin - for J of Jobs loop - for T in reverse 1 .. J.Deadline loop - if not Slots (T) then - Slots (T) := True; - Sum := Sum + J.Profit; - exit; - end if; - end loop; - end loop; - end; - - return Sum; - end Max_Profit; - - procedure Print_Usage is - begin - IO.Put_Line - ("Usage: please provide a list of profits and a list of deadlines"); - end Print_Usage; - - Jobs : Jobs_Vec.Vector; - -begin - if CL.Argument_Count /= 2 then - Print_Usage; - CL.Set_Exit_Status (CL.Failure); - return; - end if; - - Jobs := Parse_Jobs (CL.Argument (1), CL.Argument (2)); - Job_Sort.Sort (Jobs); - - IO.Put_Line (Integer'Image (Max_Profit (Jobs))); - -exception - when Parse_Error => - Print_Usage; - CL.Set_Exit_Status (CL.Failure); -end Job_Sequencing; - -``` - -{% endraw %} - -Job Sequencing in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/algol60/index.md b/docs/projects/job-sequencing/algol60/index.md deleted file mode 100644 index 914a029491..0000000000 --- a/docs/projects/job-sequencing/algol60/index.md +++ /dev/null @@ -1,321 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-18 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- job-sequencing -title: Job Sequencing in ALGOL 60 -title1: Job Sequencing -title2: in ALGOL 60 ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of profits and a list of deadlines\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Job sequencing with deadlines. Source - https://www.techiedelight.com/job-sequencing-problem-deadlines/; - integer procedure jobSequencing(profits, deadlines, n); - value n; - integer array profits, deadlines; - integer n; - begin - integer i, j, d, maxDeadline, totalProfit; - integer array jobs[1:n, 1:2]; - - comment Set up jobs and get maximum deadline; - maxDeadline := 0; - for i := 1 step 1 until n do - begin - d := deadlines[i]; - jobs[i, 1] := profits[i]; - jobs[i, 2] := d; - if d > maxDeadline then maxDeadline := d - end; - - comment Initialize total profit; - totalProfit := 0; - - begin - comment Initialize slots; - integer array slots[1:maxDeadline]; - - for i := 1 step 1 until maxDeadline do slots[i] := 0; - - comment Sort jobs by profit then deadline; - bubbleSort(jobs, n); - - for i := 1 step 1 until n do - begin - comment For each job, see if there is available slot at or - before the deadline. If so, store this job index in that - slot and update total profit; - j := jobs[i, 2] + 1; - searchloop: - j := j - 1; - if j >= 1 then - begin - if slots[j] > 0 then goto searchloop; - slots[j] := i; - totalProfit := totalProfit + jobs[i, 1] - end - end; - end; - - - jobSequencing := totalProfit - end jobSequencing; - - comment Source https://en.wikipedia.org/wiki/Bubble_sort#Optimizing_bubble_sort; - procedure bubbleSort(jobs, numJobs); - value numJobs; - integer array jobs; - integer numJobs; - begin - integer i, n, newN; - - n := numJobs; - sortloop: - newN := 1; - for i := 2 step 1 until n do - begin - if compareJobs(jobs, i - 1, i) > 0 then - begin - swapJobs(jobs, i - 1, i); - newN := i - end - end; - - n := newN; - if n > 2 then goto sortloop - end bubbleSort; - - comment Prioritize job with highest profit then longest deadline. - For jobs, profits are in column 1, deadlines as in column 2. - Returns: - - negative if first job has higher priority - - zero if both jobs have same priority - - positive if second job has higher priority; - integer procedure compareJobs(jobs, i, j); - value i, j; - integer array jobs; - integer i, j; - begin - compareJobs := if jobs[i, 1] != jobs[j, 1] then jobs[j, 1] - jobs[i, 1] - else jobs[j, 2] - jobs[i, 2] - end compareJobs; - - procedure swapJobs(jobs, i, j); - value i, j; - integer array jobs; - integer i, j; - begin - procedure swap(a, b); - integer a, b; - begin - integer t; - - t := a; - a := b; - b := t - end swap; - - swap(jobs[i, 1], jobs[j, 1]); - swap(jobs[i, 2], jobs[j, 2]) - end swapJobs; - - integer argc, numProfits, numDeadlines, result; - integer array profits[1:100], deadlines[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 2 then usage; - - comment Get profits from 1st argument. Exit if invalid; - numProfits := inIntegerArray(profits, 100); - if numProfits < 1 then usage; - - comment Get deadlines from 2nd argument. Exit if invalid or the number - of deadlines is not the same as the number of profits; - numDeadlines := inIntegerArray(deadlines, 100); - if numDeadlines != numProfits then usage; - - comment Find best sum of profits and display result; - result := jobSequencing(profits, deadlines, numProfits); - outinteger(1, result); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Job Sequencing in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/algol68/index.md b/docs/projects/job-sequencing/algol68/index.md deleted file mode 100644 index 90a5598f42..0000000000 --- a/docs/projects/job-sequencing/algol68/index.md +++ /dev/null @@ -1,296 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-06 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2023-02-06 -layout: default -tags: -- algol68 -- job-sequencing -title: Job Sequencing in ALGOL 68 -title1: Job Sequencing -title2: in ALGOL 68 ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: printf(($gl$, "Usage: please provide a list of profits and a list of deadlines")); - -# Job details # -MODE JOB = STRUCT(INT id, INT profit, INT deadline); - -# Compare 2 jobs # -OP <= = (JOB job1, JOB job2) BOOL: -( - # Prioritize by profit, then deadline # - (profit OF job1 /= profit OF job2 | profit OF job1 - profit OF job2 > 0 | deadline OF job1 - deadline OF job2 >= 0) -); - -COMMENT -Source: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme -COMMENT -PROC quick sort = (REF []JOB values) VOID: -( - quick sort rec(values, 1, UPB values) -); - -PROC quick sort rec = (REF []JOB values, INT lo, INT hi) VOID: -( - IF lo < hi AND lo >= 1 - THEN - # Partition array and get pivot value # - INT p := partition(values, lo, hi); - - # Sort left side of partition # - quick sort rec(values, lo, p - 1); - - # Sort right side of partition # - quick sort rec(values, p + 1, hi) - FI -); - -PROC partition = (REF []JOB values, INT lo, INT hi) INT: -( - # Choose last value as pivot # - JOB pivot = values[hi]; - - # Set temporary pivot index # - INT i := lo - 1; - - # Swap elements less than or equal to pivot, and increment temporary index # - FOR j FROM lo TO hi - 1 - DO - IF values[j] <= pivot - THEN - i +:= 1; - swap(values, i, j) - FI - OD; - - # Move pivot to correct position # - i +:= 1; - swap(values, i, hi); - - i -); - -PROC swap = (REF []JOB values, INT a, INT b) VOID: -( - JOB temp := values[a]; - values[a] := values[b]; - values[b] := temp -); - -PROC max = (INT a, INT b) INT: (a > b | a | b); - -COMMENT -Job sequencing with deadlines -Source: https://www.techiedelight.com/job-sequencing-problem-deadlines/ -COMMENT -PROC job sequencing = (REF []INT profits, REF []INT deadlines) REF []JOB: -( - # Set up job details and longest deadline # - INT n = UPB profits; - HEAP [n]JOB jobs; - INT longest deadline := 0; - FOR k TO n - DO - jobs[k] := JOB(k, profits[k], deadlines[k]); - longest deadline := max(longest deadline, deadlines[k]) - OD; - - # Initialize job slots # - HEAP [longest deadline]JOB slots; - FOR k TO longest deadline - DO - slots[k] := JOB(0, 0, 0) - OD; - - # Sort jobs by profit then deadline # - quick sort(jobs); - - FOR i TO n - DO - # For each job, see if there is available slot at or before the deadline # - # if so, store this job in that slot # - BOOL slot found := FALSE; - FOR j FROM deadline OF jobs[i] DOWNTO 1 - WHILE NOT slot found - DO - IF id OF slots[j] < 1 - THEN - slots[j] := jobs[i]; - slot found := TRUE - FI - OD - OD; - - slots -); - -# Get total profit # -PROC get total profit = (REF []JOB jobs) INT: -( - INT total := 0; - FOR k TO UPB jobs - DO - total +:= profit OF jobs[k] - OD; - - total -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT profits := values OF list result; -IF NOT valid OF list result -THEN - usage; - stop -FI; - -# Parse 2nd command-line argument # -s := argv(5); -list result := parse int list(s); -REF []INT deadlines := values OF list result; -IF NOT valid OF list result OR UPB deadlines /= UPB profits -THEN - usage; - stop -FI; - -# Get job sequence # -REF []JOB sequence := job sequencing(profits, deadlines); - -# Get total profit and display # -INT total profit := get total profit(sequence); -printf(($gl$, whole(total profit, 0))) - -``` - -{% endraw %} - -Job Sequencing in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/awk/index.md b/docs/projects/job-sequencing/awk/index.md deleted file mode 100644 index 6d96067e7d..0000000000 --- a/docs/projects/job-sequencing/awk/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-27 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2025-04-27 -layout: default -tags: -- awk -- job-sequencing -title: Job Sequencing in AWK -title1: Job Sequencing -title2: in AWK ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of profits and a list of deadlines" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -# Source: https://www.techiedelight.com/job-sequencing-problem-deadlines/ -function job_sequencing(profits, deadlines, jobs, slots, i, j, longest_deadline, temp_jobs) { - # Set up job details and longest deadline - longest_deadline = 0 - for (i in profits) { - temp_jobs[i]["id"] = i - temp_jobs[i]["profit"] = profits[i] - temp_jobs[i]["deadline"] = deadlines[i] - if (deadlines[i] > longest_deadline) { - longest_deadline = deadline[i] - } - } - - # Initialize job slots - for (i = 1; i <= longest_deadline; i++) { - slots[i] = 0 - } - - # Sort jobs by profit then deadline - asort(temp_jobs, jobs, "compare_profits_and_deadlines") - - # For each job, see if there is available slot at or before the deadline - # if so, store this job in that slot - for (i in jobs) { - for (j = jobs[i]["deadline"]; j >= 1; j--) { - if (!slots[j]) { - slots[j] = i - break - } - } - } -} - -# Prioritize by profit, then deadline -# Inputs: -# - i1 = Index 1 (unused) -# - v1 = Job 1 -# - i2 = Index 2 (unused) -# - v2 = Job 2 -# Returns: -# - negative if job 1 has higher profit or later deadline than job 2 -# - zero if job 1 has same profit and deadline as job 2 -# - positive if job 1 lower profit or sooner deadline than job 2 -function compare_profits_and_deadlines(i1, v1, i2, v2, diff) { - # Compare profits in reverse order since we want higher profits to be first - # If equal, compare deadlines in reverse order since we want later deadlines - # to be first - diff = v2["profit"] - v1["profit"] - return (diff != 0) ? diff : v2["deadline"] - v1["deadline"] -} - -function get_total_profit(profits, jobs, slots, total, idx) { - total = 0 - for (idx in slots) { - if (slots[idx]) { - total += jobs[slots[idx]]["profit"] - } - } - - return total -} - -BEGIN { - if (ARGC < 3) { - usage() - } - - str_to_array(ARGV[1], profits) - num_profits = length(profits) - str_to_array(ARGV[2], deadlines) - num_deadlines = length(deadlines) - if (!num_profits || profits[1] == "ERROR" || \ - !num_deadlines || deadlines[1] == "ERROR" || \ - num_profits != num_deadlines) { - usage() - } - - job_sequencing(profits, deadlines, jobs, slots) - total_profit = get_total_profit(profits, jobs, slots) - print total_profit -} - -``` - -{% endraw %} - -Job Sequencing in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/beef/index.md b/docs/projects/job-sequencing/beef/index.md deleted file mode 100644 index 94899352c4..0000000000 --- a/docs/projects/job-sequencing/beef/index.md +++ /dev/null @@ -1,251 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-18 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2024-02-18 -layout: default -tags: -- beef -- job-sequencing -title: Job Sequencing in Beef -title1: Job Sequencing -title2: in Beef ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace System.Collections -{ - extension List - where T : IMinMaxValue - where int : operator T <=> T - { - public T Max() - { - T max = T.MinValue; - for (T val in this) - { - if (val > max) - { - max = val; - } - } - - return max; - } - } -} - -namespace JobSequencing; - -struct JobInfo -where int : operator T <=> T -{ - public int mJobId; - public T mProfit; - public int mDeadline; - - public this(int jobId = 0, T profit = default(T), int deadline = 0) - { - mJobId = jobId; - mProfit = profit; - mDeadline = deadline; - } - - public bool IsAvailable => mJobId < 1; - - static public int operator <=>(JobInfo lhs, JobInfo rhs) - { - // Reverse order of compare so that it is in descending order by profit - // then deadline - int result = rhs.mProfit <=> lhs.mProfit; - if (result == 0) - { - result = rhs.mDeadline <=> lhs.mDeadline; - } - - return result; - } -} - -class JobList : List> -where T : operator T + T -where int : operator T <=> T -{ - public this() - { - } - - public this(List profits, List deadlines) - { - for (int i < profits.Count) - { - this.Add(.(i + 1, profits[i], deadlines[i])); - } - } - - public void AddEmptyJobs(int numJobs) - { - for (int i < numJobs) - { - this.Add(.()); - } - } - - public T GetTotalProfit() - { - T sum = default(T); - for (JobInfo job in this) - { - sum += job.mProfit; - } - - return sum; - } -} - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a list of profits and a list of deadlines"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Job sequencing with deadlines - // Source: https://www.techiedelight.com/job-sequencing-problem-deadlines/ - public static void JobSequencing(List profits, List deadlines, JobList slots) - where T : operator T + T - where int : operator T <=> T - { - // Set up job details - JobList jobs = scope .(profits, deadlines); - - // Get longest deadline - int longestDeadline = deadlines.Max(); - - // Initialize job slots - slots.Clear(); - slots.AddEmptyJobs(longestDeadline); - - // Sort jobs by profit then deadline - jobs.Sort(); - - // For each job, see if there is available slot at or before the deadline. - // If so, store this job in that slot - for (JobInfo job in jobs) - { - for (int j in (0.. profits = scope .(); - if (ParseIntList(args[0], profits) case .Err) - { - Usage(); - } - - List deadlines = scope .(); - if (ParseIntList(args[1], deadlines) case .Err) - { - Usage(); - } - - if (profits.Count != deadlines.Count) - { - Usage(); - } - - JobList jobs = scope .(); - JobSequencing(profits, deadlines, jobs); - int32 total = jobs.GetTotalProfit(); - Console.WriteLine(total); - - return 0; - } -} -``` - -{% endraw %} - -Job Sequencing in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/c-plus-plus/index.md b/docs/projects/job-sequencing/c-plus-plus/index.md deleted file mode 100644 index bc0d747a31..0000000000 --- a/docs/projects/job-sequencing/c-plus-plus/index.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -authors: -- Apurva Vats -- Ștefan-Iulian Alecu -date: 2025-10-31 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- job-sequencing -title: Job Sequencing in C++ -title1: Job Sequencing -title2: in C++ ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -struct Job { - int profit{}; - int deadline{}; -}; - -struct DSU { - std::vector parent; - - explicit DSU(int n) : parent(n + 1) { - for (int i = 0; i <= n; ++i) parent[i] = i; - } - - int find(int x) { - if (x == parent[x]) return x; - return parent[x] = find(parent[x]); - } - - void occupy(int slot) { parent[slot] = find(slot - 1); } -}; - -[[noreturn]] void usage() { - std::cerr - << "Usage: please provide a list of profits and a list of deadlines\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.empty() ? std::nullopt : std::make_optional(out); -} - -int job_sequencing(std::vector& jobs) { - if (jobs.empty()) return 0; - - ranges::sort(jobs, ranges::greater{}, &Job::profit); - - const int n = static_cast(jobs.size()); - const int max_deadline = - std::min(n, ranges::max(jobs | views::transform(&Job::deadline))); - - DSU dsu(max_deadline); - int total_profit = 0; - - for (const auto& [profit, deadline] : jobs) { - int available_slot = dsu.find(std::min(deadline, max_deadline)); - - if (available_slot > 0) { - total_profit += profit; - dsu.occupy(available_slot); - } - } - - return total_profit; -} - -int main(int argc, char* argv[]) { - if (argc != 3) usage(); - - auto profits = parse_vec(argv[1]); - auto deadlines = parse_vec(argv[2]); - - if (!profits || !deadlines || profits->size() != deadlines->size()) usage(); - - std::vector jobs; - jobs.reserve(profits->size()); - ranges::transform(*profits, *deadlines, std::back_inserter(jobs), - [](int p, int d) { return Job{p, d}; }); - - std::cout << job_sequencing(jobs) << '\n'; -} -``` - -{% endraw %} - -Job Sequencing in [C++](/languages/c-plus-plus) was written by: - -- Apurva Vats -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/c-sharp/index.md b/docs/projects/job-sequencing/c-sharp/index.md deleted file mode 100644 index 019c8f9842..0000000000 --- a/docs/projects/job-sequencing/c-sharp/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- alstondsouza1 -- Ștefan-Iulian Alecu -date: 2024-11-10 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- job-sequencing -title: Job Sequencing in C# -title1: Job Sequencing -title2: in C# ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Runtime.InteropServices; - -if ( - args is not [var profitsRaw, var deadlinesRaw] - || !TryParseJobs(profitsRaw.AsSpan(), deadlinesRaw.AsSpan(), out var jobs, out int maxDeadline) -) -{ - return Usage(); -} - -Console.WriteLine(MaxProfit(jobs, maxDeadline)); -return 0; - -static bool TryParseJobs( - ReadOnlySpan profits, - ReadOnlySpan deadlines, - out List jobs, - out int maxDeadline -) -{ - jobs = new(Math.Max(profits.Count(',') + 1, 0)); - maxDeadline = 0; - - while (!profits.IsEmpty && !deadlines.IsEmpty) - { - if (!TryNext(ref profits, out int profit) || !TryNext(ref deadlines, out int deadline)) - return false; - - jobs.Add(new(profit, deadline)); - maxDeadline = Math.Max(maxDeadline, deadline); - } - - return profits.IsEmpty && deadlines.IsEmpty && jobs.Count > 0; - - static bool TryNext(ref ReadOnlySpan span, out int n) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - span = comma >= 0 ? span[(comma + 1)..] : []; - return int.TryParse(token, out n); - } -} - -static long MaxProfit(List jobs, int maxDeadline) -{ - jobs.Sort((a, b) => b.Profit.CompareTo(a.Profit)); - - int n = Math.Min(jobs.Count, maxDeadline); - - Span parent = n <= 1024 ? stackalloc int[n + 1] : new int[n + 1]; - - for (int i = 0; i <= n; i++) - parent[i] = i; - - long total = 0; - - foreach (ref readonly var j in CollectionsMarshal.AsSpan(jobs)) - { - int slot = Find(parent, Math.Min(j.Deadline, n)); - - if (slot == 0) - continue; - - total += j.Profit; - parent[slot] = Find(parent, slot - 1); - } - - return total; -} - -static int Find(Span parent, int i) -{ - while (i != parent[i]) - { - parent[i] = parent[parent[i]]; - i = parent[i]; - } - return i; -} - -static int Usage() -{ - Console.Error.WriteLine("Usage: please provide a list of profits and a list of deadlines"); - return 1; -} - -readonly record struct Job(int Profit, int Deadline); - -``` - -{% endraw %} - -Job Sequencing in [C#](/languages/c-sharp) was written by: - -- alstondsouza1 -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/c/index.md b/docs/projects/job-sequencing/c/index.md deleted file mode 100644 index 6c7e298bee..0000000000 --- a/docs/projects/job-sequencing/c/index.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-18 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- job-sequencing -title: Job Sequencing in C -title1: Job Sequencing -title2: in C ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -#define MAX_JOBS 100 - -typedef struct -{ - int profit; - int deadline; -} Job; - -int compare(const void *a, const void *b) -{ - return ((Job *)b)->profit - ((Job *)a)->profit; -} - -int min(int a, int b) -{ - return (a < b) ? a : b; -} - -int max(int a, int b) -{ - return (a > b) ? a : b; -} - -int jobSequencing(Job jobs[], int n) -{ - qsort(jobs, n, sizeof(Job), compare); - - int maxDeadline = 0; - for (int i = 0; i < n; i++) - maxDeadline = max(maxDeadline, jobs[i].deadline); - - int slot[MAX_JOBS] = {0}; - int totalProfit = 0; - - for (int i = 0; i < n; i++) - { - for (int j = min(n, jobs[i].deadline) - 1; j >= 0; j--) - { - if (slot[j] == 0) - { - slot[j] = 1; - totalProfit += jobs[i].profit; - break; - } - } - } - - return totalProfit; -} - -int *parseInput(char *input, int *size) -{ - int *arr = malloc(MAX_JOBS * sizeof(int)); - char *token = strtok(input, ", "); - *size = 0; - while (token != NULL) - { - arr[(*size)++] = atoi(token); - token = strtok(NULL, ", "); - } - return arr; -} - -int main(int argc, char *argv[]) -{ - if (argc != 3) - { - printf("Usage: please provide a list of profits and a list of " - "deadlines\n"); - return 1; - } - - int profitSize, deadlineSize; - int *profits = parseInput(argv[1], &profitSize); - int *deadlines = parseInput(argv[2], &deadlineSize); - - if (profitSize != deadlineSize) - { - printf("Usage: please provide a list of profits and a list of " - "deadlines\n"); - free(profits); - free(deadlines); - return 1; - } - - Job jobs[MAX_JOBS]; - for (int i = 0; i < profitSize; i++) - { - jobs[i].profit = profits[i]; - jobs[i].deadline = deadlines[i]; - } - - int result = jobSequencing(jobs, profitSize); - printf("%d\n", result); - - free(profits); - free(deadlines); - return 0; -} - -``` - -{% endraw %} - -Job Sequencing in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/cobol/index.md b/docs/projects/job-sequencing/cobol/index.md deleted file mode 100644 index cd75a5e0dd..0000000000 --- a/docs/projects/job-sequencing/cobol/index.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- job-sequencing -title: Job Sequencing in COBOL -title1: Job Sequencing -title2: in COBOL ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. job-sequencing. - -data division. -working-storage section. - -01 ws-inputs. - 05 ws-profits-line pic x(200). - 05 ws-deadlines-line pic x(200). - 05 ws-temp pic x(200). - -01 ws-counters. - 05 ws-profit-count pic 9(4) value 0. - 05 ws-deadline-count pic 9(4) value 0. - 05 ws-job-count pic 9(4) value 0. - 05 ws-max-deadline pic 9(4) value 0. - 05 ws-pos pic 9(4). - -01 ws-indices. - 05 ws-i pic 9(4). - 05 ws-j pic 9(4). - 05 ws-x pic 9(4). - 05 ws-y pic 9(4). - -01 ws-logic-vars. - 05 ws-max-profit pic 9(12) value 0. - 05 ws-profit-temp pic 9(9). - 05 ws-deadline-temp pic 9(9). - 05 ws-find-result pic 9(4). - 05 ws-next pic 9(4). - -01 ws-flags. - 05 ws-valid-flag pic x value "y". - 88 is-valid value "y". - 88 is-invalid value "n". - -01 ws-jobs-table. - 05 job occurs 1 to 50 times - depending on ws-job-count - descending key is job-profit. - 10 job-profit pic 9(9). - 10 job-deadline pic 9(9). - -01 ws-dsu-table. - 05 parent occurs 51 times pic 9(4). - -01 ws-display. - 05 ws-out pic -(11)9. - -procedure division. - -main. - accept ws-profits-line from argument-value - accept ws-deadlines-line from argument-value - - if ws-profits-line = spaces or ws-deadlines-line = spaces - perform show-usage - stop run - end-if - - perform parse-input - - if is-invalid - perform show-usage - stop run - end-if - - sort job on descending key job-profit. - - perform schedule-jobs-dsu - - move ws-max-profit to ws-out - display function trim(ws-out) - stop run. - - -parse-input. - set is-valid to true - - move 1 to ws-pos - perform until ws-pos > length of ws-profits-line - unstring ws-profits-line delimited by "," - into ws-profit-temp - with pointer ws-pos - end-unstring - - if ws-profit-temp not = spaces - add 1 to ws-profit-count - if ws-profit-count <= 50 - move ws-profit-temp to job-profit(ws-profit-count) - end-if - end-if - end-perform - - move 1 to ws-pos - perform until ws-pos > length of ws-deadlines-line - unstring ws-deadlines-line delimited by "," - into ws-deadline-temp - with pointer ws-pos - end-unstring - - if ws-deadline-temp not = spaces - add 1 to ws-deadline-count - if ws-deadline-count <= 50 and <= ws-profit-count - move ws-deadline-temp to job-deadline(ws-deadline-count) - if job-deadline(ws-deadline-count) > ws-max-deadline - move job-deadline(ws-deadline-count) to ws-max-deadline - end-if - end-if - end-if - end-perform - - if ws-profit-count not = ws-deadline-count or ws-profit-count = 0 - set is-invalid to true - else - move ws-profit-count to ws-job-count - end-if. - -schedule-jobs-dsu. - perform varying ws-i from 0 by 1 until ws-i > ws-max-deadline - move ws-i to parent(ws-i + 1) - end-perform - - move 0 to ws-max-profit - perform varying ws-i from 1 by 1 until ws-i > ws-job-count - move job-deadline(ws-i) to ws-x - - move ws-x to ws-y - perform until parent(ws-y + 1) = ws-y - move parent(ws-y + 1) to ws-y - end-perform - move ws-y to ws-find-result - - if ws-find-result > 0 - add job-profit(ws-i) to ws-max-profit - compute ws-next = ws-find-result - 1 - move parent(ws-next + 1) to parent(ws-find-result + 1) - end-if - end-perform. - -show-usage. - display "Usage: please provide a list of profits and a list of deadlines". -``` - -{% endraw %} - -Job Sequencing in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/commodore-basic/index.md b/docs/projects/job-sequencing/commodore-basic/index.md deleted file mode 100644 index a29ad72947..0000000000 --- a/docs/projects/job-sequencing/commodore-basic/index.md +++ /dev/null @@ -1,215 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-21 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2023-10-21 -layout: default -tags: -- commodore-basic -- job-sequencing -title: Job Sequencing in Commodore BASIC -title1: Job Sequencing in -title2: Commodore BASIC ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -15 REM Job info: -16 REM - JB(i, 0) = job index for slot i -17 REM - JB(i, 1) = profit for slot i -18 REM - JB(i, 2) = deadline for slot i -20 DIM JB(99, 2) -25 REM Slots (assumes maximum deadline is 100 or smaller -26 REM - SL(i, 0) = job index for deadline i + 1 or 0 if unoccupied -27 REM - SL(i, 1) = profit of deadline i + 1 or 0 if unoccupied -28 REM - SL(i, 2) = deadline for deadline i + 1 of 0 if unoccupied -30 DIM SL(99, 2) -35 REM Get profits -40 GOSUB 2000 -50 IF V = 0 OR C <> -1 THEN GOTO 300: REM invalid or not end of value -60 NJ = NA -70 FOR I = 0 TO NA - 1 -80 JB(I, 0) = I + 1 -90 JB(I, 1) = A(I) -100 NEXT I -110 REM Get deadlines -120 GOSUB 2000 -130 IF V = 0 OR C >= 0 THEN GOTO 300: REM invalid or not end of input/value -140 IF NA <> NJ THEN GOTO 300: REM Different number of profits and deadlines -150 FOR I = 0 TO NA - 1 -160 JB(I, 2) = A(I) -170 NEXT I -175 REM Perform job sequencing, get total profit, and display -180 GOSUB 2500 -190 GOSUB 3500 -200 S$ = STR$(TP) -210 IF TP >= 0 THEN S$ = MID$(S$, 2) -220 PRINT S$ -230 END -300 PRINT "Usage: please provide a list of profits and a list of deadlines" -310 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -2500 REM Perform job sequencing with deadlines -2501 REM Source: -2502 REM https://www.techiedelight.com/job-sequencing-problem-deadlines/ -2503 REM Inputs: -2504 REM - JB contains jobs to sort -2505 REM - NJ contains number of jobs -2506 REM Outputs: -2507 REM - SL contains slots -2508 REM - MD contains maximum deadline -2510 REM Get maximum deadline -2520 MD = 0 -2530 IF NJ < 1 THEN RETURN -2540 FOR I = 0 TO NJ - 1 -2550 IF JB(I, 2) > MD THEN MD = JB(I, 2) -2560 NEXT I -2565 REM Initialize slots -2570 FOR I = 0 TO MD - 1 -2580 FOR K = 0 TO 2 -2590 SL(I, K) = 0 -2600 NEXT K -2610 NEXT I -2615 REM Sort jobs descending by profit, then deadline -2620 GOSUB 3000 -2625 REM For each job, see if there is available slot at or before the deadline. -2626 REM If so, store this job in that slot -2630 FOR I = 0 TO NJ - 1 -2640 J = JB(I, 2) -2650 J = J - 1 -2660 IF J < 0 THEN GOTO 2710: Skip over expired deadlines -2670 IF SL(J, 0) > 0 THEN GOTO 2650: Skip over occupied slots -2680 FOR K = 0 TO 2 -2690 SL(J, K) = JB(I, K) -2700 NEXT K -2710 NEXT I -2720 RETURN -3000 REM Bubble sort jobs descending by profit, then deadline -3001 REM Inputs: -3002 REM - JB contains jobs to sort -3003 REM - NJ contains number of jobs -3004 REM Outputs: JB contains sorted jobs -3010 I = -1 -3020 I = I + 1 -3030 IF I >= (NJ - 1) THEN GOTO 3160 -3040 SW = 0: REM Indicate not swapped -3050 FOR J = I + 1 TO NJ - 1 -3060 IF JB(I, 1) >= JB(J, 1) THEN GOTO 3140 -3070 IF JB(I, 1) = JB(J, 1) AND JB(I, 2) >= JB(J, 2) THEN GOTO 3140 -3080 FOR K = 0 TO 2 -3090 T = JB(I, K) -3100 JB(I, K) = JB(J, K) -3110 JB(J, K) = T -3120 NEXT K -3130 SW = 1: REM Indicate swapped -3140 NEXT J -3150 IF SW <> 0 THEN GOTO 3020 -3160 RETURN -3500 REM Calculate total profit -3501 REM Inputs: -3502 REM - SL contains slots -3503 REM - MD contains maximum deadline -3504 REM Output: TP contains total profit -3510 TP = 0 -3520 IF MD < 1 THEN GOTO 3560 -3530 FOR I = 0 TO MD - 1 -3540 TP = TP + SL(I, 1) -3550 NEXT I -3560 RETURN - -``` - -{% endraw %} - -Job Sequencing in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/euphoria/index.md b/docs/projects/job-sequencing/euphoria/index.md deleted file mode 100644 index d64de816f4..0000000000 --- a/docs/projects/job-sequencing/euphoria/index.md +++ /dev/null @@ -1,200 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-27 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2023-02-27 -layout: default -tags: -- euphoria -- job-sequencing -title: Job Sequencing in Euphoria -title1: Job Sequencing -title2: in Euphoria ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/math.e -include std/utils.e -include std/sort.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts(STDOUT, "Usage: please provide a list of profits and a list of deadlines\n") - abort(0) -end procedure - --- Indicates for jobs -enum JOB_ID, JOB_PROFIT, JOB_DEADLINE - --- Job sequencing with deadlines --- Source: https://www.techiedelight.com/job-sequencing-problem-deadlines/ -function job_sequencing(sequence profits, sequence deadlines) - sequence jobs = {} - integer n = length(profits) - - -- Set up job details - for k = 1 to n - do - jobs &= {{k, profits[k], deadlines[k]}} - end for - - -- Get longest deadline - integer longest_deadline = max(deadlines) - - -- Initialize job slots - sequence slots = repeat({0, 0, 0}, longest_deadline) - - -- Sort jobs by profit then deadline - jobs = custom_sort(routine_id("compare_jobs"), jobs,, REVERSE_ORDER) - - -- For each job, see if there is available slot at or before the deadline. - -- If so, store this job in that slot - for i = 1 to n - do - for j = jobs[i][JOB_DEADLINE] to 1 by -1 - do - if slots[j][JOB_ID] < 1 - then - slots[j] = jobs[i] - exit - end if - end for - end for - - return slots -end function - -function compare_jobs(sequence job1, sequence job2) - -- Prioritize by profit, then deadline - return iif( - job1[JOB_PROFIT] != job2[JOB_PROFIT], - job1[JOB_PROFIT] - job2[JOB_PROFIT], - job1[JOB_DEADLINE] - job2[JOB_DEADLINE] - ) -end function - -function get_total_profit(sequence jobs) - return sum(vslice(jobs, JOB_PROFIT)) -end function - --- Check 1st and 2nd command-line argument -sequence argv = command_line() -if length(argv) < 5 or length(argv[4]) = 0 or length(argv[5]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int_list(argv[4]) -sequence profits = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] -then - usage() -end if - --- Parse 2nd command-line argument -result = parse_int_list(argv[5]) -sequence deadlines = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] or length(deadlines) != length(profits) -then - usage() -end if - --- Get job sequence -sequence job_sequence = job_sequencing(profits, deadlines) - --- Get total profit and display -integer total_profit = get_total_profit(job_sequence) -printf(STDOUT, "%d\n", total_profit) - -``` - -{% endraw %} - -Job Sequencing in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/f-sharp/index.md b/docs/projects/job-sequencing/f-sharp/index.md deleted file mode 100644 index 6448d24dee..0000000000 --- a/docs/projects/job-sequencing/f-sharp/index.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- job-sequencing -title: Job Sequencing in F# -title1: Job Sequencing -title2: in F# ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -[] -type Job = { Profit: int; Deadline: int } - - -module JobSequencing = - let rec private findAvailable (parent: int array) (x: int) = - if parent.[x] <> x then - parent.[x] <- findAvailable parent parent.[x] - - parent.[x] - - let solve (profits, deadlines) = - let jobs = - List.map2 (fun p d -> { Profit = p; Deadline = d }) profits deadlines - |> List.sortByDescending (fun j -> j.Profit) - - if List.isEmpty jobs then - 0 - else - let maxDeadline = jobs |> List.maxBy (fun j -> j.Deadline) |> _.Deadline - let slots = Array.init (maxDeadline + 1) id - - jobs - |> List.fold - (fun total job -> - let slot = findAvailable slots (min job.Deadline maxDeadline) - - if slot > 0 then - slots.[slot] <- findAvailable slots (slot - 1) - total + job.Profit - else - total) - 0 - -module Helpers = - let usage = "Usage: please provide a list of profits and a list of deadlines" - - let private (|IntList|_|) (s: string) = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) - |> Array.choose (fun p -> - match p.Trim() |> Int32.TryParse with - | true, n -> Some n - | _ -> None) - |> fun arr -> if arr.Length > 0 then Some(Array.toList arr) else None - - let parseArgs argv = - match argv with - | [| IntList p; IntList d |] when p.Length = d.Length -> Ok(p, d) - | _ -> Error usage - - let handleResults = - function - | Ok result -> - printfn "%d" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map JobSequencing.solve - |> Helpers.handleResults - -``` - -{% endraw %} - -Job Sequencing in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/go/index.md b/docs/projects/job-sequencing/go/index.md deleted file mode 100644 index b9b005b5be..0000000000 --- a/docs/projects/job-sequencing/go/index.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-03-16 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2019-03-25 -layout: default -tags: -- go -- job-sequencing -title: Job Sequencing in Go -title1: Job Sequencing -title2: in Go ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "math" - "os" - "regexp" - "strconv" -) - -type job struct { - profit int - deadline int -} - -type jobSequence []job -type jobMapping map[int]job - -func maxProfit(jobs jobSequence) int { - total := 0 - seq := iterateJobSequence(jobs, jobMapping{}) - for _, j := range seq { - total += j.profit - } - return total -} - -func iterateJobSequence(available jobSequence, complete jobMapping) jobMapping { - if len(available) <= 0 { - return complete - } - maxJob, available := available.popMax() - if i := complete.newIndex(maxJob); i >= 0 { - complete[i] = maxJob - } - return iterateJobSequence(available, complete) -} - -func (mapping jobMapping) newIndex(maxJob job) int { - var indexes []int - for i := 0; i < maxJob.deadline; i++ { - if _, ok := mapping[i]; !ok { - indexes = append(indexes, i) - } - } - if len(indexes) <= 0 { - return -1 - } - return indexes[len(indexes)-1] -} - -func (seq jobSequence) popMax() (job, jobSequence) { - max := job{math.MinInt32, math.MinInt32} - maxI := -1 - for i, v := range seq { - if v.profit > max.profit { - max = v - maxI = i - } - } - return max, append(seq[:maxI], seq[maxI+1:]...) -} - -func buildJobSequence(profits []int, deadlines []int) (jobs jobSequence) { - for i, profit := range profits { - newJob := job{profit: profit, deadline: deadlines[i]} - jobs = append(jobs, newJob) - } - return -} - -func exitWithError() { - fmt.Println("Usage: please provide a list of profits and a list of deadlines") - os.Exit(1) -} - -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - if len(list) < 2 { - exitWithError() - } - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} - -func main() { - if len(os.Args) != 3 { - exitWithError() - } - - profits := strToSliceInt(os.Args[1]) - deadlines := strToSliceInt(os.Args[2]) - if len(profits) != len(deadlines) { - exitWithError() - } - jobs := buildJobSequence(profits, deadlines) - max := maxProfit(jobs) - fmt.Println(max) - -} - -``` - -{% endraw %} - -Job Sequencing in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/haskell/index.md b/docs/projects/job-sequencing/haskell/index.md deleted file mode 100644 index abdb23e173..0000000000 --- a/docs/projects/job-sequencing/haskell/index.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -authors: -- Parker Johansen -- rzuckerm -date: 2018-11-19 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- haskell -- job-sequencing -title: Job Sequencing in Haskell -title1: Job Sequencing -title2: in Haskell ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read -import Data.Map (Map) -import qualified Data.Map as Map - -data Job = Job { profit :: Int, deadline :: Int } deriving (Show, Eq) - -instance Ord Job where - (Job p1 _) `compare` (Job p2 _) = p1 `compare` p2 - -type JobSequence = [Job] -type JobMapping = Map Int Job - --- Add up the profit of all Jobs in a JobMapping -maxProfit :: JobMapping -> Int -maxProfit = foldl (\total job -> total + profit job) 0 - --- Use greedy implementation to convert a JobSequence into a JobMapping that can be done by the deadline -iterateJobs :: JobSequence -> JobMapping -iterateJobs avail = iterate' avail Map.empty - where iterate' [] complete = complete - iterate' avail complete = - let maxJob = maximum avail - newAvail = rmJob maxJob avail - is = [i | i <- [1..(deadline maxJob)], Map.notMember i complete] - newComplete = if is /= [] - then Map.insert (maximum is) maxJob complete - else complete - in iterate' newAvail newComplete - --- Filter a specified Job from a JobSequence -rmJob :: Job -> JobSequence -> JobSequence -rmJob j js = filter (\x -> x /= j) js - --- Create a job from a tuple -job :: (Int, Int) -> Job -job (p, d) = Job p d - --- Create a JobSequence from a list of tuples -jobSequence :: [(Int, Int)] -> JobSequence -jobSequence [] = [] -jobSequence (j:js) = job j : jobSequence js - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - -tailMaybe :: [a] -> Maybe [a] -tailMaybe [] = Nothing -tailMaybe (x:xs) = Just xs - --- Takes a list of values and returns a list of strings in the format "ONE_BASED_INDEX: VALUE" -printWithIndex :: (Show a) => [a] -> [[Char]] -printWithIndex = zipWith (\i x -> (show i) ++ ": " ++ (show x)) [1..] - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - -main :: IO () -main = do - args <- getArgs - let profit = headMaybe args >>= stringToListMaybe - let deadline = tailMaybe args >>= headMaybe >>= stringToListMaybe - let groups = zip <$> profit <*> deadline - let jobs = if (maybe 0 length profit) == (maybe 0 length deadline) - then fmap (jobSequence) groups - else Nothing - case jobs of - Nothing -> putStrLn "Usage: please provide a list of profits and a list of deadlines" - Just n -> putStrLn $ show $ maxProfit $ iterateJobs n - - -``` - -{% endraw %} - -Job Sequencing in [Haskell](/languages/haskell) was written by: - -- Parker Johansen -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/index.md b/docs/projects/job-sequencing/index.md deleted file mode 100644 index a343fd7d90..0000000000 --- a/docs/projects/job-sequencing/index.md +++ /dev/null @@ -1,167 +0,0 @@ ---- -date: 2018-11-19 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- job-sequencing -title: Job Sequencing -title1: Job -title2: Sequencing ---- - - - -Welcome to the Job Sequencing page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -## Description - -Job sequencing is an optimization problem where the goal is to maximize the -profit earned by completing jobs. In this particular rendition of the problem, -jobs have both a profit and a deadline, and all jobs can be completed in the -same amount of time: - -| Job | J1 | J2 | J3 | J4 | -| -------- | --- | --- | --- | --- | -| Profit | 25 | 15 | 10 | 5 | -| Deadline | 3 | 1 | 2 | 2 | - -In this example, we have four jobs sorted by largest profit first. -Using the greedy method, we can come up with the best sequence by -choosing the job with the current highest profit and scheduling it -at the last possible moment. In this case, we would end up with the -following sequence: - -> J2, J3, J1 - -Because the last possible job we can choose has a deadline of 3, we can -only select 3 jobs at most for our sequence. As a result, we cannot -complete J4. In total, we can make a profit of 50. - -Be aware that the output sequence is not unique. There may be multiple -configurations that yield the same profit. - - -## Requirements - -In order to implement this program in your choice language, you should -define the input interface as follows: - -```console -$ ./job-sequencing.lang "25, 15, 10, 5" "3, 1, 2, 2" -``` - -In other words, the input routine should accept a list of profits and -a list of deadlines. It will be up to the program to verify that these -lists are valid. - -Once the program has determined a correct sequence, it should -output the maximum profit only. For example: - -```console -$ ./job-sequencing.lang "25, 15, 10, 5" "3, 1, 2, 2" -50 -``` - -Naturally, this is for testing -purposes as verifying all of the possible sequences would be -challenging. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Job Sequencing. -In order to keep things simple, we split up the testing as follows: - -- Sequencing Valid Tests -- Sequencing Invalid Tests - -### Sequencing Valid Tests - -| Description | Profits | Deadlines | Output | -| ----------- | ------- | --------- | ------ | -| Sample Input One | "25, 15, 10, 5" | "3, 1, 2, 2" | "50" | -| Sample Input Two | "20, 15, 10, 5, 1" | "2, 2, 1, 3, 3" | "40" | - -### Sequencing Invalid Tests - -| Description | Profits | Deadlines | -| ----------- | ------- | --------- | -| No Input | | | -| Empty Input | "" | | -| Missing Input | "25, 15, 10, 5" | | -| Lists Different Lengths | "1, 2, 3, 4" | "1, 2, 3, 4, 5" | - -All of these tests should output the following: - -``` -Usage: please provide a list of profits and a list of deadlines -``` - - -## Articles - -There are 29 articles: - -- [Job Sequencing in ALGOL 60](/projects/job-sequencing/algol60) -- [Job Sequencing in ALGOL 68](/projects/job-sequencing/algol68) -- [Job Sequencing in AWK](/projects/job-sequencing/awk) -- [Job Sequencing in Ada](/projects/job-sequencing/ada) -- [Job Sequencing in Beef](/projects/job-sequencing/beef) -- [Job Sequencing in C](/projects/job-sequencing/c) -- [Job Sequencing in C#](/projects/job-sequencing/c-sharp) -- [Job Sequencing in C++](/projects/job-sequencing/c-plus-plus) -- [Job Sequencing in COBOL](/projects/job-sequencing/cobol) -- [Job Sequencing in Commodore BASIC](/projects/job-sequencing/commodore-basic) -- [Job Sequencing in Euphoria](/projects/job-sequencing/euphoria) -- [Job Sequencing in F#](/projects/job-sequencing/f-sharp) -- [Job Sequencing in Go](/projects/job-sequencing/go) -- [Job Sequencing in Haskell](/projects/job-sequencing/haskell) -- [Job Sequencing in Java](/projects/job-sequencing/java) -- [Job Sequencing in JavaScript](/projects/job-sequencing/javascript) -- [Job Sequencing in Kotlin](/projects/job-sequencing/kotlin) -- [Job Sequencing in Mathematica](/projects/job-sequencing/mathematica) -- [Job Sequencing in PHP](/projects/job-sequencing/php) -- [Job Sequencing in Pascal](/projects/job-sequencing/pascal) -- [Job Sequencing in PowerShell](/projects/job-sequencing/powershell) -- [Job Sequencing in Python](/projects/job-sequencing/python) -- [Job Sequencing in Ruby](/projects/job-sequencing/ruby) -- [Job Sequencing in Rust](/projects/job-sequencing/rust) -- [Job Sequencing in Swift](/projects/job-sequencing/swift) -- [Job Sequencing in Tcl](/projects/job-sequencing/tcl) -- [Job Sequencing in TypeScript](/projects/job-sequencing/typescript) -- [Job Sequencing in Visual Basic](/projects/job-sequencing/visual-basic) -- [Job Sequencing in m4](/projects/job-sequencing/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/job-sequencing/java/index.md b/docs/projects/job-sequencing/java/index.md deleted file mode 100644 index b7ef8d1d6e..0000000000 --- a/docs/projects/job-sequencing/java/index.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -authors: -- JaneLiu -- Jeremy Grifski -date: 2019-10-17 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- java -- job-sequencing -title: Job Sequencing in Java -title1: Job Sequencing -title2: in Java ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -class InvalidInputException extends Exception { -} - -public class JobSequencing { - - public static class Job { - int deadline; - int profit; - - public Job(int profit, int deadline) { - this.profit = profit; - this.deadline = deadline; - } - } - - private static List createJobList(List deadlines, List profits) { - List jobs = new ArrayList<>(); - for (int i = 0; i < deadlines.size(); i++) { - jobs.add(new Job(profits.get(i), deadlines.get(i))); - } - - return jobs; - } - - public static class Sorted implements Comparator { - - public int compare(Object o1, Object o2) { - Job j1 = (Job) o1; - Job j2 = (Job) o2; - - if (j1.profit != j2.profit) { - return j2.profit - j1.profit; - } else { - return j2.deadline - j1.deadline; - } - } - } - - private static int getMaxProfit(List jobs, int size) { - int maxProfit = 0; - Sorted sorter = new Sorted(); - jobs.sort(sorter); - - TreeSet ts = new TreeSet<>(); - - for (int i = 0; i < size; i++) { - ts.add(i); - } - - for (int i = 0; i < size; i++) { - Integer x = ts.floor(jobs.get(i).deadline - 1); - - if (x != null) { - maxProfit += jobs.get(i).profit; - ts.remove(x); - } - } - return maxProfit; - } - - private static List converStringToList(String arg) { - List list = new ArrayList<>(); - if (arg.length() > 0) { - for (String p : arg.split(",")) { - list.add(Integer.parseInt(p.trim())); - } - } - return list; - } - - public static void main(String[] args) { - - try { - if (args.length < 2 || "".equals(args[0]) || "".equals(args[1])) { - throw new InvalidInputException(); - } - - List profits = converStringToList(args[0]); - List deadlines = converStringToList(args[1]); - - if (profits.size() != deadlines.size()) { - throw new InvalidInputException(); - } - - List jobs = createJobList(deadlines, profits); - System.out.println(getMaxProfit(jobs, jobs.size())); - - } catch (NumberFormatException | InvalidInputException e) { - System.err.println("Usage: please provide a list of profits and a list of deadlines"); - } - } - -} -``` - -{% endraw %} - -Job Sequencing in [Java](/languages/java) was written by: - -- JaneLiu -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/javascript/index.md b/docs/projects/job-sequencing/javascript/index.md deleted file mode 100644 index 6a7005077b..0000000000 --- a/docs/projects/job-sequencing/javascript/index.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -authors: -- rzuckerm -- Sayantan Sarkar -date: 2020-10-07 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- javascript -- job-sequencing -title: Job Sequencing in JavaScript -title1: Job Sequencing -title2: in JavaScript ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -/** - * Job Sequencing with deadlines - */ - -class Job{ - constructor(profit, deadline){ - this.profit = profit; - this.deadline = deadline; - } -} - -/* Function to create an array of Job objects */ -const createJobs = (array1, array2) => { - let addedJobs = []; - for(let index=0; index jobs.sort((a,b) => { - if(a.profit > b.profit){ - return -1; - }else if(a.profit > b.profit){ - return 1; - }else{ - return 0; - } -}); - -/* Function to find the maximum deadline to limit the total time slot */ -const findMaxDeadline = (jobs) => { - let maxDeadline = 0; - for(let index = 0; index { - let jobSlotsFull = Array(maxDeadline).fill(false); - let maxProfit = 0; - let count=0; - for(let index=0; index < jobs.length; index++){ - if(count === maxDeadline){ - break; - } - let deadline = jobs[index].deadline; - if(deadline > maxDeadline){ - continue; - } - for(let slotIndex = deadline-1; slotIndex >= 0; slotIndex--){ - if(jobSlotsFull[slotIndex] === false){ - maxProfit += jobs[index].profit; - jobSlotsFull[slotIndex] = true; - count++; - break; - } - } - } - return maxProfit; -} - -/* Function to split strings into arrays */ -const splitString = (str) => str.split(',').map(each => parseInt(each.trim(),10)); - -/* Function to check the validity of the number arrays */ -const checkValidity = (array1, array2) => { - if(array1.some(isNaN) || - array2.some(isNaN) || - array1.length != array2.length){ - throw new Error(); - } -} - -/* Function to exit in case of invalid input */ -const exit = () => { - const USAGE = "Usage: please provide a list of profits and a list of deadlines"; - console.log(USAGE); -} - -/* Main Function */ -const main = (string1, string2) => { - try{ - const array1 = splitString(string1); - const array2 = splitString(string2); - checkValidity(array1, array2); - let jobs = createJobs(array1, array2); - jobs = sortJobs(jobs); - let maxDeadline = findMaxDeadline(jobs); - console.log(findMaxProfit(jobs, maxDeadline)); - } - catch(err){ - exit(); - } -} - -main(process.argv[2], process.argv[3]); - -``` - -{% endraw %} - -Job Sequencing in [JavaScript](/languages/javascript) was written by: - -- rzuckerm -- Sayantan Sarkar - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/kotlin/index.md b/docs/projects/job-sequencing/kotlin/index.md deleted file mode 100644 index 1238546d46..0000000000 --- a/docs/projects/job-sequencing/kotlin/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Blake.Ke -- smallblack9 -date: 2020-10-08 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- job-sequencing -- kotlin -title: Job Sequencing in Kotlin -title1: Job Sequencing -title2: in Kotlin ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) { - val jobs = buildJobs(args) - if (jobs.isNullOrEmpty()) { - println("Usage: please provide a list of profits and a list of deadlines") - } else { - println(maxProfit(jobs)) - } -} - -/** - * Calculates the maximum profit of a list of jobs - */ -private fun maxProfit(jobs: List): Int { - val scheduled = hashSetOf() - var profit = 0 - jobs.sortedByDescending { it.profit }.forEach { - for (i in it.deadline downTo 1) { - if (scheduled.add(i)) { - profit += it.profit - break - } - } - } - return profit -} - -/** - * Builds job list with input arguments - */ -private fun buildJobs(args: Array): List? { - if (args.run { isNullOrEmpty() || size < 2 || any { it.isBlank() } }) return null - - val profits = args[0].toIntArray() - val deadlines = args[1].toIntArray() - - if (profits.size != deadlines.size) return null - return profits.mapIndexed { index, profit -> Job(profit, deadlines[index]) } -} - -/** - * Represents the information of a job - */ -class Job(val profit: Int, val deadline: Int) - -/** - * Extracts an array of integers from the string - */ -fun String.toIntArray() = split(",").mapNotNull { it.trim().toIntOrNull() } - -``` - -{% endraw %} - -Job Sequencing in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- smallblack9 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/m4/index.md b/docs/projects/job-sequencing/m4/index.md deleted file mode 100644 index d5bb77eff0..0000000000 --- a/docs/projects/job-sequencing/m4/index.md +++ /dev/null @@ -1,267 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-11-18 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2025-11-18 -layout: default -tags: -- job-sequencing -- m4 -title: Job Sequencing in m4 -title1: Job Sequencing -title2: in m4 ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of profits and a list of deadlines -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl 2D versions of "array_get" and "array_set" -dnl array2_get(varname, idx1, idx2) -define(`array2_get', `defn(format(``%s[%s][%s]'', `$1', `$2', `$3'))') - -dnl array2_set(varname, idx1, idx2, value) -define(`array2_set', `define(format(``%s[%s][%s]'', `$1', `$2', `$3'), `$4')') - -dnl array2_swap(varname, idx1, idx2, common_idx): -dnl t = varname[idx1][common_idx] -dnl varname[idx1][common_idx] = varname[idx2][common_idx] -dnl varname[idx2][common_idx] = t -define(`array2_swap', -`pushdef(`t', array2_get(`$1', `$2', `$4'))dnl -array2_set(`$1', `$2', `$4', array2_get(`$1', `$3', `$4'))dnl -array2_set(`$1', `$3', `$4', t)dnl -popdef(`t')'dnl -) - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl Reference: https://www.techiedelight.com/job-sequencing-problem-deadlines/ -dnl job_sequencing(profits_varname, deadlines_varname, jobs_varname, slots_varname): -dnl // Set up job details and longest deadline -dnl longest_deadline = 0 -dnl jobs_varname["length"] = profits_varname["length"] -dnl for i = 0 to profits_varname["length"] - 1: -dnl jobs_varname[i]["profit"] = profits_varname[i] -dnl jobs_varname[i]["deadline"] = deadlines_varname[i] -dnl if deadlines_varname[i] > longest_deadline: -dnl longest_deadline = deadlines_varname[i] -dnl -dnl // Initialize job slots -dnl slots_varname["length"] = longest_deadline + 1 -dnl for i = 0 to longest_deadline: -dnl slots_varname[i] = -1 -dnl -dnl // Sort jobs by profit then deadline -dnl bubble_sort(jobs_varname) -dnl -dnl // For each job, see if there is available slot at or before the deadline -dnl // if so, store this job in that slot -dnl for i = 0 to jobs_varname["length"] - 1: -dnl for j = jobs_varname[i]["deadline"] down to 1: -dnl if slots_varname[j] < 0: -dnl slots_varname[j] = i -dnl break -define(`job_sequencing', -`pushdef(`longest_deadline', 0)dnl -_set_jobs(`$1', `$2', `$3')dnl -_init_slots(`$4')dnl -bubble_sort(`$3')dnl -_set_slots(`$3', `$4', 0)dnl -popdef(`longest_deadline')dnl -'dnl -) - -dnl profits_varname=$1, deadlines_varname=$2, jobs_varname=$3 -define(`_set_jobs', -`array_set(`$3', `length', array_get(`$1', `length'))dnl -_set_jobs_inner(`$1', `$2', `$3', 0)dnl -'dnl -) - -dnl profits_varname=$1, deadlines_varname=$2, jobs_varname=$3, i=$4 -define(`_set_jobs_inner', -`ifelse(eval($4 < array_get(`$1', `length')), 1, -`array2_set(`$3', `$4', `profit', array_get(`$1', `$4'))dnl -array2_set(`$3', `$4', `deadline', array_get(`$2', `$4'))dnl -ifelse(eval(array_get(`$2', `$4') > longest_deadline), 1, -`define(`longest_deadline', array_get(`$2', `$4'))')dnl -_set_jobs_inner(`$1', `$2', `$3', incr($4))'dnl -)'dnl -) - -dnl slots_varname=$1 -define(`_init_slots', -`array_set(`$1', `length', incr(longest_deadline))dnl -_init_slots_inner(`$1', 0)dnl -'dnl -) - -dnl slots_varname=$1, i=$2 -define(`_init_slots_inner', -`ifelse(eval($2 <= longest_deadline), 1, -`array_set(`$1', `$2', -1)dnl -_init_slots_inner(`$1', incr($2))'dnl -)'dnl -) - -dnl jobs_varname=$1, slots_varname=$2, i=$3 -define(`_set_slots', -`ifelse(eval($3 < array_get(`$1', `length')), 1, -`_set_slots_inner(`$2', `$3', array2_get(`$1', `$3', `deadline'))dnl -_set_slots(`$1', `$2', incr($3))'dnl -)'dnl -) - -dnl slots_varname=$1, i=$2, j=$3 -define(`_set_slots_inner', -`ifelse(eval($3 >= 1), 1, -`ifelse(eval(array_get(`$1', `$3') < 0), 1, -`array_set(`$1', `$3', `$2')', -`_set_slots_inner(`$1', `$2', decr($3))'dnl -)'dnl -)'dnl -) - -dnl Reference: https://en.wikipedia.org/wiki/Bubble_sort#Pseudocode_implementation -dnl bubble_sort(varname): -dnl n = varname[length] -dnl do: -dnl swapped = false -dnl for i from 1 to n-1: -dnl if compare_jobs(varname, i-1, i): -dnl swap_jobs(varname, i-1, i) -dnl swapped = true -dnl while swapped -define(`bubble_sort', `ifelse(_bubble_sort_outer(`$1', 1, 0), 1, `bubble_sort(`$1')')') -define(`_bubble_sort_outer', -`ifelse(eval($2 < array_get(`$1', `length')), 0, -`$3', -`ifelse(_bubble_sort_inner(`$1', $2), 1, -`_bubble_sort_outer(`$1', incr($2), 1)', `_bubble_sort_outer(`$1', incr($2), $3)'dnl -)'dnl -)'dnl -) -define(`_bubble_sort_inner', -`ifelse(eval(compare_jobs(`$1', decr($2), `$2')), 1, -0, `swap_jobs(`$1', decr($2), $2)1'`'dnl -)'dnl -) - -dnl compare_jobs(job_varname, idx1, idx2): -dnl // Prioritize by profit, then deadline: -dnl // 0 means jobs need to be swapped, 1 otherwise -dnl return (job_varname[idx1]["profit"] > job_varname[idx2]["profit"]) or -dnl (job_varname[idx1]["profit"] == job_varname[idx2]["profit"] and -dnl job_varname[idx1]["deadline"] > job_varname[idx2]["deadline"]) -define(`compare_jobs', -`eval( - array2_get(`$1', `$2', `profit') > array2_get(`$1', `$3', `profit') || - (array2_get(`$1', `$2', `profit') == array2_get(`$1', `$3', `profit') && - array2_get(`$1', `$2', `deadline') > array2_get(`$1', `$3', `deadline')) -)'dnl -) - -dnl swap_jobs(job_varname, idx1, idx2): -dnl swap(job_varname[idx1]["profit"], job_varname[idx2]["profit"]) -dnl swap(job_varname[idx1]["deadline"], job_varname[idx2]["deadline"]) -define(`swap_jobs', -`array2_swap(`$1', `$2', `$3', `profit')dnl -array2_swap(`$1', `$2', `$3', `deadline')'dnl -) - -dnl get_total_profit(jobs_varname, slots_varname): -dnl total = 0 -dnl for i = 1 to slots_varname["length"] - 1: -dnl if slots_varname[i] >= 0: -dnl total = total + jobs_varname[slots_varname[i]]["profit"] -dnl return total -define(`get_total_profit', `_get_total_profit(`$1', `$2', 0, 1)') - -dnl jobs_varname=$1, slots_varname=$2, total=$3, i=$4 -define(`_get_total_profit', -`ifelse(eval($4 >= array_get(`$2', `length')), 1, `$3', -`ifelse(eval(array_get(`$2', `$4') >= 0), 1, -`_get_total_profit(`$1', `$2', eval($3 + array2_get(`$1', array_get(`$2', `$4'), `profit')), incr($4))', -`_get_total_profit(`$1', `$2', `$3', incr($4))'dnl -)'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval( - ARGC < 2 || - !parse_int_list(`profits', ARGV1) || - !parse_int_list(`deadlines', ARGV2) -), 1, `show_usage()')dnl -ifelse(eval( - array_get(`profits', `length') != array_get(`deadlines', `length') -), 1, `show_usage()')dnl -job_sequencing(`profits', `deadlines', `jobs', `slots')dnl -get_total_profit(`jobs', `slots') - -``` - -{% endraw %} - -Job Sequencing in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/mathematica/index.md b/docs/projects/job-sequencing/mathematica/index.md deleted file mode 100644 index dda4bd0b68..0000000000 --- a/docs/projects/job-sequencing/mathematica/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-21 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2023-01-21 -layout: default -tags: -- job-sequencing -- mathematica -title: Job Sequencing in Mathematica -title1: Job Sequencing -title2: in Mathematica ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual job scheduler which takes a Mathematica list of job tuples (value, deadline): *) - -schedule = jobs \[Function] - Total[Part[(* sum the values of the scheduled jobs *) - (* keep removing jobs until all the deadlines can be met *) - FixedPoint[ - (* remove a single job *) - l \[Function] Module[ - (* find the position 'i' of the first job that fails to meet its deadline *) - {i = SelectFirst[Range[Length[l]], # > l[[#, 2]] &]}, - If[MissingQ[i], - l,(* all deadlines are met *) - (* else, delete the lowest-value job at or before that position 'i' *) - Delete[l, First[MinimalBy[Range[i], l[[#, 1]] &]]]]], - (* sort jobs by increasing deadline *) - SortBy[jobs, job \[Function] job[[2]]]], - All, 1]]; - -(* The outer function provides the 'user interface': *) - -scheduleMain = Function[{values, deadlines}, - Module[{e = "Usage: please provide a list of profits and a list of deadlines"}, - Catch[ - schedule[ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct argument to scheduler: list of job tuples *) - Module[{ - vs = StringSplit[values, ", "], - ds = StringSplit[deadlines, ", "] - }, - If[Length[vs] == Length[ds] \[And] Length[vs] > 0, Transpose[{vs, ds}], Throw[e]]], - {-1} (* at each leaf *)]]]]]; - - -(* Valid Tests *) - -Print /@ Apply[scheduleMain] /@ { - {"25, 15, 10, 5", "3, 1, 2, 2"}, - {"20, 15, 10, 5, 1", "2, 2, 1, 3, 3"} - }; - - -(* Invalid Tests *) - -scheduleMain["", ""] -scheduleMain["25, 15, 10, 5", ""] -scheduleMain["1, 2, 3, 4", "1, 2, 3, 4, 5"] - -``` - -{% endraw %} - -Job Sequencing in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/pascal/index.md b/docs/projects/job-sequencing/pascal/index.md deleted file mode 100644 index d52cb41bf4..0000000000 --- a/docs/projects/job-sequencing/pascal/index.md +++ /dev/null @@ -1,201 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- job-sequencing -- pascal -title: Job Sequencing in Pascal -title1: Job Sequencing -title2: in Pascal ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program JobSequencing; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - Generics.Defaults, - Math, - StrUtils, - SysUtils; - -type - TJobInfo = record - JobId: integer; - Profit: integer; - Deadline: integer; - end; - TJobInfoList = specialize TList; - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of profits and a list of deadlines'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) = 0 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function CompareJobs(constref Left, Right: TJobInfo): integer; -begin - // Compare profit descending - if Left.Profit > Right.Profit then - Exit(-1) // Left should come before Right - else if Left.Profit < Right.Profit then - Exit(1); - - // If profit equal, compare deadline descending - if Left.Deadline > Right.Deadline then - Exit(-1) - else if Left.Deadline < Right.Deadline then - Exit(1); - - Exit(0); -end; - - -function JobSequencing(const Profits, Deadlines: TIntegerList): integer; -type - TJobComparer = specialize TComparer; - TBooleanArray = specialize TArray; -var - Jobs: TJobInfoList; - Job: TJobInfo; - - Slots: TBooleanArray; - - i, MaxDeadline: integer; - TotalProfit, SlotIndex: integer; -begin - Jobs := TJobInfoList.Create; - try - // Build job list - Jobs.Capacity := Profits.Count; - for i := 0 to Profits.Count - 1 do - begin - Job.JobID := i + 1; - Job.Profit := Profits[i]; - Job.Deadline := Deadlines[i]; - Jobs.Add(Job); - end; - - // Sort jobs by profit desc, deadline desc using a comparer - Jobs.Sort(TJobComparer.Construct(@CompareJobs)); - - // Find maximum deadline - MaxDeadline := MaxValue(Deadlines.ToArray); - - // Initialize slots list with False (free) - SetLength(Slots, MaxDeadline); - for i := 0 to MaxDeadline - 1 do - Slots[i] := False; - - TotalProfit := 0; - for Job in Jobs do - begin - // Find free slot at or before deadline - SlotIndex := Job.Deadline - 1; - while (SlotIndex >= 0) and Slots[SlotIndex] do - Dec(SlotIndex); - - if SlotIndex >= 0 then - begin - Slots[SlotIndex] := True; - Inc(TotalProfit, Job.Profit); - end; - end; - - Result := TotalProfit; - - finally - Jobs.Free; - end; -end; - -var - Profits, Deadlines: TIntegerList; - -begin - if ParamCount <> 2 then - ShowUsage; - - Profits := nil; - Deadlines := nil; - try - Profits := ParseIntegerList(ParamStr(1)); - Deadlines := ParseIntegerList(ParamStr(2)); - - if Profits.Count <> Deadlines.Count then - ShowUsage; - - Writeln(JobSequencing(Profits, Deadlines)); - finally - Profits.Free; - Deadlines.Free; - end; -end. - -``` - -{% endraw %} - -Job Sequencing in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/php/index.md b/docs/projects/job-sequencing/php/index.md deleted file mode 100644 index a2e6ae522c..0000000000 --- a/docs/projects/job-sequencing/php/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Kateryna Tokar -date: 2019-10-28 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- job-sequencing -- php -title: Job Sequencing in PHP -title1: Job Sequencing -title2: in PHP ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php -= 0 && $job_index < $profits_count) { - if ($jobsToDo[$job_index] == 0) { - $jobsToDo[$job_index] = $profits[$i]; - break; - } - $job_index--; - } -} - -echo array_sum($jobsToDo); - -function parse_int_array($arg) -{ - return array_map('intval', explode(',', trim($arg, ','))); -} - -function return_error() -{ - echo "Usage: please provide a list of profits and a list of deadlines\n"; - exit(); -} - -``` - -{% endraw %} - -Job Sequencing in [PHP](/languages/php) was written by: - -- Jeremy Grifski -- Kateryna Tokar - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/powershell/index.md b/docs/projects/job-sequencing/powershell/index.md deleted file mode 100644 index 4e62eaf338..0000000000 --- a/docs/projects/job-sequencing/powershell/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-16 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2025-07-16 -layout: default -tags: -- job-sequencing -- powershell -title: Job Sequencing in PowerShell -title1: Job Sequencing -title2: in PowerShell ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of profits and a list of deadlines' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -class Job { - [int]$Id - [int]$Profit - [int]$Deadline - - Job([int]$id, [int]$profit, [int]$deadline) { - $this.Id = $id - $this.Profit = $profit - $this.Deadline = $deadline - } -} - -# Source: https://www.techiedelight.com/job-sequencing-problem-deadlines/ -function Invoke-JobSequencing([array]$Profits, [array]$Deadlines) { - # Set up job details and longest deadline - $longestDeadline = ($Deadlines | Measure-Object -Maximum).Maximum - $jobs = @() - for ($i = 0; $i -lt $Profits.Length; $i++) { - $jobs += [Job]::new($i, $Profits[$i], $Deadlines[$i]) - } - - # Initialize job slots - $slots = @($null) * ($longestDeadline + 1) - - # Sort jobs by profit then deadline - $jobs = $jobs | Sort-Object -Descending -Property Profit, Deadline - - # For each job, see if there is available slot at or before the deadline - # if so, store this job in that slot - foreach ($job in $jobs) { - for ($j = $job.Deadline; $j -ge 1; $j--) { - if (-not $slots[$j]) { - $slots[$j] = $job - break - } - } - } - - $slots -} - -function Get-TotalProfit([Job[]]$jobs) { - ($jobs.Profit | Measure-Object -Sum).Sum -} - -if ($args.Length -lt 2 -or -not $args[0] -or -not $args[1]) { - Show-Usage -} - -try { - $profits = Parse-IntList $args[0] - $deadlines = Parse-IntList $args[1] - if ($profits.Length -ne $deadlines.Length) { - Show-Usage - } -} catch { - Show-Usage -} - -$jobs = Invoke-JobSequencing $profits $deadlines -Write-Output (Get-TotalProfit $jobs) - -``` - -{% endraw %} - -Job Sequencing in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/python/index.md b/docs/projects/job-sequencing/python/index.md deleted file mode 100644 index be80f46760..0000000000 --- a/docs/projects/job-sequencing/python/index.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -authors: -- Parker Johansen -- rzuckerm -date: 2018-11-19 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- job-sequencing -- python -title: Job Sequencing in Python -title1: Job Sequencing -title2: in Python ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -class Job: - def __init__(self, profit, deadline): - self.profit = profit - self.deadline = deadline - - def __eq__(self, other): - return self.__dict__ == other.__dict__ - - def __gt__(self, other): - return self.profit > other.profit - - def __lt__(self, other): - return self.profit < other.profit - - -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] - - -def max_profit(jobs): - return sum([j.profit for _, j in iterate_job_sequence(jobs).items()]) - - -def iterate_job_sequence(available, complete=None): - complete = complete or {} - if not available: - return complete - max_job = max(available) - available.remove(max_job) - index_opts = [i for i in range(0, max_job.deadline) if i not in complete] - new_index = max(index_opts) if index_opts else -1 - if new_index >= 0: - complete[new_index] = max_job - return iterate_job_sequence(available, complete) - - -def exit_with_error(): - print('Usage: please provide a list of profits and a list of deadlines') - sys.exit(1) - - -def main(args): - try: - profits = input_list(args[0]) - deadlines = input_list(args[1]) - if len(profits) != len(deadlines): - exit_with_error() - - jobs = [Job(p, d) for p, d in zip(profits, deadlines)] - print(max_profit(jobs)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Job Sequencing in [Python](/languages/python) was written by: - -- Parker Johansen -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/ruby/index.md b/docs/projects/job-sequencing/ruby/index.md deleted file mode 100644 index b198b7b3cd..0000000000 --- a/docs/projects/job-sequencing/ruby/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- job-sequencing -- ruby -title: Job Sequencing in Ruby -title1: Job Sequencing -title2: in Ruby ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = "Usage: please provide a list of profits and a list of deadlines" - -def usage! - warn USAGE - exit 1 -end - -def parse_list(str) - str.split(",").map { Integer(it.strip) } -rescue ArgumentError, NoMethodError - usage! -end - -def find(parent, x) - while parent[x] != x - parent[x] = parent[parent[x]] - x = parent[x] - end - x -end - -def schedule(profits, deadlines) - jobs = profits.zip(deadlines) - max_d = deadlines.max - - parent = (0..max_d).to_a - - total = 0 - - jobs.sort_by { -it[0] }.each do |profit, d| - slot = find(parent, [d, max_d].min) - - next if slot == 0 - - parent[slot] = slot - 1 - total += profit - end - - total -end - -profits_str, deadlines_str = ARGV -usage! if profits_str.nil? || deadlines_str.nil? || - profits_str.strip.empty? || deadlines_str.strip.empty? - -profits = parse_list(profits_str) -deadlines = parse_list(deadlines_str) - -usage! if profits.size != deadlines.size - -puts schedule(profits, deadlines) - -``` - -{% endraw %} - -Job Sequencing in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/rust/index.md b/docs/projects/job-sequencing/rust/index.md deleted file mode 100644 index 30a304833e..0000000000 --- a/docs/projects/job-sequencing/rust/index.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-15 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- job-sequencing -- rust -title: Job Sequencing in Rust -title1: Job Sequencing -title2: in Rust ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::cmp::Ordering; - -fn usage() -> ! { - println!("Usage: please provide a list of profits and a list of deadlines"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -#[derive(Debug, Ord, Eq)] -struct JobInfo { - job_id: usize, - profit: i32, - deadline: usize, -} - -impl JobInfo { - fn new(job_id: usize, profit: i32, deadline: usize) -> Self { - Self {job_id: job_id, profit: profit, deadline: deadline} - } -} - -impl PartialOrd for JobInfo { - fn partial_cmp(&self, other: &Self) -> Option { - // Reverse order of compare so that it is in descending order by profit - // then deadline - match self.profit != other.profit { - true => Some(other.profit.cmp(&self.profit)), - false => Some(other.deadline.cmp(&self.deadline)), - } - } -} - -impl PartialEq for JobInfo { - fn eq(&self, other: &Self) -> bool { - self.profit == other.profit && self.deadline == other.deadline - } -} - -// Job sequencing with deadlines -// Source: https://www.techiedelight.com/job-sequencing-problem-deadlines/ -fn job_sequencing(profits: &Vec, deadlines: &Vec) -> Vec { - // Set up job details - let mut jobs: Vec = profits.iter() - .zip(deadlines.iter()) - .enumerate() - .map(|(n, (&p, &d))| JobInfo::new(n + 1, p, d as usize)) - .collect(); - - // Get longest deadline - let longest_deadline: i32 = *deadlines.iter() - .max() - .unwrap(); - - // Initialize job slots - let mut slots: Vec = (0..longest_deadline) - .map(|_| JobInfo::new(0, 0, 0)) - .collect(); - - // Sort jobs by profit then deadline - jobs.sort(); - - // For each job, see if there is available slot at or before the deadline. - // If so, store this job in that slot - for job in jobs { - for j in (0..job.deadline).rev() { - if slots[j].job_id < 1 { - slots[j] = job; - break; - } - } - } - - slots -} - -fn get_total_profit(jobs: &Vec) -> i32 { - jobs.iter() - .map(|x| x.profit) - .sum() -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let mut profits: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 2nd command-line argument to list of integers - let mut deadlines: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if profits not same length as deadlines - if profits.len() != deadlines.len() { - usage(); - } - - // Get job sequence - let jobs = job_sequencing(&profits, &deadlines); - - // Get total profit and display - println!("{}", get_total_profit(&jobs)); -} - -``` - -{% endraw %} - -Job Sequencing in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/swift/index.md b/docs/projects/job-sequencing/swift/index.md deleted file mode 100644 index 6ac6b8b799..0000000000 --- a/docs/projects/job-sequencing/swift/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- job-sequencing -- swift -title: Job Sequencing in Swift -title1: Job Sequencing -title2: in Swift ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of profits and a list of deadlines - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func sequenceJobs(profits: [Int], deadlines: [Int]) -> Int { - let jobs = zip(profits, deadlines) - .sorted { $0.0 > $1.0 } - - guard let maxDeadline = deadlines.max() else { return 0 } - - var slots = Array(repeating: false, count: maxDeadline + 1) - var totalProfit = 0 - - for (profit, deadline) in jobs { - let limit = min(deadline, maxDeadline) - for slot in stride(from: limit, through: 1, by: -1) where !slots[slot] { - slots[slot] = true - totalProfit += profit - break - } - } - - return totalProfit -} - -func parseList(_ input: String) -> [Int]? { - let parts = - input - .split(separator: ",") - .map { $0.trimmed } - - let values = parts.compactMap(Int.init) - - guard values.count == parts.count else { return nil } - return values -} - -let args = CommandLine.arguments - -guard args.count == 3, - let profits = parseList(args[1]), - let deadlines = parseList(args[2]), - profits.count == deadlines.count -else { - print(usage) - exit(1) -} - -print(sequenceJobs(profits: profits, deadlines: deadlines)) - -``` - -{% endraw %} - -Job Sequencing in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/tcl/index.md b/docs/projects/job-sequencing/tcl/index.md deleted file mode 100644 index 9d59a8fea8..0000000000 --- a/docs/projects/job-sequencing/tcl/index.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- job-sequencing -- tcl -title: Job Sequencing in Tcl -title1: Job Sequencing -title2: in Tcl ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require math - -proc usage {} { - puts stderr {Usage: please provide a list of profits and a list of deadlines} - exit 1 -} - -proc parseList {s} { - set tokens [split [string trim $s] ","] - if {[llength $tokens] < 2} { usage } - - set result {} - foreach token $tokens { - set t [string trim $token] - if {$t eq "" || [catch {expr {int($t)}} val]} usage - lappend result $val - } - return $result -} - -proc compareJobs {a b} { - lassign $a _ aProfit aDeadline - lassign $b _ bProfit bDeadline - - expr { - ($aProfit > $bProfit) ? -1 : - ($aProfit < $bProfit) ? 1 : - ($aDeadline > $bDeadline) ? -1 : - ($aDeadline < $bDeadline) ? 1 : 0 - } - -} - -proc jobSequencing {profits deadlines} { - if {[llength $profits] != [llength $deadlines]} { usage } - - set jobs {} - for {set i 0} {$i < [llength $profits]} {incr i} { - set jobId [expr {$i + 1}] - set profit [lindex $profits $i] - set deadline [lindex $deadlines $i] - lappend jobs [list $jobId $profit $deadline] - } - - set jobs [lsort -command compareJobs $jobs] - set maxDeadline [math::max {*}$deadlines] - set slots [lrepeat $maxDeadline 0] - set totalProfit 0 - - foreach job $jobs { - lassign $job jobId profit deadline - set slotIndex [expr {$deadline - 1}] - while {$slotIndex >= 0 && [lindex $slots $slotIndex]} { - incr slotIndex -1 - } - if {$slotIndex >= 0} { - lset slots $slotIndex 1 - incr totalProfit $profit - } - } - return $totalProfit -} - -if {$argc != 2} { - usage -} - -set profits [parseList [lindex $argv 0]] -set deadlines [parseList [lindex $argv 1]] - -puts [jobSequencing $profits $deadlines] - - -``` - -{% endraw %} - -Job Sequencing in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/typescript/index.md b/docs/projects/job-sequencing/typescript/index.md deleted file mode 100644 index f5580513b0..0000000000 --- a/docs/projects/job-sequencing/typescript/index.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- job-sequencing -- typescript -title: Job Sequencing in TypeScript -title1: Job Sequencing -title2: in TypeScript ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -type Job = { profit: number; deadline: number }; - -class DSU { - parent: number[]; - - constructor(size: number) { - this.parent = Array.from({ length: size + 1 }, (_, i) => i); - } - - find(x: number): number { - if (this.parent[x] !== x) { - this.parent[x] = this.find(this.parent[x]); - } - return this.parent[x]; - } - - occupy(x: number): void { - this.parent[x] = this.find(x - 1); - } -} - -function createJobs(profits: number[], deadlines: number[]): Job[] { - return profits.map((profit, i) => ({ profit, deadline: deadlines[i] })); -} - -function sortJobs(jobs: Job[]): Job[] { - return [...jobs].sort((a, b) => b.profit - a.profit); -} - -function findMaxDeadline(jobs: Job[]): number { - return jobs.reduce((max, j) => Math.max(max, j.deadline), 0); -} - -function findMaxProfit(jobs: Job[]): number { - const maxDeadline = findMaxDeadline(jobs); - const dsu = new DSU(maxDeadline); - - let profit = 0; - - for (const job of jobs) { - const availableSlot = dsu.find(Math.min(job.deadline, maxDeadline)); - - if (availableSlot > 0) { - profit += job.profit; - dsu.occupy(availableSlot); - } - } - - return profit; -} - -function parseList(input: string): number[] { - return input - .split(",") - .map((s) => Number(s.trim())) - .filter((n) => !Number.isNaN(n)); -} - -function validate(profits: number[], deadlines: number[]): void { - if (profits.length !== deadlines.length || profits.length === 0) { - throw new Error("Invalid input"); - } -} - -function printUsage(): void { - console.error( - "Usage: please provide a list of profits and a list of deadlines", - ); - process.exit(1); -} - -function main(): void { - const [, , profitInput, deadlineInput] = process.argv; - - if (!profitInput || !deadlineInput) { - printUsage(); - } - - try { - const profits = parseList(profitInput); - const deadlines = parseList(deadlineInput); - - validate(profits, deadlines); - - const jobs = sortJobs(createJobs(profits, deadlines)); - console.log(findMaxProfit(jobs)); - } catch { - printUsage(); - } -} - -main(); - -``` - -{% endraw %} - -Job Sequencing in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/job-sequencing/visual-basic/index.md b/docs/projects/job-sequencing/visual-basic/index.md deleted file mode 100644 index 569614649f..0000000000 --- a/docs/projects/job-sequencing/visual-basic/index.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: job-sequencing-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- job-sequencing -- visual-basic -title: Job Sequencing in Visual Basic -title1: Job Sequencing -title2: in Visual Basic ---- - - - -Welcome to the [Job Sequencing](/projects/job-sequencing) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Class Job - Public Property Profit As Integer - Public Property Deadline As Integer - - Public Sub New(profit As Integer, deadline As Integer) - Me.Profit = profit - Me.Deadline = deadline - End Sub -End Class - - -Public Module JobSequencing - - Public Sub Main(args As String()) - - If args.Length <> 2 Then - Console.WriteLine("Usage: please provide a list of profits and a list of deadlines") - Return - End If - - Dim profits = ParseIntList(args(0)) - Dim deadlines = ParseIntList(args(1)) - - If profits Is Nothing OrElse deadlines Is Nothing OrElse - profits.Count <> deadlines.Count Then - - Console.WriteLine("Usage: please provide a list of profits and a list of deadlines") - Return - End If - - Dim jobs As New List(Of Job) - - For i As Integer = 0 To profits.Count - 1 - jobs.Add(New Job(profits(i), deadlines(i))) - Next - - Dim selected = GetMaxProfitJobSequence(jobs) - - Dim totalProfit As Integer = 0 - - For Each job In selected - totalProfit += job.Profit - Next - - Console.WriteLine(totalProfit) - - End Sub - - - Private Function ParseIntList(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - Return Nothing - End If - - Dim result As New List(Of Integer) - - For Each part In input.Split(","c, StringSplitOptions.RemoveEmptyEntries) - - Dim value As Integer - - If Not Integer.TryParse(part.Trim(), value) Then - Return Nothing - End If - - result.Add(value) - - Next - - Return result - - End Function - - - Public Function GetMaxProfitJobSequence(jobs As List(Of Job)) As List(Of Job) - - jobs.Sort(Function(a, b) b.Profit.CompareTo(a.Profit)) - - Dim maxDeadline As Integer = 0 - - For Each job In jobs - If job.Deadline > maxDeadline Then - maxDeadline = job.Deadline - End If - Next - - Dim timeSlots(maxDeadline - 1) As Boolean - Dim selected As New List(Of Job) - - For Each job In jobs - - For i As Integer = job.Deadline - 1 To 0 Step -1 - - If Not timeSlots(i) Then - timeSlots(i) = True - selected.Add(job) - Exit For - End If - - Next - - Next - - Return selected - - End Function - -End Module -``` - -{% endraw %} - -Job Sequencing in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/ada/index.md b/docs/projects/josephus-problem/ada/index.md deleted file mode 100644 index ea9c637d0a..0000000000 --- a/docs/projects/josephus-problem/ada/index.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-11 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- ada -- josephus-problem -title: Josephus Problem in Ada -title1: Josephus -title2: Problem in Ada ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -pragma Ada_2022; -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; - -procedure Josephus is - - subtype Population is Positive; - subtype Step_Size is Positive; - - function Survivor_Index - (Count : Population; Skip : Step_Size) return Positive - is - Result : Natural := 0; - begin - for I in 2 .. Count loop - Result := (@ + Skip) mod I; - end loop; - - return Result + 1; - end Survivor_Index; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please input the total number of people and number of people to skip."); - end Print_Usage; - -begin - if Argument_Count /= 2 then - Print_Usage; - return; - end if; - - declare - Total : constant Population := Population'Value (Argument (1)); - Skip : constant Step_Size := Step_Size'Value (Argument (2)); - begin - Put_Line (Trim (Survivor_Index (Total, Skip)'Image, Ada.Strings.Left)); - end; - -exception - when Constraint_Error => - Print_Usage; - Set_Exit_Status (Failure); -end Josephus; - -``` - -{% endraw %} - -Josephus Problem in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/algol60/index.md b/docs/projects/josephus-problem/algol60/index.md deleted file mode 100644 index 1b4c625169..0000000000 --- a/docs/projects/josephus-problem/algol60/index.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-30 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- algol60 -- josephus-problem -title: Josephus Problem in ALGOL 60 -title1: Josephus Problem -title2: in ALGOL 60 ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please input the total number of people and number of people to skip.\n"); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - null byte maps to 17 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch); - integer result, ch; - begin - boolean valid; - integer s; - - result := 0; - valid := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment Ignore characters until end of argument. Indicate invalid - if not whitespace; - ignoreloop: - if ch != -1 then - begin - if ch != 12 then valid := false; - ch := indigit; - goto ignoreloop - end; - - inValidInteger := valid - end inValidInteger; - - integer procedure mod(x, n); - value x, n; - integer x, n; - begin - mod := x - n * (x % n) - end mod; - - comment Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case; - integer procedure josephusProblem(n, k); - value n, k; - integer n, k; - begin - integer m, g; - - g := 0; - for m := 2 step 1 until n do - begin - g := mod(g + k, m) - end; - - josephusProblem := g + 1 - end josephusProblem; - - integer argc, n, k, g, ch; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 2 then usage; - - comment Get integer value from 1st argument (n). Exit if invalid; - if !inValidInteger(n, ch) then usage; - - comment Get integer value from 2nd argument (k). Exit if invalid; - if !inValidInteger(k, ch) then usage; - - comment Output Josephus Problem result; - g := josephusProblem(n, k); - outinteger(1, g); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Josephus Problem in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/algol68/index.md b/docs/projects/josephus-problem/algol68/index.md deleted file mode 100644 index 4c51749d74..0000000000 --- a/docs/projects/josephus-problem/algol68/index.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-24 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- josephus-problem -title: Josephus Problem in ALGOL 68 -title1: Josephus Problem -title2: in ALGOL 68 ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC usage = VOID: printf(($gl$, "Usage: please input the total number of people and number of people to skip.")); - -COMMENT -Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case - -Use zero-based index algorithm: - - g(1, k) = 0 - g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n - -Final answer is g(n, k) + 1 to get back to one-based index -COMMENT -PROC josephus = (INT n, INT k) INT: -( - INT g := 0; - FOR m FROM 2 TO n - DO - g := (g + k) MOD m - OD; - - g + 1 -); - -# Parse 1st and 2nd command-line arguments # -[2]INT values; -FOR m TO 2 -DO - STRING s := argv(m + 3); - PARSEINT_RESULT result := parse int(s); - - # If invalid, extra characters, exit # - values[m] := value OF result; - IF NOT (valid OF result) OR (leftover OF result) /= "" - THEN - usage; - stop - FI -OD; - -INT n := values[1]; -INT k := values[2]; -INT g := josephus(n, k); -printf(($gl$, whole(g, 0))) - -``` - -{% endraw %} - -Josephus Problem in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/awk/index.md b/docs/projects/josephus-problem/awk/index.md deleted file mode 100644 index 69a2c02ca9..0000000000 --- a/docs/projects/josephus-problem/awk/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-14 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- josephus-problem -title: Josephus Problem in AWK -title1: Josephus -title2: Problem in AWK ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please input the total number of people and number of people to skip." - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -# Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case -# -# Use zero-based index algorithm: -# -# g(1, k) = 0 -# g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n -# -# Final answer is g(n, k) + 1 to get back to one-based index -function josephus_problem(n, k, g, m) { - g = 0 - for (m = 2; m <= n; m++) { - g = (g + k) % m - } - - return g + 1 -} - -BEGIN { - if (ARGC < 3) { - usage() - } - - n = str_to_number(ARGV[1]) - k = str_to_number(ARGV[2]) - if (n == "ERROR" || k == "ERROR") { - usage() - } - - print josephus_problem(n, k) -} - -``` - -{% endraw %} - -Josephus Problem in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/beef/index.md b/docs/projects/josephus-problem/beef/index.md deleted file mode 100644 index b957e39e0d..0000000000 --- a/docs/projects/josephus-problem/beef/index.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-22 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- josephus-problem -title: Josephus Problem in Beef -title1: Josephus Problem -title2: in Beef ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace JosephusProblem; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please input the total number of people and number of people to skip."); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - // Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case - // - // Use zero-based index algorithm: - // - // g(1, k) = 0 - // g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n - // - // Final answer is g(n, k) + 1 to get back to one-based index - public static T JosephusProblem(T n, T k) - where T : IInteger, operator explicit int, operator T + T, operator T % T - where int : operator T <=> T, operator explicit T - { - T g = (T)0; - for (T m = (T)2; m <= n; m += (T)1) - { - g = (g + k) % m; - } - - return g + (T)1; - } - - public static int Main(String[] args) - { - if (args.Count < 2) - { - Usage(); - } - - int32 n = 0; - switch (ParseInt(args[0])) - { - case .Ok(out n): - case .Err: - Usage(); - } - - int32 k = 0; - switch (ParseInt(args[1])) - { - case .Ok(out k): - case .Err: - Usage(); - } - - int32 result = JosephusProblem(n, k); - Console.WriteLine(result); - return 0; - } -} - -``` - -{% endraw %} - -Josephus Problem in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/c-plus-plus/index.md b/docs/projects/josephus-problem/c-plus-plus/index.md deleted file mode 100644 index 3450bfe303..0000000000 --- a/docs/projects/josephus-problem/c-plus-plus/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- Apurva Vats -- Ștefan-Iulian Alecu -date: 2025-10-26 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- josephus-problem -title: Josephus Problem in C++ -title1: Josephus -title2: Problem in C++ ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please input the total number of people and number of " - "people to skip.\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_nonnegative_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size() && value > 0) - ? std::make_optional(value) - : std::nullopt; -} - -int josephus(int n, int k) { - int survivor = 0; - for (int i = 1; i <= n; ++i) { - survivor = (survivor + k) % i; - } - return survivor + 1; -} - -int main(int argc, char* argv[]) { - if (argc != 3) usage(); - - const auto n = to_nonnegative_int(argv[1]); - const auto k = to_nonnegative_int(argv[2]); - - if (!n || !k) usage(); - - std::cout << josephus(*n, *k) << '\n'; -} -``` - -{% endraw %} - -Josephus Problem in [C++](/languages/c-plus-plus) was written by: - -- Apurva Vats -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/c-sharp/index.md b/docs/projects/josephus-problem/c-sharp/index.md deleted file mode 100644 index b68129537a..0000000000 --- a/docs/projects/josephus-problem/c-sharp/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Ben Mojo -- Ștefan-Iulian Alecu -date: 2024-11-06 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- josephus-problem -title: Josephus Problem in C# -title1: Josephus -title2: Problem in C# ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if ( - args is not [var nText, var kText] - || !int.TryParse(nText, out int n) - || !int.TryParse(kText, out int k) - || n <= 0 - || k <= 0 -) -{ - Console.Error.WriteLine( - "Usage: please input the total number of people and number of people to skip." - ); - return; -} - -int survivor = 0; -for (int i = 2; i <= n; i++) - survivor = (survivor + k) % i; - -Console.WriteLine(survivor + 1); - -``` - -{% endraw %} - -Josephus Problem in [C#](/languages/c-sharp) was written by: - -- Ben Mojo -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/c/index.md b/docs/projects/josephus-problem/c/index.md deleted file mode 100644 index d193bb0547..0000000000 --- a/docs/projects/josephus-problem/c/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-19 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- josephus-problem -title: Josephus Problem in C -title1: Josephus -title2: Problem in C ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include - -int josephus(int n, int k) -{ - if (n == 1) - return 1; - else - return (josephus(n - 1, k) + k - 1) % n + 1; -} - -int main(int argc, char *argv[]) -{ - if (argc != 3) - { - printf("Usage: please input the total number of people and number of " - "people to skip.\n"); - return 1; - } - - char *endptr; - int n = strtol(argv[1], &endptr, 10); - if (*endptr != '\0' || n <= 0) - { - printf("Usage: please input the total number of people and number of " - "people to skip.\n"); - return 1; - } - - int k = strtol(argv[2], &endptr, 10); - if (*endptr != '\0' || k <= 0) - { - printf("Usage: please input the total number of people and number of " - "people to skip.\n"); - return 1; - } - - int result = josephus(n, k); - printf("%d\n", result); - - return 0; -} - -``` - -{% endraw %} - -Josephus Problem in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/cobol/index.md b/docs/projects/josephus-problem/cobol/index.md deleted file mode 100644 index 865755ce3c..0000000000 --- a/docs/projects/josephus-problem/cobol/index.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- josephus-problem -title: Josephus Problem in COBOL -title1: Josephus Problem -title2: in COBOL ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. josephus-problem. - -data division. -working-storage section. - -01 ws-n pic 9(9). -01 ws-k pic 9(9). - -01 ws-arg-n pic x(50). -01 ws-arg-k pic x(50). - -01 ws-survivor pic 9(9) value 0. -01 ws-i pic 9(9). - -01 ws-n-num pic 9(9) value 0. -01 ws-k-num pic 9(9) value 0. - -01 ws-valid pic x value "y". - 88 is-valid value "y". - 88 is-invalid value "n". -01 ws-out pic -(11)9. -01 ws-temp-sum pic 9(9) value 0. -01 ws-quotient pic 9(9) value 0. - -procedure division. - -main. - accept ws-arg-n from argument-value - accept ws-arg-k from argument-value - - if ws-arg-n = spaces or ws-arg-k = spaces - perform show-usage - stop run - end-if - - move function numval(ws-arg-n) to ws-n-num - move function numval(ws-arg-k) to ws-k-num - - if ws-n-num = 0 or ws-k-num = 0 - perform show-usage - stop run - end-if - - perform compute-josephus - - add 1 to ws-survivor - move ws-survivor to ws-out - display function trim(ws-out) - - stop run. - -compute-josephus. - move 0 to ws-survivor - - perform varying ws-i from 1 by 1 until ws-i > ws-n-num - add ws-survivor to ws-k-num giving ws-temp-sum - divide ws-i into ws-temp-sum giving ws-quotient remainder ws-survivor - end-perform. - -show-usage. - display "Usage: please input the total number of people and number of people to skip." -``` - -{% endraw %} - -Josephus Problem in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/commodore-basic/index.md b/docs/projects/josephus-problem/commodore-basic/index.md deleted file mode 100644 index b22db7e863..0000000000 --- a/docs/projects/josephus-problem/commodore-basic/index.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- josephus-problem -title: Josephus Problem in Commodore BASIC -title1: Josephus Problem -title2: in Commodore BASIC ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input N -10 GOSUB 1000 -20 IF V = 0 OR C <> -1 THEN GOTO 140: REM invalid or not end of value -30 N = NR -35 REM Input K -40 GOSUB 1000 -50 IF V = 0 OR C >= 0 THEN GOTO 140: REM invalid or not end character -60 K = NR -70 G = 0 -80 IF N < 2 THEN GOTO 120 -85 REM Calculate Josephus Problem using this: -86 REM https://en.wikipedia.org/wiki/Josephus_problem#The_general_case -90 FOR M = 2 TO N -100 G = G + K - INT((G + K) / M) * M -110 NEXT M -120 PRINT MID$(STR$(G + 1), 2) -130 END -140 PRINT "Usage: please input the total number of people and number of people to skip." -150 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN - -``` - -{% endraw %} - -Josephus Problem in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/euphoria/index.md b/docs/projects/josephus-problem/euphoria/index.md deleted file mode 100644 index d79acb0e7f..0000000000 --- a/docs/projects/josephus-problem/euphoria/index.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-25 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2023-02-25 -layout: default -tags: -- euphoria -- josephus-problem -title: Josephus Problem in Euphoria -title1: Josephus Problem -title2: in Euphoria ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/math.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - -procedure usage() - puts(STDOUT, "Usage: please input the total number of people and number of people to skip.\n") - abort(0) -end procedure - --- Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case --- --- Use zero-based index algorithm: --- --- g(1, k) = 0 --- g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n --- --- Final answer is g(n, k) + 1 to get back to one-based index -function josephus(integer n, integer k) - integer g = 0 - for m = 2 to n - do - g = mod(g + k, m) - end for - - return g + 1 -end function - --- Check 1st and 2nd command-line argument -sequence argv = command_line() -if length(argv) < 5 or length(argv[4]) = 0 or length(argv[5]) = 0 -then - usage() -end if - --- Parse 1st and second command-line argument -sequence arg_nums = {4, 5} -sequence values = {} -for m = 1 to 2 -do - sequence result = parse_int(argv[arg_nums[m]]) - values &= result[PARSE_INT_VALUE] - if not result[PARSE_INT_VALID] - then - usage() - end if -end for - --- Calculate Josephus problem and display -integer n = values[1] -integer k = values[2] -integer g = josephus(n, k) -printf(STDOUT, "%d\n", g) - -``` - -{% endraw %} - -Josephus Problem in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/f-sharp/index.md b/docs/projects/josephus-problem/f-sharp/index.md deleted file mode 100644 index 52c6aa1378..0000000000 --- a/docs/projects/josephus-problem/f-sharp/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- josephus-problem -title: Josephus Problem in F# -title1: Josephus -title2: Problem in F# ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Josephus = - let run (n, k) = - if n = 1 then - Ok 1 - elif k = 1 then - Ok n - elif k = 2 then - // fast formula for k = 2 - let mutable p = 1 - - while p <= n do - p <- p <<< 1 - - Ok(2 * (n - (p >>> 1)) + 1) - else - // general k > 2 using iterative approach - let mutable survivor = 0 - - for i in 2..n do - survivor <- (survivor + k) % i - - Ok(survivor + 1) - -module Helpers = - let usage = - "Usage: please input the total number of people and number of people to skip." - - let private (|Int|_|) (s: string) = - match s.Trim() |> Int32.TryParse with - | true, n -> Some n - | false, _ -> None - - let parseArgs argv = - match argv with - | [| Int n; Int k |] when n > 0 && k > 0 -> Ok(n, k) - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%d" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.bind Josephus.run |> Helpers.handleResult - -``` - -{% endraw %} - -Josephus Problem in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/go/index.md b/docs/projects/josephus-problem/go/index.md deleted file mode 100644 index fedcd30a2e..0000000000 --- a/docs/projects/josephus-problem/go/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Zia -date: 2025-02-17 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-02-17 -layout: default -tags: -- go -- josephus-problem -title: Josephus Problem in Go -title1: Josephus -title2: Problem in Go ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "os" - "strconv" -) - -func die() { - println("Usage: please input the total number of people and number of people to skip.") - os.Exit(1) -} - -func josephus(n, k int) int { - if n == 1 { - return 1 - } - - return (josephus(n-1, k)+k-1)%n + 1 -} - -func main() { - if len(os.Args) != 3 { - die() - } - - n, err := strconv.Atoi(os.Args[1]) - if err != nil { - die() - } - - k, err := strconv.Atoi(os.Args[2]) - if err != nil { - die() - } - - println(josephus(n, k)) -} - -``` - -{% endraw %} - -Josephus Problem in [Go](/languages/go) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/haskell/index.md b/docs/projects/josephus-problem/haskell/index.md deleted file mode 100644 index 11efbe12d4..0000000000 --- a/docs/projects/josephus-problem/haskell/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-11 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- haskell -- josephus-problem -title: Josephus Problem in Haskell -title1: Josephus Problem -title2: in Haskell ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Text.Read -import System.Environment - -josephus :: Int -> Int -> Int -josephus 1 _ = 1 -josephus n k = (josephus (n-1) k + k - 1) `mod` n + 1 - -parseArgs :: [String] -> Maybe (Int, Int) -parseArgs [n, k] = do - n' <- readMaybe n - k' <- readMaybe k - return (n', k') -parseArgs _ = Nothing - -main :: IO () -main = do - args <- getArgs - case parseArgs args of - Just (n, k) -> print (josephus n k) - Nothing -> putStrLn "Usage: please input the total number of people and number of people to skip." - -``` - -{% endraw %} - -Josephus Problem in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/index.md b/docs/projects/josephus-problem/index.md deleted file mode 100644 index b1ea9b2991..0000000000 --- a/docs/projects/josephus-problem/index.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -date: 2021-10-08 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- josephus-problem -title: Josephus Problem -title1: Josephus -title2: Problem ---- - - - -Welcome to the Josephus Problem page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -## Description - -There are `n` people standing in a circle waiting to be executed. The counting out begins -at some point in the circle and proceeds around the circle in a fixed direction. In each -step, a certain number of people are skipped and the next person is executed. The -elimination proceeds around the circle (which is becoming smaller and smaller as the -executed people are removed), until only the last person remains, who is given freedom. -Given the total number of persons `n` and a number `k` (the step count) which indicates -that `k-1` persons are skipped and `k`th person is killed in circle. The task is to find -out which person will survive. - -### Example - -In this example, 5 people are placed in a circle (`n = 5`), and the step count is 2 (`k = 2`). - -
-      [1]
-     /   \
-  [5]     [2]
-   |       |
-  [4]-----[3]
-
- -The count starts at person 1, and person 2 is executed: - -
-      [1]
-     /   \
-  [5]     [2] X
-   |       |
-  [4]-----[3]
-
- -The count now starts at person 3, and person 4 is executed: - -
-      [1]
-     /   \
-  [5]     [2] X
-   |       |
-X [4]-----[3]
-
- -The count now starts a person 5, and person 1 is executed: - -
-      [1] X
-     /   \
-  [5]     [2] X
-   |       |
-X [4]-----[3]
-
- -The count now starts at person 3, and person 5 is executed: - -
-      [1] X
-     /   \
-X [5]     [2] X
-   |       |
-X [4]-----[3]
-
- -At the end, person 3 is the survivor. - - -## Requirements - -Create a file called "Josephus problem" using the naming convention appropriate for your language of choice. - -Write a sample program which accepts an integer n (total number of people in the circle) and k (k-1 number of people to be skipped to kill next person) and provide the output integer of the last person alive. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Josephus Problem. -In order to keep things simple, we split up the testing as follows: - -- Josephus Problem Valid Tests -- Josephus Problem Invalid Tests - -### Josephus Problem Valid Tests - -| Description | Input (n) | Input (k) | Output | -| ----------- | --------- | --------- | ------ | -| Sample Input 5, 2 | "5" | "2" | "3" | -| Sample Input 7 3 | "7" | "3" | "4" | -| Sample Input 41 4 | "41" | "4" | "11" | - -### Josephus Problem Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A Number | "a" | -| Invalid Input: No K | "1" | - -All of these tests should output the following: - -``` -Usage: please input the total number of people and number of people to skip. -``` - - -## Articles - -There are 29 articles: - -- [Josephus Problem in ALGOL 60](/projects/josephus-problem/algol60) -- [Josephus Problem in ALGOL 68](/projects/josephus-problem/algol68) -- [Josephus Problem in AWK](/projects/josephus-problem/awk) -- [Josephus Problem in Ada](/projects/josephus-problem/ada) -- [Josephus Problem in Beef](/projects/josephus-problem/beef) -- [Josephus Problem in C](/projects/josephus-problem/c) -- [Josephus Problem in C#](/projects/josephus-problem/c-sharp) -- [Josephus Problem in C++](/projects/josephus-problem/c-plus-plus) -- [Josephus Problem in COBOL](/projects/josephus-problem/cobol) -- [Josephus Problem in Commodore BASIC](/projects/josephus-problem/commodore-basic) -- [Josephus Problem in Euphoria](/projects/josephus-problem/euphoria) -- [Josephus Problem in F#](/projects/josephus-problem/f-sharp) -- [Josephus Problem in Go](/projects/josephus-problem/go) -- [Josephus Problem in Haskell](/projects/josephus-problem/haskell) -- [Josephus Problem in Java](/projects/josephus-problem/java) -- [Josephus Problem in JavaScript](/projects/josephus-problem/javascript) -- [Josephus Problem in Mathematica](/projects/josephus-problem/mathematica) -- [Josephus Problem in PHP](/projects/josephus-problem/php) -- [Josephus Problem in Pascal](/projects/josephus-problem/pascal) -- [Josephus Problem in PowerShell](/projects/josephus-problem/powershell) -- [Josephus Problem in Python](/projects/josephus-problem/python) -- [Josephus Problem in Ruby](/projects/josephus-problem/ruby) -- [Josephus Problem in Rust](/projects/josephus-problem/rust) -- [Josephus Problem in Swift](/projects/josephus-problem/swift) -- [Josephus Problem in TI-BASIC](/projects/josephus-problem/ti-basic) -- [Josephus Problem in Tcl](/projects/josephus-problem/tcl) -- [Josephus Problem in TypeScript](/projects/josephus-problem/typescript) -- [Josephus Problem in Visual Basic](/projects/josephus-problem/visual-basic) -- [Josephus Problem in m4](/projects/josephus-problem/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/josephus-problem/java/index.md b/docs/projects/josephus-problem/java/index.md deleted file mode 100644 index 4eceb56332..0000000000 --- a/docs/projects/josephus-problem/java/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Apurva Vats -date: 2025-10-29 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-10-29 -layout: default -tags: -- java -- josephus-problem -title: Josephus Problem in Java -title1: Josephus Problem -title2: in Java ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -public class JosephusProblem { - - private static int josephus(int n, int k) { - if (n == 1) return 1; - return (josephus(n - 1, k) + k - 1) % n + 1; - } - - public static void main(String[] args) { - final String usage_msg = "Usage: please input the total number of people and number of people to skip.\n"; - - if (args.length != 2) { - System.err.print(usage_msg); - System.exit(1); - } - - int n=0, k=0; - try { - n = Integer.parseInt(args[0]); - k = Integer.parseInt(args[1]); - } catch (NumberFormatException e) { - System.err.print(usage_msg); - System.exit(1); - } - - if (n <= 0 || k <= 0) { - System.err.print(usage_msg); - System.exit(1); - } - - int result = josephus(n, k); - System.out.println(result); - } -} - -``` - -{% endraw %} - -Josephus Problem in [Java](/languages/java) was written by: - -- Apurva Vats - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/javascript/index.md b/docs/projects/josephus-problem/javascript/index.md deleted file mode 100644 index 75855e7d72..0000000000 --- a/docs/projects/josephus-problem/javascript/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Matteo Planchet -date: 2021-10-08 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2021-10-08 -layout: default -tags: -- javascript -- josephus-problem -title: Josephus Problem in JavaScript -title1: Josephus Problem -title2: in JavaScript ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const josephus = (n, k) => { - if (n == 1) return 1; - else return ((josephus(n - 1, k) + k - 1) % n) + 1; -}; - -const usage = - "Usage: please input the total number of people and number of people to skip."; - -const n = parseInt(process.argv[2]); -const k = parseInt(process.argv[3]); - -if (!n || !k || typeof n !== "number" || typeof k !== "number") { - return console.log(usage); -} - -console.log(josephus(n, k)); - -``` - -{% endraw %} - -Josephus Problem in [JavaScript](/languages/javascript) was written by: - -- Matteo Planchet - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/m4/index.md b/docs/projects/josephus-problem/m4/index.md deleted file mode 100644 index f2fcf4c469..0000000000 --- a/docs/projects/josephus-problem/m4/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-16 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-08-16 -layout: default -tags: -- josephus-problem -- m4 -title: Josephus Problem in m4 -title1: Josephus -title2: Problem in m4 ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please input the total number of people and number of people to skip. -m4exit(`1')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl josephus_problem(n, k) -dnl Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case -dnl -dnl Use zero-based index algorithm: -dnl -dnl g(1, k) = 0 -dnl g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n -dnl -dnl Final answer is g(n, k) + 1 to get back to one-based index -define(`josephus_problem', `_josephus_problem(`$1', `$2', 0, 2)') - -dnl _josephus_problem(n, k, g, m) -dnl while m <= n: -dnl g = (g + k) % m -dnl m = m + 1 -dnl Return g + 1 -define(`_josephus_problem', -`ifelse(eval(`$4' <= `$1'), 1, - `_josephus_problem(`$1', `$2', eval((`$3' + `$2') % `$4'), incr(`$4'))', - `incr(`$3')'dnl -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 2 || !is_valid(ARGV1) || !is_valid(ARGV2)), 1, - `show_usage()', `josephus_problem(ARGV1, ARGV2)') - -``` - -{% endraw %} - -Josephus Problem in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/mathematica/index.md b/docs/projects/josephus-problem/mathematica/index.md deleted file mode 100644 index 1755b3dedb..0000000000 --- a/docs/projects/josephus-problem/mathematica/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-20 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2023-01-20 -layout: default -tags: -- josephus-problem -- mathematica -title: Josephus Problem in Mathematica -title1: Josephus Problem -title2: in Mathematica ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The code is trivial: *) - -josephus[1, _] := 1 -josephus[n_Integer, k_Integer] := Mod[josephus[n - 1, k] + (k - 1), n] + 1 - -(* The outer function provides the 'user interface': *) - -josephusMain = Function[{people, skip}, - Catch[ - Module[{e = "Usage: please input the total number of people and number of people to skip."}, - josephus @@ Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - Module[{v = FromDigits[s]}, - If[Positive[v], v, Throw[e]]],(* make sure both numbers are positive *) - Throw[e]], - {people, skip}]]]]; - - -(* Valid Tests *) - -Print /@ Apply[josephusMain] /@ { - {"5", "2"}, - {"7", "3"}, - {"41", "4"} - }; - - -(* Invalid Tests *) - -josephusMain["", ""] -josephusMain["word", "word"] -josephusMain["0", "1"] - -``` - -{% endraw %} - -Josephus Problem in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/pascal/index.md b/docs/projects/josephus-problem/pascal/index.md deleted file mode 100644 index c2c0bc0652..0000000000 --- a/docs/projects/josephus-problem/pascal/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- josephus-problem -- pascal -title: Josephus Problem in Pascal -title1: Josephus Problem -title2: in Pascal ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program JosephusProblem; - -{$mode objfpc}{$H+} - -uses - Classes, - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: please input the total number of people and number of people to skip.'); - Halt(1); -end; - -function ParseInteger(const S: string; out Value: integer): boolean; -begin - Result := TryStrToInt(Trim(S), Value); -end; - -function Josephus(TotalPeople, SkipCount: integer): integer; -var - CurrentCount, HighestPowerOf2: integer; -begin - if (SkipCount < 1) or (TotalPeople < 1) then ShowUsage; - - // If skip = 1, that means that survivor is the last person - if SkipCount = 1 then - begin - Result := TotalPeople; - Exit; - end; - - if SkipCount = 2 then - begin - HighestPowerOf2 := 1; - while (HighestPowerOf2 shl 1) <= TotalPeople do - HighestPowerOf2 := HighestPowerOf2 shl 1; - - Result := 2 * (TotalPeople - HighestPowerOf2) + 1; - Exit; - end; - - Result := 0; - - for CurrentCount := 2 to TotalPeople do - Result := (Result + SkipCount) mod CurrentCount; - - Result := Result + 1; -end; - -var - TotalPeople, SkipCount: integer; -begin - if ParamCount <> 2 then - ShowUsage; - - if not ParseInteger(ParamStr(1), TotalPeople) then - ShowUsage; - if not ParseInteger(ParamStr(2), SkipCount) then - ShowUsage; - - Writeln(Josephus(TotalPeople, SkipCount)); -end. - -``` - -{% endraw %} - -Josephus Problem in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/php/index.md b/docs/projects/josephus-problem/php/index.md deleted file mode 100644 index 130daa0feb..0000000000 --- a/docs/projects/josephus-problem/php/index.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-24 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- josephus-problem -- php -title: Josephus Problem in PHP -title1: Josephus -title2: Problem in PHP ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -// Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case -// -// Use zero-based index algorithm: -// -// g(1, k) = 0 -// g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n -// -// Final answer is g(n, k) + 1 to get back to one-based index -function josephus($n, $k) -{ - $g = 0; - for ($m = 2; $m <= $n; $m++) - { - $g = ($g + $k) % $m; - } - - return $g + 1; -} - -// Exit if too few arguments -if (count($argv) < 3) -{ - usage(); -} - -// Parse arguments. Exit if invalid -$n = parse_int($argv[1]); -$k = parse_int($argv[2]); -if ($n === FALSE || $k === FALSE) -{ - usage(); -} - -// Run Josephus problem and store results -$g = josephus($n, $k); -echo "$g\n"; - -``` - -{% endraw %} - -Josephus Problem in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/powershell/index.md b/docs/projects/josephus-problem/powershell/index.md deleted file mode 100644 index 8be3ec8d11..0000000000 --- a/docs/projects/josephus-problem/powershell/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-05-20 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-05-20 -layout: default -tags: -- josephus-problem -- powershell -title: Josephus Problem in PowerShell -title1: Josephus Problem -title2: in PowerShell ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please input the total number of people and number of people to skip." - Exit 1 -} - -<# -Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case - -Use zero-based index algorithm: - - g(1, k) = 0 - g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n - -Final answer is g(n, k) + 1 to get back to one-based index -#> -function Get-JosephusProblem([int]$N, [int]$K) { - $G = 0 - for ($M = 2; $M -le $N; $M++) { - $G = ($G + $K) % $M - } - - $G + 1 -} - -if ($args.Length -lt 2) { - Show-Usage -} - -try { - $N = [int]::Parse($args[0]) - $K = [int]::Parse($args[1]) -} catch { - Show-Usage -} - -Write-Host (Get-JosephusProblem $N $K) - -``` - -{% endraw %} - -Josephus Problem in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/python/index.md b/docs/projects/josephus-problem/python/index.md deleted file mode 100644 index d181832a86..0000000000 --- a/docs/projects/josephus-problem/python/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Sriniketh J -date: 2022-12-30 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2022-12-30 -layout: default -tags: -- josephus-problem -- python -title: Josephus Problem in Python -title1: Josephus Problem -title2: in Python ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys # for receiving inputs from command line - -def josephus(n, k): # main routine - if (n == 1): - return 1 - else: - return (josephus(n - 1, k) + k-1) % n + 1 - -n, k = 0, 0 # initialising the values - -try: - n = int(sys.argv[1]) # input from CLI - k = int(sys.argv[2]) # input from CLI - -except: - print("Usage: please input the total number of people and number of people to skip.") - exit(1) - -if (n <= k): - print("Usage: please input the total number of people and number of people to skip.") - exit(1) - -print(josephus(n, k)) - -``` - -{% endraw %} - -Josephus Problem in [Python](/languages/python) was written by: - -- Sriniketh J - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/ruby/index.md b/docs/projects/josephus-problem/ruby/index.md deleted file mode 100644 index 96ab46bc4e..0000000000 --- a/docs/projects/josephus-problem/ruby/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- AAshGray -- Ștefan-Iulian Alecu -date: 2025-02-15 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- josephus-problem -- ruby -title: Josephus Problem in Ruby -title1: Josephus Problem -title2: in Ruby ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def josephus(n, k) - (1..n).reduce(0) { |acc, i| (acc + k) % i } + 1 -end - -def usage! - abort("Usage: please input the total number of people and number of people to skip.") -end - -n, k = ARGV - -usage! unless n && k -usage! unless n.match?(/\A\d+\z/) && k.match?(/\A\d+\z/) - -n = n.to_i -k = k.to_i - -puts josephus(n, k) - -``` - -{% endraw %} - -Josephus Problem in [Ruby](/languages/ruby) was written by: - -- AAshGray -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/rust/index.md b/docs/projects/josephus-problem/rust/index.md deleted file mode 100644 index b8599a919b..0000000000 --- a/docs/projects/josephus-problem/rust/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-09 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- josephus-problem -- rust -title: Josephus Problem in Rust -title1: Josephus Problem -title2: in Rust ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please input the total number of people and number of people to skip."); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -// Reference: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case -// -// Use zero-based index algorithm: -// -// g(1, k) = 0 -// g(m, k) = [g(m - 1, k) + k] MOD m, for m = 2, 3, ..., n -// -// Final answer is g(n, k) + 1 to get back to one-based index -fn josephus(n: i32, k: i32) -> i32 { - let mut g: i32 = 0; - for m in 2..=n { - g = (g + k) % m; - } - - g + 1 -} - -fn main() { - let mut args = args().skip(1); - - // Exit if 1st command-line argument not an integer - let mut n: i32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if 2nd command-line argument not an integer - let mut k: i32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Run Josephus problem and store results - println!("{}", josephus(n, k)); -} - -``` - -{% endraw %} - -Josephus Problem in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/swift/index.md b/docs/projects/josephus-problem/swift/index.md deleted file mode 100644 index de4cd47b67..0000000000 --- a/docs/projects/josephus-problem/swift/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- josephus-problem -- swift -title: Josephus Problem in Swift -title1: Josephus Problem -title2: in Swift ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = "Usage: please input the total number of people and number of people to skip." - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -extension Array { - func argument(at index: Int) -> Element? { - indices.contains(index) ? self[index] : nil - } -} - -func solveJosephus(_ n: Int, _ k: Int) -> Int { - guard n > 0 else { return 0 } - - if k == 2 { - let mostSignificantBit = 1 << (Int.bitWidth - 1 - n.leadingZeroBitCount) - return 2 * (n - mostSignificantBit) + 1 - } - - return (2...n).reduce(0) { (survivor, i) in - (survivor + k) % i - } + 1 -} - -func parseInput(from args: [String]) -> (n: Int, k: Int)? { - guard let rawN = args.argument(at: 1), - let rawK = args.argument(at: 2), - let n = Int(rawN.trimmed), - let k = Int(rawK.trimmed), - n > 0, k > 0 - else { return nil } - - return (n, k) -} - -guard let (n, k) = parseInput(from: CommandLine.arguments) else { - print(usage) - exit(1) -} - -print(solveJosephus(n, k)) - -``` - -{% endraw %} - -Josephus Problem in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/tcl/index.md b/docs/projects/josephus-problem/tcl/index.md deleted file mode 100644 index 85453c7518..0000000000 --- a/docs/projects/josephus-problem/tcl/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- josephus-problem -- tcl -title: Josephus Problem in Tcl -title1: Josephus -title2: Problem in Tcl ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please input the total number of people and number of people to skip.} - exit 1 -} - -proc parseInt {s} { - set s [string trim $s] - if {[string is integer -strict $s]} { return $s } - usage -} - -proc josephus {total skip} { - if {$skip < 1 || $total < 1} { usage } - - # If skip = 1, survivor is the last person - if {$skip == 1} { return $total } - - # Optimized case for skip = 2 - if {$skip == 2} { - set power 1 - while {($power << 1) <= $total} { - set power [expr {$power << 1}] - } - return [expr {2 * ($total - $power) + 1}] - } - - set result 0 - for {set i 2} {$i <= $total} {incr i} { - set result [expr {($result + $skip) % $i}] - } - - return [expr {$result + 1}] -} - -if {$argc != 2} { usage } - -set total [parseInt [lindex $argv 0]] -set skip [parseInt [lindex $argv 1]] - -puts [josephus $total $skip] - -``` - -{% endraw %} - -Josephus Problem in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/ti-basic/index.md b/docs/projects/josephus-problem/ti-basic/index.md deleted file mode 100644 index f913e7b7fb..0000000000 --- a/docs/projects/josephus-problem/ti-basic/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-03 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2025-02-03 -layout: default -tags: -- josephus-problem -- ti-basic -title: Josephus Problem in TI-BASIC -title1: Josephus Problem -title2: in TI-BASIC ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -"0123456789"->Str2 -2->dim(l1) -1->M -0->E -While E=0 and M<=2 - Input "",Str1 - length(Str1)->L - L<1->E - 0->D - 0->V - 1->N - 1->S - While E=0 and N<=L - sub(Str1,N,1)->C - inString(Str2,C)-1->K - If C="+" or C="-" - Then - D>0->E - If C="-" - Then 0-S->S - End - Else - K<0->E - D+1->D - V*10+K*S->V - End - N+1->N - End - E or D<1->E - V->l1(M) - M+1->M -End -If E Then Disp "Usage: please input the total number of people and number of people to skip." -Else - :"Source: https://en.wikipedia.org/wiki/Josephus_problem#The_general_case" - 0->G - l1(1)->N - l1(2)->K - For(M,2,N) - remainder(G+K,M)->G - End - Disp G+1 -End - -``` - -{% endraw %} - -Josephus Problem in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/typescript/index.md b/docs/projects/josephus-problem/typescript/index.md deleted file mode 100644 index d636de3c3d..0000000000 --- a/docs/projects/josephus-problem/typescript/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- josephus-problem -- typescript -title: Josephus Problem in TypeScript -title1: Josephus Problem -title2: in TypeScript ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function printUsage(): void { - console.error( - "Usage: please input the total number of people and number of people to skip.", - ); - process.exit(1); -} - -function josephus(n: number, k: number): number { - if (n === 1) return 1; - return ((josephus(n - 1, k) + k - 1) % n) + 1; -} - -function main(): void { - const n = Number.parseInt(process.argv[2], 10); - const k = Number.parseInt(process.argv[3], 10); - - if (Number.isNaN(n) || Number.isNaN(k) || n <= 0 || k <= 0) { - printUsage(); - } - - console.log(josephus(n, k).toString()); -} - -main(); - -``` - -{% endraw %} - -Josephus Problem in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/josephus-problem/visual-basic/index.md b/docs/projects/josephus-problem/visual-basic/index.md deleted file mode 100644 index c80623b0ed..0000000000 --- a/docs/projects/josephus-problem/visual-basic/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: josephus-problem-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- josephus-problem -- visual-basic -title: Josephus Problem in Visual Basic -title1: Josephus Problem -title2: in Visual Basic ---- - - - -Welcome to the [Josephus Problem](/projects/josephus-problem) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Module JosephusProblem - - Public Sub Main(args As String()) - - If args.Length < 2 Then - Console.WriteLine("Usage: please input the total number of people and number of people to skip.") - Return - End If - - Dim n As Integer - Dim k As Integer - - If Not Integer.TryParse(args(0), n) OrElse - Not Integer.TryParse(args(1), k) OrElse - n <= 0 OrElse k <= 0 Then - - Console.WriteLine("Usage: please input the total number of people and number of people to skip.") - Return - End If - - Dim survivor As Integer = Josephus(n, k) - - Console.WriteLine(survivor) - - End Sub - - - Private Function Josephus(n As Integer, k As Integer) As Integer - - Dim result As Integer = 0 - - For m As Integer = 2 To n - result = (result + k) Mod m - Next - - Return result + 1 - - End Function - -End Module -``` - -{% endraw %} - -Josephus Problem in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/ada/index.md b/docs/projects/linear-search/ada/index.md deleted file mode 100644 index 600fe9469e..0000000000 --- a/docs/projects/linear-search/ada/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-11 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- ada -- linear-search -title: Linear Search in Ada -title1: Linear Search -title2: in Ada ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Strings.Maps; use Ada.Strings.Maps; -with Ada.Containers.Vectors; - -procedure Linear_Search is - - Data_Format_Error : exception; - - function Clean (S : String) return String - is (Trim (S, Ada.Strings.Both)); - - function To_Int (S : String) return Integer is - Cleaned : constant String := Clean (S); - begin - return Integer'Value (Cleaned); - exception - when Constraint_Error => - raise Data_Format_Error with "Invalid integer: '" & Cleaned & "'"; - end To_Int; - - package Integer_Vectors is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - subtype Int_List is Integer_Vectors.Vector; - - function Found (Within : Int_List; Item : Integer) return Boolean is - use Integer_Vectors; - begin - return Within.Find (Item) /= No_Element; - end Found; - - function To_Int_List (Raw_String : String) return Int_List is - Result : Int_List; - Start : Positive := Raw_String'First; - Finish : Natural; - Seps : constant Character_Set := To_Set (", "); - begin - while Start <= Raw_String'Last loop - Find_Token - (Raw_String, Seps, Start, Ada.Strings.Outside, Start, Finish); - - exit when Start > Finish; - - Result.Append (To_Int (Raw_String (Start .. Finish))); - - Start := Finish + 1; - end loop; - - if Result.Is_Empty then - raise Data_Format_Error with "List is empty"; - end if; - - return Result; - end To_Int_List; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide a list of integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")"); - end Print_Usage; - -begin - if Argument_Count /= 2 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - begin - declare - Haystack : constant Int_List := To_Int_List (Argument (1)); - Needle : constant Integer := To_Int (Argument (2)); - begin - Put_Line (if Found (Haystack, Needle) then "true" else "false"); - end; - exception - when Data_Format_Error | Constraint_Error => - Print_Usage; - Set_Exit_Status (Failure); - end; - -end Linear_Search; - -``` - -{% endraw %} - -Linear Search in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/algol60/index.md b/docs/projects/linear-search/algol60/index.md deleted file mode 100644 index 73db820b57..0000000000 --- a/docs/projects/linear-search/algol60/index.md +++ /dev/null @@ -1,232 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-17 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-04-17 -layout: default -tags: -- algol60 -- linear-search -title: Linear Search in ALGOL 60 -title1: Linear Search -title2: in ALGOL 60 ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") " - "and the integer to find (\"11\")\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - integer procedure linearSearch(arr, arrLen, target); - value arrLen, target; - integer array arr; - integer arrLen, target; - begin - integer idx, i; - - idx := -1; - i := 1; - searchloop: - if i <= arrLen then - begin - if arr[i] = target then idx := i - else - begin - i := i + 1; - goto searchloop - end - end; - - linearSearch := idx - end linearSearch; - - integer argc, arrLen, ch, target, idx; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 2 then usage; - - comment Get list input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 1 then usage; - - comment Get target value from 2nd argument. Exit if invalid; - if !inValidInteger(target, ch, false) then usage; - - comment Linear search for target value in list. Indicate if found; - idx := linearSearch(arr, arrLen, target); - if idx > 0 then outstring(1, "true\n") - else outstring(1, "false\n") -end - -``` - -{% endraw %} - -Linear Search in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/algol68/index.md b/docs/projects/linear-search/algol68/index.md deleted file mode 100644 index 489e9fe92f..0000000000 --- a/docs/projects/linear-search/algol68/index.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-30 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-01-30 -layout: default -tags: -- algol68 -- linear-search -title: Linear Search in ALGOL 68 -title1: Linear Search -title2: in ALGOL 68 ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a list of integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")")) -); - -PROC linear search = (INT target, REF []INT values) INT: -( - INT found := 0; - FOR k TO UPB values - WHILE found = 0 - DO - IF values[k] = target - THEN - found := k - FI - OD; - - found -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result -THEN - usage; - stop -FI; - -# Parse 2nd command-line argument # -s := argv(5); -PARSEINT_RESULT result := parse int(s); -INT target := value OF result; -IF NOT valid OF result OR leftover OF result /= "" -THEN - usage; - stop -FI; - -# Do linear search and show results # -INT index = linear search(target, values); -printf(($gl$, (index > 0 | "true" | "false"))) - -``` - -{% endraw %} - -Linear Search in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/awk/index.md b/docs/projects/linear-search/awk/index.md deleted file mode 100644 index d42577d48b..0000000000 --- a/docs/projects/linear-search/awk/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-07 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- linear-search -title: Linear Search in AWK -title1: Linear Search -title2: in AWK ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -function linear_search(arr, target, result, idx) { - result = 0 - for (idx in arr) { - if (arr[idx] == target) { - result = idx - break - } - } - - return result -} - -BEGIN { - if (ARGC < 3) { - usage() - } - - str_to_array(ARGV[1], arr) - target = str_to_number(ARGV[2]) - if (!length(arr) || arr[1] == "ERROR" || target == "ERROR") { - usage() - } - - idx = linear_search(arr, target) - print (idx > 0) ? "true" : "false" -} - -``` - -{% endraw %} - -Linear Search in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/beef/index.md b/docs/projects/linear-search/beef/index.md deleted file mode 100644 index e2d23002a8..0000000000 --- a/docs/projects/linear-search/beef/index.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-03 -featured-image: linear-search-in-every-language.jpg -last-modified: 2024-02-03 -layout: default -tags: -- beef -- linear-search -title: Linear Search in Beef -title1: Linear Search -title2: in Beef ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace LinearSearch; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11") - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - public static int LinearSearch(List arr, T target) - { - return arr.IndexOf(target); - } - - public static int Main(String[] args) - { - if (args.Count < 2) - { - Usage(); - } - - List arr = scope .(); - if (ParseIntList(args[0], arr) case .Err) - { - Usage(); - } - - int32 target = ?; - switch (ParseInt(args[1])) - { - case .Ok(out target): - case .Err: - Usage(); - } - - int index = LinearSearch(arr, target); - Console.WriteLine(index >= 0 ? "true" : "false"); - - return 0; - } -} - -``` - -{% endraw %} - -Linear Search in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/c-plus-plus/index.md b/docs/projects/linear-search/c-plus-plus/index.md deleted file mode 100644 index 8c133f17ad..0000000000 --- a/docs/projects/linear-search/c-plus-plus/index.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Vipin Yadav -- Ștefan-Iulian Alecu -date: 2022-10-03 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- linear-search -title: Linear Search in C++ -title1: Linear Search -title2: in C++ ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11"))" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.empty() ? std::nullopt : std::make_optional(out); -} - -int main(int argc, char* argv[]) { - if (argc != 3) usage(); - - const auto haystack = parse_vec(argv[1]); - const auto needle = to_int(argv[2]); - - if (!haystack || !needle) usage(); - - std::cout << std::boolalpha - << (ranges::find(*haystack, *needle) != haystack->end()) << '\n'; -} -``` - -{% endraw %} - -Linear Search in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Vipin Yadav -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/c-sharp/index.md b/docs/projects/linear-search/c-sharp/index.md deleted file mode 100644 index 09da43d21b..0000000000 --- a/docs/projects/linear-search/c-sharp/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2024-10-29 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- linear-search -title: Linear Search in C# -title1: Linear -title2: Search in C# ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if ( - args is not [var input, var targetRaw] - || !int.TryParse(targetRaw, out int target) - || !TryParseList(input.AsSpan(), out var numbers) -) - return Usage(); - -Console.WriteLine(numbers.Contains(target)); -return 0; - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return numbers.Count > 0; -} - -static int Usage() -{ - Console.WriteLine( - """Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")""" - ); - return 1; -} - -``` - -{% endraw %} - -Linear Search in [C#](/languages/c-sharp) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/c/index.md b/docs/projects/linear-search/c/index.md deleted file mode 100644 index 49ac046c2b..0000000000 --- a/docs/projects/linear-search/c/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-21 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- linear-search -title: Linear Search in C -title1: Linear -title2: Search in C ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include - -bool linear_search(int *arr, int size, int target) -{ - for (int i = 0; i < size; i++) - if (arr[i] == target) - return true; - return false; -} - -int *parse_array(char *input, int *size) -{ - int *arr = NULL; - *size = 0; - char *token = strtok(input, ", "); - while (token != NULL) - { - arr = realloc(arr, (*size + 1) * sizeof(int)); - arr[*size] = atoi(token); - (*size)++; - token = strtok(NULL, ", "); - } - return arr; -} - -int main(int argc, char *argv[]) -{ - if (argc != 3) - { - printf("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") " - "and the integer to find (\"11\")\n"); - return 1; - } - - int size; - int *arr = parse_array(argv[1], &size); - int target = atoi(argv[2]); - - if (size == 0) - { - printf("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") " - "and the integer to find (\"11\")\n"); - free(arr); - return 1; - } - - bool result = linear_search(arr, size, target); - printf("%s\n", result ? "true" : "false"); - - free(arr); - return 0; -} - -``` - -{% endraw %} - -Linear Search in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/cobol/index.md b/docs/projects/linear-search/cobol/index.md deleted file mode 100644 index f7ced2782f..0000000000 --- a/docs/projects/linear-search/cobol/index.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-19 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-04-19 -layout: default -tags: -- cobol -- linear-search -title: Linear Search in COBOL -title1: Linear Search -title2: in COBOL ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. linear-search. - -data division. -working-storage section. - -01 MAX-ENTRIES constant as 100. -01 argc binary-long. -01 list-string pic x(1100). -01 target-string pic x(20). -01 ws-token pic x(20). -01 ws-ptr binary-long. -01 num-count binary-long value 0. -01 num-list. - 05 num pic s9(9) - occurs 1 to MAX-ENTRIES - depending on num-count - indexed by num-idx. -01 target-number pic s9(9). -01 search-state pic x value 'F'. - 88 item-found value 'T'. - 88 item-not-found value 'F'. - -procedure division. - -main. - perform validate-args - perform parse-and-validate-input - perform linear-search - - if item-found - display "true" - else - display "false" - end-if - goback. - -validate-args. - accept argc from argument-number - - if argc <> 2 - perform display-usage - end-if - - accept list-string from argument-value - accept target-string from argument-value - - if list-string = spaces or target-string = spaces - perform display-usage - end-if - - if function test-numval(target-string) <> 0 - perform display-usage - end-if - - move function numval(target-string) to target-number. - -parse-and-validate-input. - move 1 to ws-ptr - perform until ws-ptr > length of list-string - or list-string(ws-ptr:) = spaces - - move spaces to ws-token - unstring list-string - delimited by all "," - into ws-token - with pointer ws-ptr - end-unstring - - if ws-token <> spaces - if function test-numval(ws-token) <> 0 - perform display-usage - end-if - - add 1 to num-count - if num-count > MAX-ENTRIES - perform display-usage - end-if - - move function numval(ws-token) to num(num-count) - end-if - end-perform - - if num-count = 0 - perform display-usage - end-if. - -linear-search. - set item-not-found to true - search num - when num(num-idx) = target-number - set item-found to true - end-search. - -display-usage. - display 'Usage: please provide a list of integers ' - '("1, 4, 5, 11, 12") and the integer to find ("11")' - stop run. - -``` - -{% endraw %} - -Linear Search in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/commodore-basic/index.md b/docs/projects/linear-search/commodore-basic/index.md deleted file mode 100644 index bedc232aa3..0000000000 --- a/docs/projects/linear-search/commodore-basic/index.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-07 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-10-15 -layout: default -tags: -- commodore-basic -- linear-search -title: Linear Search in Commodore BASIC -title1: Linear Search in -title2: Commodore BASIC ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -20 GOSUB 2000: REM Get array -30 IF V = 0 OR C <> -1 THEN GOTO 200: REM invalid or end of input/value -40 GOSUB 1000: REM Get target value -50 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -55 REM Perform linear search -60 T = NR -70 GOSUB 3000 -80 R$ = "false" -90 IF I >= 0 THEN R$ = "true" -100 PRINT R$ -110 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide a list of integers "; -220 PRINT "("; Q$; "1, 4, 5, 11, 12"; Q$; ") and the integer to find "; -230 PRINT "("; Q$; "11"; Q$; ")" -240 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Linear search -3001 REM Inputs: -3002 REM - A contains array to search -3003 REM - NA contains size of array -3004 REM - T contains item to find -3005 REM Outputs: I contains index of array item found, -1 if not found -3010 I = -1 -3020 I = I + 1 -3030 IF I >= NA THEN I = -1: RETURN: REM not found -3040 IF A(I) = T THEN RETURN: REM found -3050 GOTO 3020 - -``` - -{% endraw %} - -Linear Search in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/elvish/index.md b/docs/projects/linear-search/elvish/index.md deleted file mode 100644 index 9caec42d38..0000000000 --- a/docs/projects/linear-search/elvish/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-15 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-01-15 -layout: default -tags: -- elvish -- linear-search -title: Linear Search in Elvish -title1: Linear Search -title2: in Elvish ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -use str - -fn die { - echo 'Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")' - exit 1 -} - -fn validate-num {|n| - try { - var _ = (+ 4 $n) - } catch _ { - die - } -} - -if (> 2 (count $args)) { - die -} - -var list = [(str:split ', ' $args[0])] -for i $list { - validate-num $i -} - -var key = $args[1] -validate-num $key - -for i $list { - if (== $i $key) { - echo true - exit - } -} - -echo false - -``` - -{% endraw %} - -Linear Search in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/euphoria/index.md b/docs/projects/linear-search/euphoria/index.md deleted file mode 100644 index f3f5ef91b1..0000000000 --- a/docs/projects/linear-search/euphoria/index.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- linear-search -title: Linear Search in Euphoria -title1: Linear Search -title2: in Euphoria ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n" - ) - abort(0) -end procedure - --- Check command-line arguments -sequence argv = command_line() -if length(argv) < 5 or length(argv[4]) = 0 or length(argv[5]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence list_result = parse_int_list(argv[4]) -sequence values = list_result[PARSE_INT_LIST_VALUES] -if not list_result[PARSE_INT_LIST_VALID] -then - usage() -end if - --- Parse 2nd command-line argument -sequence result = parse_int(argv[5]) -integer target = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] -then - usage() -end if - --- Use built-in linear search and show results -integer index = find(target, values) -if index > 0 -then - puts(STDOUT, "true\n") -else - puts(STDOUT, "false\n") -end if - -``` - -{% endraw %} - -Linear Search in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/f-sharp/index.md b/docs/projects/linear-search/f-sharp/index.md deleted file mode 100644 index 023740e8c7..0000000000 --- a/docs/projects/linear-search/f-sharp/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- linear-search -title: Linear Search in F# -title1: Linear -title2: Search in F# ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module LinearSearch = - let run (numbers: 'a list, target: 'a) = - numbers - |> List.exists ((=) target) - |> Ok - - -module Helpers = - let usage = - "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")" - - let private (|Int|_|) (s: string) = - match s.Trim() |> Int32.TryParse with - | true, n -> Some n - | _ -> None - - let private (|IntList|_|) (s: string) = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) - |> Array.toList - |> List.choose (fun x -> - match x.Trim() with - | Int n -> Some n - | _ -> None) - |> function - | [] -> None - | xs -> Some xs - - - let parseArgs argv = - match argv with - | [| IntList numbers; Int target |] -> Ok(numbers, target) - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%b" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.bind LinearSearch.run - |> Helpers.handleResult - -``` - -{% endraw %} - -Linear Search in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/fortran/index.md b/docs/projects/linear-search/fortran/index.md deleted file mode 100644 index 53de41d2de..0000000000 --- a/docs/projects/linear-search/fortran/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- leoraggy -date: 2025-10-28 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-10-28 -layout: default -tags: -- fortran -- linear-search -title: Linear Search in Fortran -title1: Linear Search -title2: in Fortran ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -Program linearsearch - implicit none - - character(len=256) :: input1 - character(len=10) :: input2 - integer :: key - integer, dimension(5) :: array - logical :: searched - integer :: io_status - - if(command_argument_count() < 2) call usage() - - call get_command_argument(1, input1) - call get_command_argument(2,input2) - - if(input1 == "") call usage() - - read(unit=input1, fmt=*, iostat=io_status) array - read(unit=input2, fmt=*, iostat=io_status) key - - searched = exists(array,key) - - if (searched) then - print '(a)', 'true' - else - print '(a)', 'false' - end if - - contains - - pure function exists(array, key) result(answer) - implicit none - INTEGER :: i - integer, intent(in) :: key - integer, intent(in) :: array(:) - logical :: answer - - answer = .false. - - do i = 1, size(array), 1 - if(array(i) == key) then - answer = .true. - return - end if - end do - - end function exists - -subroutine usage() - write(*,'(a)') "Usage: please provide a list of integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")" - stop -end subroutine usage - -End Program linearsearch -``` - -{% endraw %} - -Linear Search in [Fortran](/languages/fortran) was written by: - -- leoraggy - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/go/index.md b/docs/projects/linear-search/go/index.md deleted file mode 100644 index 9aea4f0965..0000000000 --- a/docs/projects/linear-search/go/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2024-10-08 -featured-image: linear-search-in-every-language.jpg -last-modified: 2024-10-08 -layout: default -tags: -- go -- linear-search -title: Linear Search in Go -title1: Linear -title2: Search in Go ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" - "strings" -) - -func linearSearch(list []int, keyToSearch int) bool { - for _, number := range list { - if number == keyToSearch { - return true - } - } - return false -} - -func main() { - if len(os.Args) < 3 { - fmt.Println("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")") - return - } - - numberString := os.Args[1] - keyToSearchStr := os.Args[2] - keyToSearch, err := strconv.Atoi(keyToSearchStr) - if err != nil { - fmt.Println("Usage: please provide a valid integer to find.") - return - } - numberArray := strings.Split(numberString, ",") - var listOfNumbers []int - - for _, numStr := range numberArray { - numStr = strings.TrimSpace(numStr) - number, err := strconv.Atoi(numStr) - if err == nil { - listOfNumbers = append(listOfNumbers, number) - } - } - if len(listOfNumbers) > 0 { - searched := linearSearch(listOfNumbers, keyToSearch) - fmt.Println(searched) - } else { - fmt.Println("Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")") - } -} - -``` - -{% endraw %} - -Linear Search in [Go](/languages/go) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/haskell/index.md b/docs/projects/linear-search/haskell/index.md deleted file mode 100644 index 3a8126412b..0000000000 --- a/docs/projects/linear-search/haskell/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-04-29 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-04-29 -layout: default -tags: -- haskell -- linear-search -title: Linear Search in Haskell -title1: Linear Search -title2: in Haskell ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - --- Ensure that a list is not empty -verifyListLength :: [a] -> Maybe [a] -verifyListLength [] = Nothing -verifyListLength xs = Just xs - -usage :: String -usage = "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")" - -main :: IO () -main = do - args <- getArgs - case args of - [xs, key] -> do - let xs' = stringToListMaybe xs >>= verifyListLength - let key' = readMaybe key - case elem <$> key' <*> xs' of - Just res -> putStrLn (if res then "true" else "false") - Nothing -> putStrLn usage - _ -> putStrLn usage - -``` - -{% endraw %} - -Linear Search in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/index.md b/docs/projects/linear-search/index.md deleted file mode 100644 index ed325b5d34..0000000000 --- a/docs/projects/linear-search/index.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -date: 2019-10-17 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- linear-search -title: Linear Search -title1: Linear -title2: Search ---- - - - -Welcome to the Linear Search page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Linear search is quite intuitive, it is basically searching an element in an array by traversing -the array from the beginning to the end and comparing each item in the array with the key. If a -particular array entry matches with the key the position is recorded and the loop is stopped. -The algorithm for this is: - -1. Define a flag (set it's value to 0) for checking if key is present in array or notation. -2. Iterate through every element in array. -3. In each iteration compare the key and the current element. -4. If they match set the flag to 1, position to the current iteration and break from the loop. -5. If entire loop is traversed and the element is not found the value of flag will be 0 and user -can notified that key is not in array. - -### Performance - -The performance of searching algorithms is generally defined in "Big O notation". -If you are not familiar with such notations, please refer to the relevant -article by [Rob Bell][1] or the [Wikipedia][2] entry listed in further readings below. - -| Cases | Big O Notatation | -| ------------ | ---------------- | -| Best case | O(1) | -| Average case | O(n) | -| Worst case | O(n) | - -Linear search is not efficient for large arrays, but for relatively smaller arrays it works fine. - -### Example: key=3, array=[1, 2, 3, 4, 5] - -Iteration 1 -
array[i] = array[0] = 1 -
key = 3 -
key != array[i] - -Iteration 2 -
array[i] = array[1] = 2 -
key = 3 -
key != array[i] - -Iteration 3 -
array[i] = array[2] = 3 -
key = 3 -
key = array[i] -
break -
flag = 1 -
pos = 2 - -[1]: https://robbell.io/2009/06/a-beginners-guide-to-big-o-notation -[2]: https://en.wikipedia.org/wiki/Big_O_notation - - -## Requirements - -Write a sample program that takes a list of numbers (e.g. "1, 2, 3, 4, 5") and a key (e.g. "3"). - -``` -linear-search.lang "1, 4, 2, 9" "3" -``` - -In addition, there should be some error handling for situations where the user -doesn't supply correct input. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Linear Search. -In order to keep things simple, we split up the testing as follows: - -- Linear Search Valid Tests -- Linear Search Invalid Tests - -### Linear Search Valid Tests - -| Description | List Input | Target Integer Input | Output | -| ----------- | ---------- | -------------------- | ------ | -| Sample Input First True | "1, 3, 5, 7" | "1" | "true" | -| Sample Input Last True | "1, 3, 5, 7" | "7" | "true" | -| Sample Input Middle True | "1, 3, 5, 7" | "5" | "true" | -| Sample Input One True | "5" | "5" | "true" | -| Sample Input One False | "5" | "7" | "false" | -| Sample Input Many False | "1, 3, 5, 6" | "7" | "false" | - -### Linear Search Invalid Tests - -| Description | List Input | Target Integer Input | -| ----------- | ---------- | -------------------- | -| No Input | | | -| Missing Input: Target | "1, 2, 3, 4" | | -| Missing Input: List | "" | "5" | - -All of these tests should output the following: - -``` -Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11") -``` - - -## Articles - -There are 35 articles: - -- [Linear Search in ALGOL 60](/projects/linear-search/algol60) -- [Linear Search in ALGOL 68](/projects/linear-search/algol68) -- [Linear Search in AWK](/projects/linear-search/awk) -- [Linear Search in Ada](/projects/linear-search/ada) -- [Linear Search in Beef](/projects/linear-search/beef) -- [Linear Search in C](/projects/linear-search/c) -- [Linear Search in C#](/projects/linear-search/c-sharp) -- [Linear Search in C++](/projects/linear-search/c-plus-plus) -- [Linear Search in COBOL](/projects/linear-search/cobol) -- [Linear Search in Commodore BASIC](/projects/linear-search/commodore-basic) -- [Linear Search in Elvish](/projects/linear-search/elvish) -- [Linear Search in Euphoria](/projects/linear-search/euphoria) -- [Linear Search in F#](/projects/linear-search/f-sharp) -- [Linear Search in Fortran](/projects/linear-search/fortran) -- [Linear Search in Go](/projects/linear-search/go) -- [Linear Search in Haskell](/projects/linear-search/haskell) -- [Linear Search in Java](/projects/linear-search/java) -- [Linear Search in JavaScript](/projects/linear-search/javascript) -- [Linear Search in Kotlin](/projects/linear-search/kotlin) -- [Linear Search in Lua](/projects/linear-search/lua) -- [Linear Search in Mathematica](/projects/linear-search/mathematica) -- [Linear Search in OCaml](/projects/linear-search/ocaml) -- [Linear Search in PHP](/projects/linear-search/php) -- [Linear Search in Pascal](/projects/linear-search/pascal) -- [Linear Search in Perl](/projects/linear-search/perl) -- [Linear Search in PowerShell](/projects/linear-search/powershell) -- [Linear Search in Python](/projects/linear-search/python) -- [Linear Search in Ruby](/projects/linear-search/ruby) -- [Linear Search in Rust](/projects/linear-search/rust) -- [Linear Search in Scala](/projects/linear-search/scala) -- [Linear Search in Swift](/projects/linear-search/swift) -- [Linear Search in Tcl](/projects/linear-search/tcl) -- [Linear Search in TypeScript](/projects/linear-search/typescript) -- [Linear Search in Visual Basic](/projects/linear-search/visual-basic) -- [Linear Search in m4](/projects/linear-search/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/linear-search/java/index.md b/docs/projects/linear-search/java/index.md deleted file mode 100644 index e9e5f4a950..0000000000 --- a/docs/projects/linear-search/java/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Ashish Aggarwal -- Jeremy Grifski -- rzuckerm -date: 2020-10-05 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-01-29 -layout: default -tags: -- java -- linear-search -title: Linear Search in Java -title1: Linear Search -title2: in Java ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -public class LinearSearch { - - public static void main(String[] args) { - try { - ArrayList listOfNumbers = new ArrayList<>(); - Integer keyToSearch = Integer.parseInt(args[1]); - String[] NumberArray = args[0].split(","); - for (String Number : NumberArray) { - listOfNumbers.add(Integer.parseInt(Number.trim())); - } - if (listOfNumbers.size() >= 1) { - StringBuilder output = new StringBuilder(); - Boolean searched = linearSearch(listOfNumbers, keyToSearch); - System.out.println(searched); - } else { - System.out.println( - "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); - } - } catch (Exception e) { - System.out.println( - "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"); - } - } - - private static Boolean linearSearch(ArrayList list, Integer keyToSearch) { - Boolean ans = false; - for (Integer number : list) { - if (number == keyToSearch) { - ans = true; - break; - } - } - return ans; - } -} - -``` - -{% endraw %} - -Linear Search in [Java](/languages/java) was written by: - -- Ashish Aggarwal -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/javascript/index.md b/docs/projects/linear-search/javascript/index.md deleted file mode 100644 index 65cdb028db..0000000000 --- a/docs/projects/linear-search/javascript/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Grifski -- NameerWaqas -- rzuckerm -date: 2020-10-01 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- javascript -- linear-search -title: Linear Search in JavaScript -title1: Linear Search -title2: in JavaScript ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -function LinSearch(arr = [], valToSearch) { - let check = false; - if (arr.length == 0) return check; - if(valToSearch==='') return check; - else { - for (i = 0; i < arr.length; i++) { - if (arr[i] == valToSearch){ - check = true; - return check; - } - } - return check; - } -} - -sanitizeArray = (list) => { - return list.split(',').map(e => { - _e = parseInt(e.replace(" ","")); - if (!_e){ throw new Error();} - return _e; - }); - } - -const exit = () => { - const usage = 'Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")'; - console.log(usage); - process.exit(); - } - -const main = (input, key) => { - try { - arr = sanitizeArray(input); - arr.length < 1 || key == undefined ? exit() : console.log(LinSearch(arr, key)); - } catch(err) { - exit(); - } -} - -main(process.argv[2], process.argv[3]); - -``` - -{% endraw %} - -Linear Search in [JavaScript](/languages/javascript) was written by: - -- Jeremy Grifski -- NameerWaqas -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/kotlin/index.md b/docs/projects/linear-search/kotlin/index.md deleted file mode 100644 index 2c49c828c2..0000000000 --- a/docs/projects/linear-search/kotlin/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Matthew Larsen -date: 2025-02-13 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-02-13 -layout: default -tags: -- kotlin -- linear-search -title: Linear Search in Kotlin -title1: Linear Search -title2: in Kotlin ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) -{ - // store usage message in variable - val message = "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")" - - // validate input array is correct size and does not contain empty Strings - if(args.size !=2 || args[0].isBlank() || args[1].isBlank()) - { - println(message) - return - } - - // convert input number String into a List of integers, invalid characters are converted to null - val intList = args[0].split(",").map { it.trim().toIntOrNull() } - - // convert input key String into an int, invalid characters are converted to null - val key = args[1].toIntOrNull() - - // check if the List or the key contains null (invalid) elements - if(null in intList || key == null) - { - println(message) - return - } - - // check if key is in the List and print returned boolean - println(key in intList) -} -``` - -{% endraw %} - -Linear Search in [Kotlin](/languages/kotlin) was written by: - -- Matthew Larsen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/lua/index.md b/docs/projects/linear-search/lua/index.md deleted file mode 100644 index d6869361f2..0000000000 --- a/docs/projects/linear-search/lua/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Connor H -date: 2025-10-29 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-10-29 -layout: default -tags: -- linear-search -- lua -title: Linear Search in Lua -title1: Linear Search -title2: in Lua ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua - -local args = {...} - -local nums_str = args[1] - -local key = tonumber(args[2]) - -local numbers = {} - -local found = false - - if #args ~= 2 then - print('Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")') - return - end - - if not key then - - print('Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")') - return - end - - if #nums_str < 1 then - print('Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")') - return - end - -for num in string.gmatch(nums_str, '([^,]+)') do - table.insert(numbers, tonumber(num)) -end - - - - -for i = 1, #numbers do - - if numbers[i] == key then - found = true - - break - end -end - -print(found and "true" or "false") - -``` - -{% endraw %} - -Linear Search in [Lua](/languages/lua) was written by: - -- Connor H - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/m4/index.md b/docs/projects/linear-search/m4/index.md deleted file mode 100644 index df6847768a..0000000000 --- a/docs/projects/linear-search/m4/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-09-03 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-09-03 -layout: default -tags: -- linear-search -- m4 -title: Linear Search in m4 -title1: Linear -title2: Search in m4 ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11") -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl linear_search(varname, target): -dnl for n = 0 to varname[length] - 1 -dnl if varname[n] == target: -dnl Return n -dnl Return -1 -define(`linear_search', `_linear_search(`$1', `$2', 0)') -define(`_linear_search', -`ifelse( -eval($3 >= array_get(`$1', `length')), 1, `-1', -array_get(`$1', $3), `$2', $3, `_linear_search(`$1', `$2', incr($3))'dnl -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 2 || len(ARGV1) < 1 || !parse_int_list(`arr', ARGV1) || !is_valid(ARGV2)), 1, `show_usage()')dnl -ifelse(linear_search(`arr', ARGV2), -1, `false', `true') - -``` - -{% endraw %} - -Linear Search in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/mathematica/index.md b/docs/projects/linear-search/mathematica/index.md deleted file mode 100644 index 0bc6bc2fae..0000000000 --- a/docs/projects/linear-search/mathematica/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-18 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-01-18 -layout: default -tags: -- linear-search -- mathematica -title: Linear Search in Mathematica -title1: Linear Search -title2: in Mathematica ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* This is simply the 'FirstCase' built-in. Only an outer function is needed to provide the 'user interface': *) - -linearSearchMain = Function[{list, value}, - Module[{e = "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"}, - Catch[ - Replace[ - FirstCase @@ Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments to FirstCase: list of items and value to search *) - {StringSplit[If[list != "", list, Throw[e]], ", "], value}, - {-1} (* at each leaf *)], - {_Missing -> "false", _ -> "true"}]]]]; - - -(* Valid Tests *) - -Print /@ Apply[linearSearchMain] /@ { - {"1, 3, 5, 7", "1"}, - {"1, 3, 5, 7", "7"}, - {"1, 3, 5, 7", "5"}, - {"5", "5"}, - {"5", "7"}, - {"1, 3, 5, 6", "7"} - }; - - -(* Invalid Tests *) - -linearSearchMain["1, 2, 3, 4", ""] -linearSearchMain["", "5"] - -``` - -{% endraw %} - -Linear Search in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/ocaml/index.md b/docs/projects/linear-search/ocaml/index.md deleted file mode 100644 index ff012ad26c..0000000000 --- a/docs/projects/linear-search/ocaml/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-17 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- linear-search -- ocaml -title: Linear Search in OCaml -title1: Linear Search -title2: in OCaml ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let ( let* ) = Option.bind -let ( let+ ) f g = Option.map g f - -let parse_list list_str = - let rec aux acc l = - match l with - | [] -> Some (List.rev acc) - | head :: rest -> - let* num = head |> String.trim |> int_of_string_opt in - aux (num :: acc) rest - in - list_str |> String.split_on_char ',' |> aux [] - -let parse_args argv = - match argv with - | [| _; nums; key |] -> - let* parsed_nums = parse_list nums in - let+ parsed_key = int_of_string_opt key in - (parsed_nums, parsed_key) - | _ -> None - -let () = - match parse_args Sys.argv with - | Some (nums, key) -> Printf.printf "%b\n" (List.mem key nums) - | _ -> - print_endline - {|Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")|} - -``` - -{% endraw %} - -Linear Search in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/pascal/index.md b/docs/projects/linear-search/pascal/index.md deleted file mode 100644 index ae036b865d..0000000000 --- a/docs/projects/linear-search/pascal/index.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- linear-search -- pascal -title: Linear Search in Pascal -title1: Linear Search -title2: in Pascal ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program LinearSearch; - -{$mode objfpc}{$H+} - -uses - Generics.Collections, - SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) = 0 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function LinearSearch(const Haystack: TIntegerList; const Needle: integer): boolean; -var - i: integer; -begin - if Haystack.Count = 1 then - Exit(Haystack[0] = Needle); - - Result := False; - - for i := 0 to Haystack.Count - 1 do - if Haystack[i] = Needle then - Exit(True); -end; - -var - List: TIntegerList; - Value: integer; -begin - if ParamCount <> 2 then - ShowUsage; - - try - if Trim(ParamStr(1)) = '' then - ShowUsage; - - List := ParseIntegerList(ParamStr(1)); - - if not TryStrToInt(ParamStr(2), Value) then - begin - List.Free; - ShowUsage; - end; - - Writeln(BoolToStr(LinearSearch(List, Value), 'true', 'false')); - finally - List.Free; - end; -end. - -``` - -{% endraw %} - -Linear Search in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/perl/index.md b/docs/projects/linear-search/perl/index.md deleted file mode 100644 index 43c99d6778..0000000000 --- a/docs/projects/linear-search/perl/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Tim W -- Ștefan-Iulian Alecu -date: 2025-02-13 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- linear-search -- perl -title: Linear Search in Perl -title1: Linear Search -title2: in Perl ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -use feature qw/keyword_any/; -no warnings 'experimental::keyword_any'; - -sub usage { - say 'Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")'; - exit; -} - -sub parse_list ($s) { - return undef unless defined $s; - - my @vals = split /\s*,\s*/, $s; - - return undef unless @vals; - return undef if any { $_ !~ /\A\d+\z/ } @vals; - - @vals = map 0 + $_, @vals; - - return \@vals; -} - -my ( $list_s, $num_s ) = @ARGV; - -defined $num_s or usage(); - -my $list = parse_list($list_s) or usage(); - -usage() unless $num_s =~ /\A\d+\z/; -my $num = 0 + $num_s; - -my $found = any { $_ == $num } @$list; -say $found ? "true" : "false"; - -``` - -{% endraw %} - -Linear Search in [Perl](/languages/perl) was written by: - -- Tim W -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/php/index.md b/docs/projects/linear-search/php/index.md deleted file mode 100644 index 017a60ad0d..0000000000 --- a/docs/projects/linear-search/php/index.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-24 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-03-24 -layout: default -tags: -- linear-search -- php -title: Linear Search in PHP -title1: Linear Search -title2: in PHP ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -// Exit if too few arguments -if (count($argv) < 3) -{ - usage(); -} - -// Parse 1st argument. Exit if invalid or too few values -$values = parse_int_array($argv[1]); -if ($values === FALSE || count($values) < 1) -{ - usage(); -} - -// Parse 2nd argument. Exit if invalid -$target = parse_int($argv[2]); -if ($target === FALSE) -{ - usage(); -} - -// Use built-in linear search and show result -$index = array_search($target, $values); -printf("%s\n", ($index !== FALSE) ? "true" : "false"); - -``` - -{% endraw %} - -Linear Search in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/powershell/index.md b/docs/projects/linear-search/powershell/index.md deleted file mode 100644 index 399b90c4d4..0000000000 --- a/docs/projects/linear-search/powershell/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-09 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-07-09 -layout: default -tags: -- linear-search -- powershell -title: Linear Search in PowerShell -title1: Linear Search -title2: in PowerShell ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -function Invoke-LinearSearch([int[]]$arr, [int]$target) { - $arr.IndexOf($target) -} - -if ($args.Length -lt 2 -or -not $args[0]) { - Show-Usage -} - -try { - $arr = Parse-IntList $args[0] - $target = [int]::Parse($args[1]) -} catch { - Show-Usage -} - -$idx = Invoke-LinearSearch $arr $target -Write-Output (($idx -ge 0) ? "true" : "false") - -``` - -{% endraw %} - -Linear Search in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/python/index.md b/docs/projects/linear-search/python/index.md deleted file mode 100644 index a2d0c983ea..0000000000 --- a/docs/projects/linear-search/python/index.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -authors: -- frankhart2017 -- Jeremy Grifski -- rzuckerm -- Siddhartha Dhar Choudhury -date: 2019-10-17 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- linear-search -- python -title: Linear Search in Python -title1: Linear Search -title2: in Python ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def sysarg_to_list(string: str): - return [int(x.strip(" "), 10) for x in string.split(',')] - - -def linear_search(array: list, key: int) -> bool: - for item in array: - if item == key: - return True - return False - - -if len(sys.argv) != 3 or not sys.argv[1]: - print('Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")') -else: - key = int(sys.argv[2]) - array = sysarg_to_list(sys.argv[1]) - print(linear_search(array, key)) - -``` - -{% endraw %} - -Linear Search in [Python](/languages/python) was written by: - -- frankhart2017 -- Jeremy Grifski -- rzuckerm -- Siddhartha Dhar Choudhury - -This article was written by: - -- frankhart2017 -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's break up the code into parts to get a deeper understanding of the entire code. - -### Convert String to List of Integers - -```python -def sysarg_to_list(string: str): - return [int(x.strip(" "), 10) for x in string.split(',')] -``` - -This function takes a string like `"2, 1, 10, 5, 3"`, and turns into a list of numbers. -It does this using a list comprehension, first we need to convert our string into a -list `string.split(',')` which is a list of strings split by comma (`,`). So our -original input string becomes `["2", " 1", " 10", " 5", " 3"]`. -Then for each element in the list `for x in ...` , we do something to it. - -In this example we convert it into a decimal integer, `int(x.strip(" "), 10)`. Then `x.strip(" ")`, -removes any whitespace so `" 1"` becomes `"1"`. Then `int("1", 10)` -converts the string `"1"` into a decimal number in this case `1`. This is done -for every item in the list so our original input of `"2, 1, 10, 5, 3"` becomes `[2, 1, 10, 5, 3]`. - -### Linear Search - -```python -def linear_search(array: list, key: int) -> bool: - for item in array: - if item == key: - return True - return False -``` - -This function loops through each element in `array` comparing current value (`item`) to the -desired value (`key`). When a match is found, `True` is returned. When all values have been -compared, and no match is found, `False` is returned. - -### Get User Input and Process It - -```python -if len(sys.argv) != 3 or not sys.argv[1]: - print('Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")') -else: - key = int(sys.argv[2]) - array = sysarg_to_list(sys.argv[1]) - print(linear_search(array, key)) -``` - -The first command-line argument is a string containing a comma-separated list of integers, and the -second command-line argument is the value to find. If the number of arguments is not correct, or -the first argument is empty, a user statement is displayed. Otherwise, the following is done: - -* Convert the value to find (`sys.argv[2]`) to an integer -* Call `sysarg_to_list` to convert the string to a list of integers -* Call `linear_search` to search for the value in the list -* Call `print` to display the result of the search - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Linear Search in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/linear_search.py). -After that, we should make sure we have the [latest Python interpreter](https://www.python.org/downloads/). -From there, we can run the following command in the terminal: - -``` -python linear-search.py "3, 2, 6, 1, 7" "2" -``` - -Alternatively, we can copy the solution into an [online Python interpreter](https://www.online-python.com/) and hit run. diff --git a/docs/projects/linear-search/ruby/index.md b/docs/projects/linear-search/ruby/index.md deleted file mode 100644 index b405840485..0000000000 --- a/docs/projects/linear-search/ruby/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Elvin Hrytsyuk -- Ștefan-Iulian Alecu -date: 2025-10-29 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- linear-search -- ruby -title: Linear Search in Ruby -title1: Linear Search -title2: in Ruby ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def usage! - abort('Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")') -end - -list_str, target_str = ARGV - -usage! if [list_str, target_str].any? { it.to_s.strip.empty? } - -numbers = list_str.split(",").map { Integer(it.strip) } -target = Integer(target_str) - -puts numbers.include?(target) - -``` - -{% endraw %} - -Linear Search in [Ruby](/languages/ruby) was written by: - -- Elvin Hrytsyuk -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/rust/index.md b/docs/projects/linear-search/rust/index.md deleted file mode 100644 index d66d9ac4ec..0000000000 --- a/docs/projects/linear-search/rust/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-09 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- linear-search -- rust -title: Linear Search in Rust -title1: Linear Search -title2: in Rust ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!( - "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")" - ); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -fn linear_search(arr: &Vec, target: &T) -> Option { - arr.into_iter().position(|x| x == target) -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 2nd command-line argument to integer - let target: i32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Do linear search and display result - let result: bool = match linear_search::(&arr, &target) { - Some(_) => true, - None => false, - }; - println!("{result}"); -} - -``` - -{% endraw %} - -Linear Search in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/scala/index.md b/docs/projects/linear-search/scala/index.md deleted file mode 100644 index a1271b552d..0000000000 --- a/docs/projects/linear-search/scala/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- konradkelly -- Ștefan-Iulian Alecu -date: 2025-10-31 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- linear-search -- scala -title: Linear Search in Scala -title1: Linear Search -title2: in Scala ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -import scala.util.Try - -object LinearSearch: - - private val usage = - """Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")""" - - def main(args: Array[String]): Unit = - if args.length < 2 then - println(usage) - else - val listStr = args(0) - val targetStr = args(1) - - val output = - for - numbers <- parseNumbers(listStr) - target <- targetStr.toIntOption - yield numbers.contains(target) - - println(output.map(_.toString).getOrElse(usage)) - - private def parseNumbers(input: String): Option[List[Int]] = - Try(input.split(',').map(_.trim.toInt).toList).toOption -``` - -{% endraw %} - -Linear Search in [Scala](/languages/scala) was written by: - -- konradkelly -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/swift/index.md b/docs/projects/linear-search/swift/index.md deleted file mode 100644 index c5c357170b..0000000000 --- a/docs/projects/linear-search/swift/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- linear-search -- swift -title: Linear Search in Swift -title1: Linear Search -title2: in Swift ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11") - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -extension Collection { - subscript(safe index: Index) -> Element? { - indices.contains(index) ? self[index] : nil - } -} - -extension Collection where Element: Equatable { - func linearSearch(for target: Element) -> Index? { - firstIndex(of: target) - } -} - -func parseInput(_ args: [String]) -> ([Int], Int)? { - guard - let rawList = args[safe: 1], - let rawTarget = args[safe: 2], - let target = Int(rawTarget) - else { return nil } - - let values = - rawList - .split(separator: ",") - .compactMap { Int($0.trimmed) } - - return values.isEmpty ? nil : (values, target) -} - -guard let (values, target) = parseInput(CommandLine.arguments) else { - print(usage) - exit(1) -} - -print(values.linearSearch(for: target) != nil) - -``` - -{% endraw %} - -Linear Search in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/tcl/index.md b/docs/projects/linear-search/tcl/index.md deleted file mode 100644 index d23e9ccced..0000000000 --- a/docs/projects/linear-search/tcl/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: linear-search-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- linear-search -- tcl -title: Linear Search in Tcl -title1: Linear Search -title2: in Tcl ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a list of integers ("1, 4, 5, 11, 12") and the integer to find ("11")} - exit 1 -} - -proc parseList {s} { - set tokens [split [string trim $s] ","] - if {[llength $tokens] < 1} { usage } - - set result {} - - set result {} - foreach token $tokens { - set t [string trim $token] - if {$t eq "" || [catch {expr {int($t)}} val]} usage - lappend result $val - } - return $result -} - - -proc parseInt {s} { - set s [string trim $s] - if {$s eq "" || [catch {expr {int($s)}} val]} { - usage - } - return $val -} - -proc linearSearch {nums value} { - expr {[lsearch -integer -exact $nums $value] != -1} -} - -if {$argc != 2} { usage } - -set numbers [parseList [lindex $argv 0]] -set key [parseInt [lindex $argv 1]] - -set found [linearSearch $numbers $key] -puts [expr {$found ? "true" : "false"}] - - -``` - -{% endraw %} - -Linear Search in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/typescript/index.md b/docs/projects/linear-search/typescript/index.md deleted file mode 100644 index ab71566e68..0000000000 --- a/docs/projects/linear-search/typescript/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2023-10-02 -featured-image: linear-search-in-every-language.jpg -last-modified: 2023-10-02 -layout: default -tags: -- linear-search -- typescript -title: Linear Search in TypeScript -title1: Linear Search -title2: in TypeScript ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -const error_msg: string = "Usage: please provide a list of integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")"; -if (process.argv.length != 4) { - console.log(error_msg); - process.exit(1); -} - -let list_str: string = process.argv[2] -let target: number = parseInt(process.argv[3]); - -if (isNaN(target) || list_str.length == 0) { - console.log(error_msg); - process.exit(1); -} -let list: number[] = list_str.split(",").map((x: string) => parseInt(x)); -let found: boolean = false; -for (let i = 0; i < list.length; i++) { - if (list[i] == target) { - found = true; - break; - } -} -console.log(found ? "true" : "false"); - -``` - -{% endraw %} - -Linear Search in [TypeScript](/languages/typescript) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/linear-search/visual-basic/index.md b/docs/projects/linear-search/visual-basic/index.md deleted file mode 100644 index d6a25fb9c9..0000000000 --- a/docs/projects/linear-search/visual-basic/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: linear-search-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- linear-search -- visual-basic -title: Linear Search in Visual Basic -title1: Linear Search -title2: in Visual Basic ---- - - - -Welcome to the [Linear Search](/projects/linear-search) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Module LinearSearch - - Public Sub Main(args As String()) - - If args.Length < 2 Then - ShowUsage() - Return - End If - - Dim list = ParseList(args(0)) - Dim target As Integer - - If list Is Nothing OrElse - Not Integer.TryParse(args(1), target) Then - - ShowUsage() - Return - End If - - Console.WriteLine(Search(list, target)) - - End Sub - - - Private Function Search(list As List(Of Integer), target As Integer) As Boolean - - For Each value In list - If value = target Then - Return True - End If - Next - - Return False - - End Function - - - Private Function ParseList(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - Return Nothing - End If - - Dim result As New List(Of Integer) - - For Each part In input.Split(","c, StringSplitOptions.RemoveEmptyEntries) - - Dim value As Integer - - If Not Integer.TryParse(part.Trim(), value) Then - Return Nothing - End If - - result.Add(value) - - Next - - Return result - - End Function - - - Private Sub ShowUsage() - Console.WriteLine("Usage: please provide a list of integers (""1, 4, 5, 11, 12"") and the integer to find (""11"")") - Environment.Exit(1) - End Sub - -End Module -``` - -{% endraw %} - -Linear Search in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/ada/index.md b/docs/projects/longest-common-subsequence/ada/index.md deleted file mode 100644 index 42efa6a0c5..0000000000 --- a/docs/projects/longest-common-subsequence/ada/index.md +++ /dev/null @@ -1,203 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-11 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- ada -- longest-common-subsequence -title: Longest Common Subsequence in Ada -title1: Longest Common -title2: Subsequence in Ada ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -pragma Ada_2022; - -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Strings.Maps; use Ada.Strings.Maps; -with Ada.Containers.Vectors; - -procedure Longest_Common_Subsequence is - - Data_Format_Error : exception; - - package Integer_Vectors is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - use Integer_Vectors; - - subtype Int_List is Integer_Vectors.Vector; - - function Clean (S : String) return String - is (Trim (S, Ada.Strings.Both)); - - function To_Int (S : String) return Integer is - Cleaned : constant String := Clean (S); - begin - return Integer'Value (Cleaned); - exception - when Constraint_Error => - raise Data_Format_Error with "Invalid integer: '" & Cleaned & "'"; - end To_Int; - - function To_Int_List (Raw_String : String) return Int_List is - Result : Int_List; - Start : Positive := Raw_String'First; - Finish : Natural; - Seps : constant Character_Set := To_Set (", "); - begin - while Start <= Raw_String'Last loop - Find_Token - (Raw_String, Seps, Start, Ada.Strings.Outside, Start, Finish); - - exit when Start > Finish; - - Result.Append (To_Int (Raw_String (Start .. Finish))); - - Start := Finish + 1; - end loop; - - if Result.Is_Empty then - raise Data_Format_Error with "List is empty"; - end if; - - return Result; - end To_Int_List; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide two lists in the format ""1, 2, 3, 4, 5"""); - end Print_Usage; - - function LCS (A, B : Int_List) return Int_List is - N : constant Natural := Natural (A.Length); - M : constant Natural := Natural (B.Length); - - DP : array (0 .. N, 0 .. M) of Natural := (others => (others => 0)); - Result : Int_List; - - begin - for I in 1 .. N loop - for J in 1 .. M loop - - declare - X : constant Integer := Element (A, I - 1); - Y : constant Integer := Element (B, J - 1); - begin - if X = Y then - DP (I, J) := DP (I - 1, J - 1) + 1; - else - DP (I, J) := Natural'Max (DP (I - 1, J), DP (I, J - 1)); - end if; - end; - - end loop; - end loop; - - declare - I : Natural := N; - J : Natural := M; - begin - while I > 0 and J > 0 loop - - declare - X : constant Integer := Element (A, I - 1); - Y : constant Integer := Element (B, J - 1); - begin - if X = Y then - Result.Prepend (X); - I := I - 1; - J := J - 1; - - elsif DP (I - 1, J) >= DP (I, J - 1) then - I := I - 1; - else - J := J - 1; - end if; - end; - - end loop; - end; - - return Result; - end LCS; - - procedure Print_List (V : Int_List) is - First : constant Natural := V.First_Index; - Last : constant Natural := V.Last_Index; - - function Img (X : Integer) return String - is (Trim (Integer'Image (X), Ada.Strings.Left)); - begin - for I in First .. Last loop - Put (Img (V (I))); - if I /= Last then - Put (", "); - end if; - end loop; - New_Line; - end Print_List; - -begin - if Argument_Count /= 2 then - Print_Usage; - return; - end if; - - begin - declare - A : constant Int_List := To_Int_List (Argument (1)); - B : constant Int_List := To_Int_List (Argument (2)); - begin - if A.Is_Empty or else B.Is_Empty then - raise Data_Format_Error; - end if; - - Print_List (LCS (A, B)); - end; - exception - when Data_Format_Error | Constraint_Error => - Print_Usage; - end; - -end Longest_Common_Subsequence; - -``` - -{% endraw %} - -Longest Common Subsequence in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/algol60/index.md b/docs/projects/longest-common-subsequence/algol60/index.md deleted file mode 100644 index 268d4a198a..0000000000 --- a/docs/projects/longest-common-subsequence/algol60/index.md +++ /dev/null @@ -1,297 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-21 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-04-21 -layout: default -tags: -- algol60 -- longest-common-subsequence -title: Longest Common Subsequence in ALGOL 60 -title1: Longest Common -title2: Subsequence in ALGOL 60 ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide two lists in the format " - "\"1, 2, 3, 4, 5\"\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Output integer array; - procedure outIntegerArray(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i; - for i := 1 step 1 until arrLen do - begin - if i > 1 then outstring(1, ", "); - outIntegerNoSpace(arr[i]) - end; - - if arrLen > 0 then outstring(1, "\n") - end outIntegerArray; - - integer procedure max(a, b); - value a, b; - integer a, b; - begin - max := if a > b then a else b - end max; - - comment Source - https://en.wikipedia.org/wiki/Longest_common_subsequence# - Code_for_the_dynamic_programming_solution; - procedure lcs(x, m, y, n, result, resultLen); - value m, n; - integer array x, y, result; - integer m, n, resultLen; - begin - procedure backtrack(c, i, j); - value i, j; - integer array c; - integer i, j; - begin - if i != 0 & j != 0 then - begin - if x[i] = y[j] then - begin - result[c[i, j]] := x[i]; - backtrack(c, i - 1, j - 1) - end - else if c[i, j - 1] > c[i - 1, j] then backtrack(c, i, j - 1) - else backtrack(c, i - 1, j) - end - end backtrack; - - integer i, j; - integer array c[0:m, 0:n]; - - for i := 0 step 1 until m do c[i, 0] := 0; - for j := 0 step 1 until n do c[0, j] := 0; - for i := 1 step 1 until m do - begin - for j := 1 step 1 until n do - begin - if x[i] = y[j] then c[i, j] := c[i - 1, j - 1] + 1 - else c[i, j] := max(c[i, j - 1], c[i - 1, j]) - end - end; - - resultLen := c[m, n]; - backtrack(c, m, n) - end lcs; - - integer argc, list1Len, list2Len, resultLen; - integer array list1[1:100], list2[1:100], result[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 2 then usage; - - comment Get list 1 from 1st argument. Exit if invalid; - list1Len := inIntegerArray(list1, 100); - if list1Len < 1 then usage; - - comment Get list 2 from 2nd argument. Exit if invalid; - list2Len := inIntegerArray(list2, 100); - if list2Len < 1 then usage; - - comment Find longest command subsequence and output result; - lcs(list1, list1Len, list2, list2Len, result, resultLen); - outIntegerArray(result, resultLen) -end - -``` - -{% endraw %} - -Longest Common Subsequence in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/algol68/index.md b/docs/projects/longest-common-subsequence/algol68/index.md deleted file mode 100644 index 9ddec9c3e5..0000000000 --- a/docs/projects/longest-common-subsequence/algol68/index.md +++ /dev/null @@ -1,232 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-13 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2023-02-13 -layout: default -tags: -- algol68 -- longest-common-subsequence -title: Longest Common Subsequence in ALGOL 68 -title1: Longest Common -title2: Subsequence in ALGOL 68 ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: printf(($gl$, "Usage: please provide two lists in the format ""1, 2, 3, 4, 5""")); - -COMMENT -Longest Common Sequence -Source: https://en.wikipedia.org/wiki/Longest_common_subsequence#Example_in_C# - -However, instead of storing lengths, the entire subsequence is stored -COMMENT -PROC longest common subsequence = (REF []INT list1, REF []INT list2) REF []INT: -( - # Allocate space for all of the subsequence pointers # - INT m := UPB list1; - INT n := UPB list2; - HEAP [0..m, 0..n]REF []INT c; - - # Initialize subsequences of zero length # - HEAP [0]INT empty list := (); - FOR i FROM 0 TO m - DO - c[i, 0] := empty list - OD; - - FOR j FROM 0 TO n - DO - c[0, j] := empty list - OD; - - # Find the longest common subsequence using prior subsequences # - INT num elems; - FOR i TO m - DO - FOR j TO n - DO - # If common element found, create new subsequence based on prior # - # subsequence with the common element appended # - IF list1[i] = list2[j] - THEN - num elems := ELEMS c[i - 1, j - 1]; - c[i, j] := HEAP [num elems + 1]INT; - c[i, j][1..num elems] := c[i - 1, j - 1]; - c[i, j][num elems + 1] := list1[i] - # Else, reuse the longer of the two prior subsequences # - ELSE - c[i, j] := (ELEMS c[i, j - 1] > ELEMS c[i - 1, j] | c[i, j - 1] | c[i - 1, j]) - FI - OD - OD; - - c[m, n] -); - -PROC show list values = (REF []INT values) VOID: -( - INT n = UPB values; - FOR k TO n - DO - IF k > 1 - THEN - print(", ") - FI; - - print(whole(values[k], 0)) - OD; - - IF n > 0 - THEN - print(newline) - FI -); - -# Parse 1st and 2nd command-line arguments # -[2]REF []INT lists; -[2]INT argnums := (4, 5); -FOR k TO 2 -DO - STRING s := argv(argnums[k]); - PARSEINTLIST_RESULT list result := parse int list(s); - lists[k] := values OF list result; - IF NOT valid OF list result - THEN - usage; - stop - FI -OD; - -# Get longest common subsequence and display it # -REF []INT result = longest common subsequence(lists[1], lists[2]); -show list values(result) - -``` - -{% endraw %} - -Longest Common Subsequence in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/awk/index.md b/docs/projects/longest-common-subsequence/awk/index.md deleted file mode 100644 index 8249664da2..0000000000 --- a/docs/projects/longest-common-subsequence/awk/index.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-27 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2025-04-27 -layout: default -tags: -- awk -- longest-common-subsequence -title: Longest Common Subsequence in AWK -title1: Longest Common -title2: Subsequence in AWK ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide two lists in the format \"1, 2, 3, 4, 5\"" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -# Source: https://en.wikipedia.org/wiki/Longest_common_subsequence -# However, instead of storing lengths, an index to a subsequence is stored. -function longest_common_subsequence(list1, m, list2, n, arr, \ - i, j, k, c, subsequences, num_subsequences, len1, len2) { - # Initialize subsequences of length 0 - for (i = 0; i <= m; i++) { - c[i, 0] = 0 - } - - for (j = 0; j <=n; j++) { - c[0, j] = 0 - } - - num_subsequences = 0 - - # Find the longest common subsequence using prior subsequences - for (i = 1; i <= m; i++) { - for (j = 1; j <= n; j++) { - # If common element found, create new subsequence based on prior - # subsequence with the common element appended - if (list1[i] == list2[j]) { - num_subsequences++ - c[i, j] = num_subsequences - len1 = length(subsequences[c[i - 1, j - 1]]) - copy_array(subsequences[c[i - 1, j - 1]], len1, subsequences[num_subsequences]) - subsequences[num_subsequences][len1 + 1] = list1[i] - } else { - # Else, reuse the longer of the two prior subsequences - len1 = length(subsequences[c[i, j - 1]]) - len2 = length(subsequences[c[i - 1, j]]) - c[i, j] = (len1 > len2) ? c[i, j - 1] : c[i - 1, j] - } - } - } - - len1 = length(subsequences[c[m, n]]) - copy_array(subsequences[c[m, n]], len1, arr) -} - -function copy_array(arr_src, arr_src_len, arr_dest, i) { - for (i = 1; i <= arr_src_len; i++) { - arr_dest[i] = arr_src[i] - } -} - -function show_array(arr, idx, s) { - s = "" - for (idx in arr) { - if (s) { - s = s ", " - } - s = s arr[idx] - } - - print s -} - -BEGIN { - if (ARGC < 3) { - usage() - } - - str_to_array(ARGV[1], list1) - m = length(list1) - str_to_array(ARGV[2], list2) - n = length(list2) - if (!m || list1[1] == "ERROR" || !n || list2[1] == "ERROR") { - usage() - } - - longest_common_subsequence(list1, m, list2, n, arr) - show_array(arr) -} - -``` - -{% endraw %} - -Longest Common Subsequence in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/beef/index.md b/docs/projects/longest-common-subsequence/beef/index.md deleted file mode 100644 index bb0e92ed09..0000000000 --- a/docs/projects/longest-common-subsequence/beef/index.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-11 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2024-02-11 -layout: default -tags: -- beef -- longest-common-subsequence -title: Longest Common Subsequence in Beef -title1: Longest Common -title2: Subsequence in Beef ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace LongestCommonSubsequence; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide two lists in the format "1, 2, 3, 4, 5" - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Source: https://en.wikipedia.org/wiki/Longest_common_subsequence#Computing_the_length_of_the_LCS - // - // However, instead of storing lengths, an index to the subsequence is stored - public static void LongestCommonSubsequence(List arr1, List arr2, List result) - where int : operator T <=> T - { - int m = arr1.Count; - int n = arr2.Count; - - // Initialize all subsequences to the empty sequence - int[,] c = new .[m + 1, n + 1]; - List> subsequences = new .(); - subsequences.Add(new List()); - - // Find the longest common subsequence using prior subsequences - for (int i in 1...m) - { - for (int j in 1...n) - { - // If common element found, create new subsequence based on prior - // subsequence with the common element appended - if (arr1[i - 1] == arr2[j - 1]) - { - c[i, j] = subsequences.Count; - List newSubsequence = new .() .. - AddRange(subsequences[c[i - 1, j - 1]]) .. - Add(arr1[i - 1]); - subsequences.Add(newSubsequence); - } - // Else, reuse the longer of the two prior subsequences - else - { - int index1 = c[i, j - 1]; - int index2 = c[i - 1, j]; - c[i, j] = (subsequences[index1].Count > subsequences[index2].Count) ? - index1 : index2; - } - } - } - - // Store result - result.Clear(); - result.AddRange(subsequences[c[m, n]]); - - // Deallocate subsequences - for (List subsequence in subsequences) - { - delete subsequence; - } - delete subsequences; - delete c; - } - - public static void ShowList(List arr) - { - String line = scope .(); - for (T val in arr) - { - if (!line.IsEmpty) - { - line += ", "; - } - - line.AppendF("{}", val); - } - - Console.WriteLine(line); - } - - public static int Main(String[] args) - { - if (args.Count < 2) - { - Usage(); - } - - List arr1 = scope .(); - if (ParseIntList(args[0], arr1) case .Err) - { - Usage(); - } - - List arr2 = scope .(); - if (ParseIntList(args[1], arr2) case .Err) - { - Usage(); - } - - List result = scope .(); - LongestCommonSubsequence(arr1, arr2, result); - ShowList(result); - return 0; - } -} - -``` - -{% endraw %} - -Longest Common Subsequence in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/c-plus-plus/index.md b/docs/projects/longest-common-subsequence/c-plus-plus/index.md deleted file mode 100644 index 69f3a92090..0000000000 --- a/docs/projects/longest-common-subsequence/c-plus-plus/index.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Shubham Tiwari -- Ștefan-Iulian Alecu -date: 2019-10-13 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- longest-common-subsequence -title: Longest Common Subsequence in C++ -title1: Longest Common -title2: Subsequence in C++ ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace views = std::views; -namespace ranges = std::ranges; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide two lists in the format "1, 2, 3, 4, 5")" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.empty() ? std::nullopt : std::make_optional(out); -} - -template -std::vector find_lcs(const std::vector& a, const std::vector& b) { - const std::size_t m = a.size(); - const std::size_t n = b.size(); - - auto idx = [n](std::size_t i, std::size_t j) { return i * (n + 1) + j; }; - - std::vector dp((m + 1) * (n + 1), 0); - - for (std::size_t i = 1; i <= m; ++i) { - for (std::size_t j = 1; j <= n; ++j) { - if (a[i - 1] == b[j - 1]) - dp[idx(i, j)] = dp[idx(i - 1, j - 1)] + 1; - else - dp[idx(i, j)] = std::max(dp[idx(i - 1, j)], dp[idx(i, j - 1)]); - } - } - - std::vector result; - result.reserve(dp.back()); - - std::size_t i = m, j = n; - - while (i > 0 && j > 0) { - if (a[i - 1] == b[j - 1]) { - result.push_back(a[i - 1]); - --i; - --j; - } else if (dp[idx(i - 1, j)] > dp[idx(i, j - 1)]) { - --i; - } else { - --j; - } - } - - ranges::reverse(result); - return result; -} - -int main(int argc, char* argv[]) { - if (argc != 3) usage(); - - const auto a = parse_vec(argv[1]); - const auto b = parse_vec(argv[2]); - if (!a || !b) usage(); - - const auto result = find_lcs(*a, *b); - - for (const char* sep = ""; int val : result) { - std::cout << std::exchange(sep, ", ") << val; - } - std::cout << "\n"; -} -``` - -{% endraw %} - -Longest Common Subsequence in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Shubham Tiwari -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/c-sharp/index.md b/docs/projects/longest-common-subsequence/c-sharp/index.md deleted file mode 100644 index 59c8190294..0000000000 --- a/docs/projects/longest-common-subsequence/c-sharp/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-10-28 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- longest-common-subsequence -title: Longest Common Subsequence in C# -title1: Longest Common -title2: Subsequence in C# ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Collections.Generic; - -if ( - args is not [var raw1, var raw2] - || !TryParseList(raw1.AsSpan(), out var a) - || !TryParseList(raw2.AsSpan(), out var b) -) -{ - Console.WriteLine( - """ -Usage: please provide two lists in the format "1, 2, 3, 4, 5" -""" - ); - return; -} - -Console.WriteLine(string.Join(", ", LCS(a, b))); - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return true; -} - -static List LCS(List a, List b) -{ - int n = a.Count, m = b.Count; - if (n == 0 || m == 0) return []; - - int[,] dp = new int[n + 1, m + 1]; - - for (int i = 1; i <= n; i++) - for (int j = 1; j <= m; j++) - dp[i, j] = a[i - 1] == b[j - 1] - ? dp[i - 1, j - 1] + 1 - : Math.Max(dp[i - 1, j], dp[i, j - 1]); - - var result = new List(dp[n, m]); - - int i2 = n, j2 = m; - - while (i2 > 0 && j2 > 0) - { - if (a[i2 - 1] == b[j2 - 1]) - { - result.Add(a[i2 - 1]); - i2--; - j2--; - } - else if (dp[i2 - 1, j2] >= dp[i2, j2 - 1]) - { - i2--; - } - else - { - j2--; - } - } - - result.Reverse(); - return result; -} - -``` - -{% endraw %} - -Longest Common Subsequence in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/c/index.md b/docs/projects/longest-common-subsequence/c/index.md deleted file mode 100644 index ca1f3fe262..0000000000 --- a/docs/projects/longest-common-subsequence/c/index.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -authors: -- LezendarySandwich -- Ștefan-Iulian Alecu -date: 2019-10-20 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- longest-common-subsequence -title: Longest Common Subsequence in C -title1: Longest Common -title2: Subsequence in C ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -long long arr[100000], arr1[100000]; -int lc[1000][1000]; -long long ans[100000]; -int indic; - -long long get_val(int tmp[], int len) -{ - long long value = 0, mult = 1; - for (int i = len - 1; i > -1; --i) - { - if (tmp[i] == ' ' - '0') - { - printf("Usage: please provide two lists in the format \"1, 2, 3, " - "4, 5\""); - exit(0); - } - value += tmp[i] * mult; - mult *= 10; - } - return value; -} - -int max(int a, int b) -{ - return a > b ? a : b; -} - -int lcs(int l, int r) -{ - if (l < 0 || r < 0) - return 0; - if (lc[l][r] != -1) - return lc[l][r]; - if (arr[l] == arr1[r]) - lc[l][r] = lcs(l - 1, r - 1) + 1; - lc[l][r] = max(lc[l][r], max(lcs(l, r - 1), lcs(l - 1, r))); - return lc[l][r]; -} - -void find(int l, int r) -{ - if (l < 0 || r < 0) - return; - if (arr[l] == arr1[r]) - { - ans[indic++] = arr[l]; - find(l - 1, r - 1); - } - else if (lc[l - 1][r] == lc[l][r]) - find(l - 1, r); - else - find(l, r - 1); -} - -int main(int argc, char **argv) -{ - if (argv[1] == NULL - || strlen(argv[1]) == 0 - || argv[2] == NULL - || strlen(argv[2]) == 0) - { - printf( - "Usage: please provide two lists in the format \"1, 2, 3, 4, 5\""); - return 0; - } - - int len = strlen(argv[1]); - int tmp[20]; - int ind = 0; - int pos = 0; - - for (int i = 0; i < len; ++i) - { - if (argv[1][i] == ',') - { - long long val = get_val(tmp, ind); - ind = 0; - i++; - arr[pos++] = val; - continue; - } - tmp[ind++] = argv[1][i] - '0'; - } - arr[pos++] = get_val(tmp, ind); - int len1 = pos; - ind = 0, pos = 0; - len = strlen(argv[2]); - for (int i = 0; i < len; ++i) - { - if (argv[2][i] == ',') - { - long long val = get_val(tmp, ind); - ind = 0; - i++; - arr1[pos++] = val; - continue; - } - tmp[ind++] = argv[2][i] - '0'; - } - arr1[pos++] = get_val(tmp, ind); - memset(lc, -1, sizeof(lc)); - lcs(len1 - 1, pos - 1); - find(len1 - 1, pos - 1); - for (int i = indic - 1; i > -1; --i) - { - printf("%lld", ans[i]); - if (i != 0) - printf(", "); - } -} -``` - -{% endraw %} - -Longest Common Subsequence in [C](/languages/c) was written by: - -- LezendarySandwich -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/cobol/index.md b/docs/projects/longest-common-subsequence/cobol/index.md deleted file mode 100644 index 78e66e7907..0000000000 --- a/docs/projects/longest-common-subsequence/cobol/index.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- longest-common-subsequence -title: Longest Common Subsequence in COBOL -title1: Longest Common -title2: Subsequence in COBOL ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. longest-common-subsequence. - -environment division. - -data division. -working-storage section. - -01 ws-a-line pic x(200). -01 ws-b-line pic x(200). - -01 ws-a occurs 50 times pic s9(9). -01 ws-b occurs 50 times pic s9(9). - -01 ws-a-count pic 9(4) value 0. -01 ws-b-count pic 9(4) value 0. - -01 ws-i pic 9(4). -01 ws-j pic 9(4). -01 ws-pos pic 9(4). - -01 ws-temp pic x(200). -01 ws-num pic s9(9). - -01 dp-table. - 05 dp-row occurs 51 times. - 10 dp-col occurs 51 times pic 9(9) value 0. - -01 ws-result occurs 50 times pic s9(9). -01 ws-result-len pic 9(4) value 0. -01 ws-out-num pic -(9)9. - -01 ws-valid pic x value "y". - 88 is-valid value "y". - 88 is-invalid value "n". - -procedure division. -main. - accept ws-a-line from argument-value - accept ws-b-line from argument-value - - if ws-a-line = spaces or ws-b-line = spaces - perform show-usage - stop run - end-if - - perform parse-input - - if is-invalid - perform show-usage - stop run - end-if - - perform build-dp - perform backtrack - - perform print-result - stop run. - -parse-input. - set is-valid to true - - move ws-a-line to ws-temp - perform parse-a - - move ws-b-line to ws-temp - perform parse-b - - if ws-a-count = 0 or ws-b-count = 0 - set is-invalid to true - end-if. - -parse-a. - move 0 to ws-a-count - move 1 to ws-pos - - perform until ws-pos > length of ws-temp - unstring ws-temp - delimited by "," - into ws-num - with pointer ws-pos - end-unstring - - add 1 to ws-a-count - move ws-num to ws-a(ws-a-count) - end-perform. - -parse-b. - move 0 to ws-b-count - move 1 to ws-pos - - perform until ws-pos > length of ws-temp - unstring ws-temp - delimited by "," - into ws-num - with pointer ws-pos - end-unstring - - add 1 to ws-b-count - move ws-num to ws-b(ws-b-count) - end-perform. - -build-dp. - perform varying ws-i from 0 by 1 until ws-i > ws-a-count - perform varying ws-j from 0 by 1 until ws-j > ws-b-count - move 0 to dp-col(ws-i + 1, ws-j + 1) - end-perform - end-perform - - perform varying ws-i from 1 by 1 until ws-i > ws-a-count - perform varying ws-j from 1 by 1 until ws-j > ws-b-count - - if ws-a(ws-i) = ws-b(ws-j) - compute dp-col(ws-i + 1, ws-j + 1) = - dp-col(ws-i, ws-j) + 1 - else - compute dp-col(ws-i + 1, ws-j + 1) = - function max(dp-col(ws-i, ws-j + 1), dp-col(ws-i + 1, ws-j)) - end-if - - end-perform - end-perform. - -backtrack. - move ws-a-count to ws-i - move ws-b-count to ws-j - move 0 to ws-result-len - - perform until ws-i = 0 or ws-j = 0 - - if ws-a(ws-i) = ws-b(ws-j) - add 1 to ws-result-len - move ws-a(ws-i) to ws-result(ws-result-len) - - subtract 1 from ws-i - subtract 1 from ws-j - else - if dp-col(ws-i, ws-j + 1) >= dp-col(ws-i + 1, ws-j) - subtract 1 from ws-i - else - subtract 1 from ws-j - end-if - end-if - - end-perform. - -print-result. - if ws-result-len = 0 - display spaces - exit paragraph - end-if - - perform varying ws-i from ws-result-len by -1 until ws-i = 0 - move ws-result(ws-i) to ws-out-num - display function trim(ws-out-num) with no advancing - - if ws-i > 1 - display ", " with no advancing - end-if - end-perform. - -show-usage. - display 'Usage: please provide two lists in the format "1, 2, 3, 4, 5"'. - -``` - -{% endraw %} - -Longest Common Subsequence in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/commodore-basic/index.md b/docs/projects/longest-common-subsequence/commodore-basic/index.md deleted file mode 100644 index be627d2f11..0000000000 --- a/docs/projects/longest-common-subsequence/commodore-basic/index.md +++ /dev/null @@ -1,221 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-26 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2023-10-26 -layout: default -tags: -- commodore-basic -- longest-common-subsequence -title: Longest Common Subsequence in Commodore BASIC -title1: Longest Common Subsequence -title2: in Commodore BASIC ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(31) -15 REM Storage for lists -20 DIM L1(31), L2(31) -25 REM Storage for subsequences: -26 REM - C%(i, j, 0) contains length of subsequence -27 REM - C%(i, j, 1:2) contains bitmap indicating which indices of first list -28 REM are in the subsequence -30 DIM C%(32, 32, 2) -35 REM Bit 0 to 15 -40 DATA 1, 2, 4, 8, 16, 32, 64, 128 -50 DATA 256, 512, 1024, 2048, 4096, 8192, 16384, -32768 -60 DIM WM%(15) -70 FOR I = 0 TO 15 -80 READ WM%(I) -90 NEXT I -95 REM Get list 1 -100 GOSUB 2000 -110 IF V = 0 OR C >= 0 THEN 300: REM invalid or not end of input/value -120 M = NA -130 FOR I = 0 TO NA - 1 -140 L1(I) = A(I) -150 NEXT I -155 REM Get list 2 -160 GOSUB 2000 -170 IF V = 0 OR C >= 0 THEN 300: REM invalid or not end of input/value -180 N = NA -190 FOR I = 0 TO NA - 1 -200 L2(I) = A(I) -210 NEXT I -215 REM Find longest common subsequence and display -220 GOSUB 3000 -230 GOSUB 3500 -240 END -300 Q$ = CHR$(34): REM quote -310 PRINT "Usage: please provide two lists in the format "; -320 PRINT Q$; "1, 2, 3, 4, 5"; Q$ -330 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Longest common subsequence -3001 REM Source: -3002 REM https://en.wikipedia.org/wiki/Longest_common_subsequence#Example_in_C# -3003 REM Instead of storing just lengths, a bitmap indicating the indices of -3004 REM the first list is also stored -3005 REM Inputs: -3006 REM - L1 contains first list -3007 REM - M contains length of first list -3008 REM - L2 contains second list -3009 REM - N contains length of second list -3010 REM - WM% contains 16-bit words -3011 REM Outputs: -3012 REM - A contains subsequence -3013 REM - NA contains length of subsequence -3020 NA = 0 -3030 IF M < 1 OR N < 1 THEN RETURN: REM exit if empty lists -3035 REM Initialize all subsequences to an empty sequence -3040 NW = INT((M + 15) / 16): REM Number of 16-bit words -3050 FOR I = 0 TO M -3060 FOR J = 0 TO N -3070 FOR K = 0 TO NW -3080 C%(I, J, K) = 0 -3090 NEXT K -3100 NEXT J -3110 NEXT I -3115 REM Find the longest common subsequence using prior subsequences -3120 FOR I = 1 TO M -3130 FOR J = 1 TO N -3140 IF L1(I - 1) <> L2(J - 1) THEN GOTO 3230 -3145 REM If common element found, create new subsequence based on -3146 REM prior subsequence with the common element appended -3150 C%(I, J, 0) = C%(I - 1, J - 1, 0) + 1 -3160 FOR K = 1 TO NW -3170 C%(I, J, K) = C%(I - 1, J - 1, K) -3180 NEXT K -3190 WI = INT((I - 1) / 16): REM Word index -3200 BN = (I - 1) - 16 * WI: REM Bit number -3210 C%(I, J, WI + 1) = C%(I, J, WI + 1) OR WM%(BN) -3220 GOTO 3280 -3230 REM Else, reuse the longer of the two prior subsequences -3240 II = I - 1: JJ = J -3240 IF C%(I, J - 1, 0) > C%(I - 1, J, 0) THEN II = I: JJ = J - 1 -3250 FOR K = 0 TO NW -3260 C%(I, J, K) = C%(II, JJ, K) -3270 NEXT K -3280 NEXT J -3290 NEXT I -3295 REM Construct longest common subsequence from bitmap -3300 NA = 0 -3310 NL = -1 -3320 FOR WI = 0 TO NW - 1 -3330 FOR BN = 0 TO 15 -3340 NL = NL + 1 -3350 IF (C%(M, N, WI + 1) AND WM%(BN)) = 0 THEN GOTO 3380 -3360 A(NA) = L1(NL) -3370 NA = NA + 1 -3380 NEXT BN -3390 NEXT WI -3400 RETURN -3500 REM Display array -3501 REM A contains array -3502 REM NA contains size of array -3510 IF NA < 1 THEN GOTO 3590 -3520 FOR I = 0 TO NA - 1 -3530 S$ = STR$(A(I)) -3540 IF A(I) >= 0 THEN S$ = MID$(S$, 2): REM strip leading space -3550 PRINT S$; -3560 IF I < (NA - 1)THEN PRINT ", "; -3570 NEXT I -3580 PRINT -3590 RETURN - -``` - -{% endraw %} - -Longest Common Subsequence in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/elixir/index.md b/docs/projects/longest-common-subsequence/elixir/index.md deleted file mode 100644 index 5b7cad2033..0000000000 --- a/docs/projects/longest-common-subsequence/elixir/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Ann -- Jeremy Grifski -date: 2019-10-14 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2019-10-16 -layout: default -tags: -- elixir -- longest-common-subsequence -title: Longest Common Subsequence in Elixir -title1: Longest Common -title2: Subsequence in Elixir ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Elixir](/languages/elixir) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elixir -defmodule LongestCommonSubsequence do - def main() do - lcs = solve(System.argv()) - IO.puts("#{lcs}") - end - - def solve([as, bs]) when is_bitstring(as) and is_bitstring(bs) do - lcs(parse_string_to_list_integer(as), parse_string_to_list_integer(bs)) |> Enum.join(", ") - end - - def solve(_) do - print_usage() - end - - def print_usage() do - ~s(Usage: please provide two lists in the format "1, 2, 3, 4, 5") - end - - def lcs([], _) do - [] - end - - def lcs(_, []) do - [] - end - - def lcs([a | as], [b | bs]) when a == b do - [a] ++ lcs(as, bs) - end - - def lcs([a | as], [b | bs]) do - longest(lcs(as, [b | bs]), lcs([a | as], bs)) - end - - def longest(l1, l2) do - if Enum.count(l1) > Enum.count(l2) do - l1 - else - l2 - end - end - - def parse_string_to_list_integer(xs) do - xs - |> String.trim() - |> String.split(",") - |> Enum.map(&String.to_integer(String.trim(&1))) - end -end - -LongestCommonSubsequence.main() - -``` - -{% endraw %} - -Longest Common Subsequence in [Elixir](/languages/elixir) was written by: - -- Ann -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/euphoria/index.md b/docs/projects/longest-common-subsequence/euphoria/index.md deleted file mode 100644 index c94b2c945f..0000000000 --- a/docs/projects/longest-common-subsequence/euphoria/index.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-27 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2023-02-27 -layout: default -tags: -- euphoria -- longest-common-subsequence -title: Longest Common Subsequence in Euphoria -title1: Longest Common -title2: Subsequence in Euphoria ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/utils.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts(STDOUT, "Usage: please provide two lists in the format \"1, 2, 3, 4, 5\"\n") - abort(0) -end procedure - --- Longest Common Sequence --- Source: https://en.wikipedia.org/wiki/Longest_common_subsequence#Example_in_C# --- --- However, instead of storing lengths, a subsequence index is stored. --- Subsequences are stored in a separate array. The indices used for the --- "c" array in the above source are offset by 1 due to the fact that --- one-based instead of zero-based indexing must be used -function longest_common_subsequence(sequence list1, sequence list2) - -- Initialize all subsequences to an empty sequence - integer m = length(list1) - integer n = length(list2) - sequence c = repeat(repeat(1, n + 1), m + 1) - sequence subsequences = {{}} - - -- Find the longest common subsequence using prior subsequences - integer index1 - integer index2 - for i = 1 to m - do - for j = 1 to n - do - -- If common element found, create new subsequence based on prior - -- subsequence with the common element appended - if list1[i] = list2[j] - then - subsequences &= {subsequences[c[i][j]] & list1[i]} - c[i + 1][j + 1] = length(subsequences) - -- Else, reuse the longer of the two prior subsequences - else - index1 = c[i + 1][j] - index2 = c[i][j + 1] - c[i + 1][j + 1] = iif( - length(subsequences[index1]) > length(subsequences[index2]), - index1, - index2 - ) - end if - end for - end for - - return subsequences[c[m + 1][n + 1]] -end function - -procedure show_list_values(sequence values) - if length(values) > 0 - then - sequence format = repeat_pattern("%d, ", length(values)) - sequence s = sprintf(format[1..$-2], values) - printf(STDOUT, "%s\n", {s}) - end if -end procedure - --- Check command-line arguments -sequence argv = command_line() -if length(argv) < 5 or length(argv[4]) = 0 or length(argv[5]) = 0 -then - usage() -end if - --- Parse 1st and 2nd command-line arguments -sequence arg_nums = {4, 5} -sequence lists = {} -for k = 1 to 2 -do - sequence list_result = parse_int_list(argv[arg_nums[k]]) - lists &= {list_result[PARSE_INT_LIST_VALUES]} - if not list_result[PARSE_INT_LIST_VALID] - then - usage() - end if -end for - --- Get longest common subsequence and display it -sequence result = longest_common_subsequence(lists[1], lists[2]) -show_list_values(result) - -``` - -{% endraw %} - -Longest Common Subsequence in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/f-sharp/index.md b/docs/projects/longest-common-subsequence/f-sharp/index.md deleted file mode 100644 index 7a460a7402..0000000000 --- a/docs/projects/longest-common-subsequence/f-sharp/index.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-09 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-04-09 -layout: default -tags: -- f-sharp -- longest-common-subsequence -title: Longest Common Subsequence in F# -title1: Longest Common -title2: Subsequence in F# ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module LCS = - let private buildTable (s1: int[]) (s2: int[]) = - let m, n = s1.Length, s2.Length - let dp = Array2D.zeroCreate (m + 1) (n + 1) - - for i = 1 to m do - for j = 1 to n do - dp[i, j] <- - if s1[i - 1] = s2[j - 1] then - dp[i - 1, j - 1] + 1 - else - max dp[i - 1, j] dp[i, j - 1] - - dp - - let private backtrack (s1: int[]) (s2: int[]) (dp: int[,]) = - let rec loop i j acc = - match i, j with - | 0, _ | _, 0 -> acc - | _ when s1[i - 1] = s2[j - 1] -> loop (i - 1) (j - 1) (s1[i - 1] :: acc) - | _ when dp[i - 1, j] >= dp[i, j - 1] -> loop (i - 1) j acc - | _ -> loop i (j - 1) acc - - loop s1.Length s2.Length [] |> List.toArray - - let run (a: int[], b: int[]) = - let dp = buildTable a b - backtrack a b dp - - -module Helpers = - let usage = "Usage: please provide two lists in the format \"1, 2, 3, 4, 5\"" - - let private (|IntArray|_|) (s: string) = - let parts = s.Split(',', StringSplitOptions.RemoveEmptyEntries) - - let rec parseAll i acc = - if i = parts.Length then - Some(List.rev acc |> List.toArray) - else - match Int32.TryParse(parts[i].Trim()) with - | true, n -> parseAll (i + 1) (n :: acc) - | false, _ -> None - - if parts.Length = 0 then None else parseAll 0 [] - - let parseArgs argv = - match argv with - | [| IntArray numbers; IntArray target |] -> Ok(numbers, target) - | _ -> Error usage - - let handleResult = - function - | Ok result -> - let output = result |> Array.map string |> String.concat ", " - printfn "%s" output - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.map LCS.run |> Helpers.handleResult - -``` - -{% endraw %} - -Longest Common Subsequence in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/go/index.md b/docs/projects/longest-common-subsequence/go/index.md deleted file mode 100644 index b9392d6247..0000000000 --- a/docs/projects/longest-common-subsequence/go/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-03-17 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2019-03-25 -layout: default -tags: -- go -- longest-common-subsequence -title: Longest Common Subsequence in Go -title1: Longest Common -title2: Subsequence in Go ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "encoding/json" - "fmt" - "os" - "regexp" - "strconv" - "strings" -) - -func lcs(list1 []int, list2 []int) (lcsList []int) { - if len(list1) <= 0 || len(list2) <= 0 { - return - } - if list1[0] == list2[0] { - return append(lcs(list1[1:], list2[1:]), list1[0]) - } - return longest(lcs(list1, list2[1:]), lcs(list1[1:], list2)) -} - -func longest(list1 []int, list2 []int) []int { - if len(list1) > len(list2) { - return list1 - } - return list2 -} - -func reverse(list []int) (reversed []int) { - for i := len(list) - 1; i >= 0; i-- { - reversed = append(reversed, list[i]) - } - return -} -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - if len(list) < 2 { - exitWithError() - } - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} - -func exitWithError() { - fmt.Println("Usage: please provide two lists in the format \"1, 2, 3, 4, 5\"") - os.Exit(1) -} - -func sliceIntToString(list []int) (out string) { - bytes, _ := json.Marshal(list) - out = strings.Replace(string(bytes), ",", ", ", -1) - out = strings.Trim(out, "[]") - return -} - -func main() { - if len(os.Args) != 3 { - exitWithError() - } - - list1 := strToSliceInt(os.Args[1]) - list2 := strToSliceInt(os.Args[2]) - fmt.Println(sliceIntToString(reverse(lcs(list1, list2)))) -} - -``` - -{% endraw %} - -Longest Common Subsequence in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/haskell/index.md b/docs/projects/longest-common-subsequence/haskell/index.md deleted file mode 100644 index 8048b29516..0000000000 --- a/docs/projects/longest-common-subsequence/haskell/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-10-20 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2019-03-26 -layout: default -tags: -- haskell -- longest-common-subsequence -title: Longest Common Subsequence in Haskell -title1: Longest Common -title2: Subsequence in Haskell ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import System.Exit (exitWith, ExitCode(ExitFailure)) -import Data.List (intercalate) - --- Recursively find longest common subsequence -lcs :: Eq a => [a] -> [a] -> [a] -lcs [] bs = [] -lcs as [] = [] -lcs (a:as) (b:bs) - | a == b = (lcs as bs) ++ [a] - | otherwise = longest (lcs (a:as) bs) (lcs as (b:bs)) - - --- Returns the longer of two lists -longest :: Foldable t => t a -> t a -> t a -longest l1 l2 - | length l1 > length l2 = l1 - | otherwise = l2 - - --- Converts string in format "1, 2, 3" to a list of integers -stringToList :: String -> [Int] -stringToList str = read $ "[" ++ str ++ "]" :: [Int] - - -listToString :: [Int] -> String -listToString = intercalate ", " . map show - - -main :: IO () -main = do - args <- getArgs - let l1 = stringToList $ head args :: [Int] - let l2 = stringToList $ head $ tail args :: [Int] - if length args /= 2 then do - putStrLn "Usage: please provide two lists in the format \"1, 2, 3, 4, 5\"" - exitWith $ ExitFailure 1 - else - putStrLn $ listToString $ reverse $ lcs l1 l2 - -``` - -{% endraw %} - -Longest Common Subsequence in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/index.md b/docs/projects/longest-common-subsequence/index.md deleted file mode 100644 index 0c486a6760..0000000000 --- a/docs/projects/longest-common-subsequence/index.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -date: 2018-10-16 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- longest-common-subsequence -title: Longest Common Subsequence -title1: Longest Common -title2: Subsequence ---- - - - -Welcome to the Longest Common Subsequence page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Given two arrays of numbers, find the longest common subsequence. For example, let's say we have the -following pair of arrays: - -```python -A = [1, 4, 5, 3, 15, 6] -B = [1, 7, 4, 5, 11, 6] -``` - -The longest common subsequence is `1, 4, 5, 6`. - - -## Requirements - -Write a program which accepts two command line arguments--each list--and outputs the longest -common subsequence between the two lists. Input arguments should be in comma separated list notation: -`1, 2, 14, 11, 31, 7, 9`. - -Your program should be able to parse these lists into some internal representation in your -choice language (ideally an array). From there, the program should compare the two arrays -to find the longest common subsequence and output it in comma separated list notation to the user. - -The following is recursive pseudocode that you can use for reference: - -```python -LCS(arrayA, arrayB, indexA, indexB): - if indexA == 0 || indexB == 0: - return 0 - else if arrayA[indexA - 1] == arrayB[indexB - 1]: - return 1 + LCS(arrayA, arrayB, indexA - 1, indexB - 1) - else: - return max(LCS(arrayA, arrayB, indexA - 1, indexB), LCS(arrayA, arrayB, indexA, indexB - 1)) -``` - -Unfortunately, this pseudocode only gives us the length of the longest common subsequence. Since we -want to actually *print* the result, we'll probably need to augment this algorithm a bit. Also, -it may be useful to implement the memoized solution for the sake of efficiency. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Longest Common Subsequence. -In order to keep things simple, we split up the testing as follows: - -- Lcs Valid Tests -- Lcs Invalid Tests - -### Lcs Valid Tests - -| Description | Sequence 1 | Sequence 2 | Output | -| ----------- | ---------- | ---------- | ------ | -| Sample Input Same Length | "1, 4, 5, 3, 15, 6" | "1, 7, 4, 5, 11, 6" | "1, 4, 5, 6" | -| Sample Input Different Length | "1, 4, 8, 6, 9, 3, 15, 11, 6" | "1, 7, 4, 5, 8, 11, 6" | "1, 4, 8, 11, 6" | - -### Lcs Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Missing Input | "25 15 10 5" | - -All of these tests should output the following: - -``` -Usage: please provide two lists in the format "1, 2, 3, 4, 5" -``` - - -## Articles - -There are 30 articles: - -- [Longest Common Subsequence in ALGOL 60](/projects/longest-common-subsequence/algol60) -- [Longest Common Subsequence in ALGOL 68](/projects/longest-common-subsequence/algol68) -- [Longest Common Subsequence in AWK](/projects/longest-common-subsequence/awk) -- [Longest Common Subsequence in Ada](/projects/longest-common-subsequence/ada) -- [Longest Common Subsequence in Beef](/projects/longest-common-subsequence/beef) -- [Longest Common Subsequence in C](/projects/longest-common-subsequence/c) -- [Longest Common Subsequence in C#](/projects/longest-common-subsequence/c-sharp) -- [Longest Common Subsequence in C++](/projects/longest-common-subsequence/c-plus-plus) -- [Longest Common Subsequence in COBOL](/projects/longest-common-subsequence/cobol) -- [Longest Common Subsequence in Commodore BASIC](/projects/longest-common-subsequence/commodore-basic) -- [Longest Common Subsequence in Elixir](/projects/longest-common-subsequence/elixir) -- [Longest Common Subsequence in Euphoria](/projects/longest-common-subsequence/euphoria) -- [Longest Common Subsequence in F#](/projects/longest-common-subsequence/f-sharp) -- [Longest Common Subsequence in Go](/projects/longest-common-subsequence/go) -- [Longest Common Subsequence in Haskell](/projects/longest-common-subsequence/haskell) -- [Longest Common Subsequence in Java](/projects/longest-common-subsequence/java) -- [Longest Common Subsequence in JavaScript](/projects/longest-common-subsequence/javascript) -- [Longest Common Subsequence in Kotlin](/projects/longest-common-subsequence/kotlin) -- [Longest Common Subsequence in Mathematica](/projects/longest-common-subsequence/mathematica) -- [Longest Common Subsequence in PHP](/projects/longest-common-subsequence/php) -- [Longest Common Subsequence in Pascal](/projects/longest-common-subsequence/pascal) -- [Longest Common Subsequence in PowerShell](/projects/longest-common-subsequence/powershell) -- [Longest Common Subsequence in Python](/projects/longest-common-subsequence/python) -- [Longest Common Subsequence in Ruby](/projects/longest-common-subsequence/ruby) -- [Longest Common Subsequence in Rust](/projects/longest-common-subsequence/rust) -- [Longest Common Subsequence in Swift](/projects/longest-common-subsequence/swift) -- [Longest Common Subsequence in Tcl](/projects/longest-common-subsequence/tcl) -- [Longest Common Subsequence in TypeScript](/projects/longest-common-subsequence/typescript) -- [Longest Common Subsequence in Visual Basic](/projects/longest-common-subsequence/visual-basic) -- [Longest Common Subsequence in m4](/projects/longest-common-subsequence/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/java/index.md b/docs/projects/longest-common-subsequence/java/index.md deleted file mode 100644 index 634998d6b2..0000000000 --- a/docs/projects/longest-common-subsequence/java/index.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2022-05-16 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2022-05-16 -layout: default -tags: -- java -- longest-common-subsequence -title: Longest Common Subsequence in Java -title1: Longest Common -title2: Subsequence in Java ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -public class LongestCommonSubsequence { - - static ArrayList split_strings(String str) { - String word = ""; - char dl = ','; - - str = str + dl; - - ArrayList substr_list = new ArrayList<>(); - for (int i = 0; i < str.length(); i++) { - - if (str.charAt(i) != dl) - word = word + str.charAt(i); - else { - if ((int) word.length() != 0) - substr_list.add(word); - word = ""; - } - } - - return substr_list; - } - - static void longest_common_subsequence(ArrayList arr1, ArrayList arr2) { - - int[][] array = new int[arr1.size() + 1][arr2.size() + 1]; - - for (int i = 0; i < array.length; i++) { - for (int j = 0; j < array[0].length; j++) { - - if (i == 0 || j == 0) { - array[i][j] = 0; - } else if (arr1.get(i - 1).equals(arr2.get(j - 1))) { - array[i][j] = 1 + array[i - 1][j - 1]; - } else { - array[i][j] = Math.max(array[i - 1][j], array[i][j - 1]); - } - } - } - - ArrayList lcs = new ArrayList<>(); - int x = array.length - 1; - int y = array[0].length - 1; - - while (x > 0 && y > 0) { - - if (arr1.get(x - 1).equals(arr2.get(y - 1))) { - lcs.add(0, arr1.get(x - 1)); - x--; - y--; - } else { - if (array[x - 1][y] > array[x][y - 1]) - x--; - else - y--; - } - } - - for (int element = 0; element < lcs.size() - 1; element++) { - System.out.print(lcs.get(element) + ","); - } - System.out.println(lcs.get(lcs.size() - 1)); - } - - public static void main(String args[]) { - - if (args.length < 2 || args[0] == "" || args[1] == "") { - System.out.println("Usage: please provide two lists in the format \"1, 2, 3, 4, 5\""); - return; - } - - ArrayList arr1 = split_strings(args[0]); - ArrayList arr2 = split_strings(args[1]); - - longest_common_subsequence(arr1, arr2); - } -} - -``` - -{% endraw %} - -Longest Common Subsequence in [Java](/languages/java) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/javascript/index.md b/docs/projects/longest-common-subsequence/javascript/index.md deleted file mode 100644 index 55a6880461..0000000000 --- a/docs/projects/longest-common-subsequence/javascript/index.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -authors: -- Sayantan Sarkar -date: 2020-10-04 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2020-10-04 -layout: default -tags: -- javascript -- longest-common-subsequence -title: Longest Common Subsequence in JavaScript -title1: Longest Common Subsequence -title2: in JavaScript ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -/** - * Main Code for Longest Commmon Subsequence - * - * @param {Integer[]} arr1 - * @param {Integer[]} arr2 - */ - -function lcs(arr1, arr2) { - let matrix = [...Array(arr1.length +1)].fill(0).map(() => Array(arr2.length+1).fill(0)); - - for(let rowIndex=1; rowIndex<=arr1.length; rowIndex++){ - for(let columnIndex=1; columnIndex<=arr2.length; columnIndex++){ - if(arr1[rowIndex-1] === arr2[columnIndex-1]) { - matrix[rowIndex][columnIndex] = 1+matrix[rowIndex-1][columnIndex-1]; - }else{ - matrix[rowIndex][columnIndex] = Math.max(matrix[rowIndex-1][columnIndex],matrix[rowIndex][columnIndex-1]); - } - - } - } - //If there is no match, printing empty string - if(matrix[arr1.length][arr2.index]===0){ - console.log(""); - return; - } - - - let result = []; - let rowIndex = arr1.length; - let columnIndex = arr2.length; - - while(rowIndex > 0 && columnIndex > 0){ - if(arr1[rowIndex-1] === arr2[columnIndex-1]){ - //Prepending everytime a new character is matched in both strings - result.unshift(arr1[rowIndex-1]); - rowIndex--; - columnIndex--; - }else if(matrix[rowIndex-1][columnIndex] === matrix[rowIndex][columnIndex]){ - rowIndex--; - } - else{ - columnIndex--; - } - - } - //Converting the LCS array into a comma separated string - console.log(result.join(', ')); -} - -//Usage Text -const usage = `Usage: please provide two lists in the format "1, 2, 3, 4, 5"`; -if(process.argv.length <4 || process.argv[2] == "" || process.argv[3] == "") { - console.log(usage); - return; -} -else{ - const input1 = process.argv[2]; - const input2 = process.argv[3]; - //Parsing into integers after trimming extra blank spaces - const array1 = input1.split(',').map(x => parseInt(x.trim(),10)); - const array2 = input2.split(',').map(y => parseInt(y.trim(),10)); - lcs(array1,array2); -} - - -``` - -{% endraw %} - -Longest Common Subsequence in [JavaScript](/languages/javascript) was written by: - -- Sayantan Sarkar - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/kotlin/index.md b/docs/projects/longest-common-subsequence/kotlin/index.md deleted file mode 100644 index 4cfcae5f6a..0000000000 --- a/docs/projects/longest-common-subsequence/kotlin/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Blake.Ke -- David Phillips -date: 2020-10-05 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- kotlin -- longest-common-subsequence -title: Longest Common Subsequence in Kotlin -title1: Longest Common -title2: Subsequence in Kotlin ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin - -private fun lcsOf(a: MutableList, b: MutableList, indexA: Int, indexB: Int): MutableList { - return if (indexA < 0 || indexB < 0) { - mutableListOf() - } else if (a[indexA] == b[indexB]) { - // get the best subsequence of the rest, then add this one at the end (prevents needing to reverse at the end) - lcsOf(a, b, indexA - 1, indexB - 1).also { it.add(a[indexA] )} - } else { - // compare both subsequences and return the one that has more element - val subA = lcsOf(a, b, indexA, indexB - 1) - val subB = lcsOf(a, b, indexA - 1, indexB) - if (subA.size >= subB.size) subA else subB - } -} - -// only require consumers to pass in the lists... we'll handle the indices ourselves -fun lcsOf(a: List, b: List) = lcsOf(a.toMutableList(), b.toMutableList(), a.size - 1, b.size - 1) - -fun main(args: Array) { - if (args.size != 2 || args[0].isBlank() || args[1].isBlank()) { - // print and exit if we don't have the correct number of arguments - println("Usage: please provide two lists in the format \"1, 2, 3, 4, 5\"") - return - } - - // split each argument by comma, remove whitespace around each element, and pack them all in a list - val seqA = args[0].split(",").map { it.trim() } - val seqB = args[1].split(",").map { it.trim() } - - lcsOf(seqA, seqB).joinToString(", ").also { println(it) } -} - -``` - -{% endraw %} - -Longest Common Subsequence in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- David Phillips - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/m4/index.md b/docs/projects/longest-common-subsequence/m4/index.md deleted file mode 100644 index 5e7daab005..0000000000 --- a/docs/projects/longest-common-subsequence/m4/index.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-11-16 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2025-11-16 -layout: default -tags: -- longest-common-subsequence -- m4 -title: Longest Common Subsequence in m4 -title1: Longest Common -title2: Subsequence in m4 ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide two lists in the format "1, 2, 3, 4, 5" -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl 2D versions of "array_get" and "array_set" -dnl array2_get(varname, idx1, idx2) -define(`array2_get', `defn(format(``%s[%s][%s]'', `$1', `$2', `$3'))') - -dnl array2_set(varname, idx1, idx2, value) -define(`array2_set', `define(format(``%s[%s][%s]'', `$1', `$2', `$3'), `$4')') - -dnl array2_append(varname, idx1, value): -dnl varname[idx1][varname[idx1]["length"]] = value -dnl varname[idx1]["length"] = varname[idx1]["length"] + 1 -define(`array2_append', -`array2_set(`$1', `$2', array2_get(`$1', `$2', `length'), `$3')dnl -array2_set(`$1', `$2', `length', incr(array2_get(`$1', `$2', `length')))dnl -'dnl -) - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl show_int_list(varname): -dnl for i = 0 to n-1: -dnl if i > 0: -dnl Output ", " -dnl Output varname[i] -define(`show_int_list', `_show_int_list(`$1', 0)') -define(`_show_int_list', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`ifelse(eval($2 > 0), 1, `, ')dnl -array_get(`$1', $2)`'dnl -_show_int_list(`$1', incr($2))'`'dnl -)'dnl -) - -dnl Source: https://en.wikipedia.org/wiki/Longest_common_subsequence -dnl However, instead of storing lengths, an index to a subsequence is stored. -dnl longest_common_subsequence(list1_varname, list2_varname, c_varname, subseq_varname, result_varname): -dnl // Initialize all subsequences to an empty sequence -dnl m = list1_varname["length"] -dnl n = list2_varname["length"] -dnl for i = 0 to m: -dnl c_varname[i][0] = 0 -dnl -dnl for j = 0 to n: -dnl c_varname[0][j] = 0 -dnl -dnl subseq_varname[0]["length"] = 0 -dnl subseq_varname["length"] = 1 -dnl -dnl // Find the longest common subsequence using prior subsequences -dnl for i = 1 to m: -dnl for j = 1 to n: -dnl // If common element found, create new subsequence based on prior -dnl // subsequence with the common element appended -dnl if list1_varname[i - 1] == list2_varname[j - 1]: -dnl c_varname[i][j] = subseq_varname["length"] -dnl copy_array2(subseq_varname, c_varname[i - 1][j - 1], subseq_varname["length"]) -dnl array2_append(subseq_varname, subseq_varname["length"], list1_varname[i - 1]) -dnl subseq_varname[subseq_varname["length"]] = subseq_varname[subseq_varname["length"]] + 1 -dnl // Else, reuse the longer of the two prior subsequences -dnl else: -dnl idx1 = c_varname[i][j - 1] -dnl idx2 = c_varname[i - 1][j] -dnl if subseq_varname[idx1]["length"] > subseq_varname[idx2]["length"]: -dnl c_varname[i][j] = idx1 -dnl else: -dnl c_varname[i][j] = idx2 -dnl -dnl // Store result -dnl result_varname["length"] = subseq_varname[c_varname[m][n]]["length"] -dnl for i = 0 to result_varname["length"] - 1: -dnl result_varname[i] = subseq_varname[c_varname[m][n]][i] -define(`longest_common_subsequence', -`pushdef(`m', array_get(`$1', `length'))dnl -pushdef(`n', array_get(`$2', `length'))dnl -_lcs_init_c_col0(`$3', 0)dnl -_lcs_init_c_row0(`$3', 1)dnl -array2_set(`$4', 0, `length', 0)dnl -array_set(`$4', `length', 1)dnl -_lcs_outer(`$1', `$2', `$3', `$4', 1)dnl -_lcs_store_result(`$4', array2_get(`$3', m, n), `$5')dnl -popdef(`n')dnl -popdef(`m')dnl -'dnl -) - -dnl c_varname=$1, i=$2 -define(`_lcs_init_c_col0', -`ifelse(eval($2 <= m), 1, -`array2_set(`$1', `$2', 0, 0)dnl -_lcs_init_c_col0(`$1', incr($2))dnl -'dnl -)'dnl -) - -dnl c_varname=$1, j=$2 -define(`_lcs_init_c_row0', -`ifelse(eval($2 <= n), 1, -`array2_set(`$1', 0, `$2', 0)dnl -_lcs_init_c_row0(`$1', incr($2))dnl -'dnl -)'dnl -) - -dnl list1_varname=$1, list2_varname=$2, c_varname=$3, subseq_varname=$4, i=$5 -define(`_lcs_outer', -`ifelse(eval($5 <= m), 1, -`_lcs_inner(`$1', `$2', `$3', `$4', `$5', 1)dnl -_lcs_outer(`$1', `$2', `$3', `$4', incr($5))dnl -'dnl -)'dnl -) - -dnl list1_varname=$1, list2_varname=$2, c_varname=$3, subseq_varname=$4, i=$5, j=$6 -define(`_lcs_inner', -`ifelse(eval($6 <= n), 1, -`ifelse(eval(array_get(`$1', decr($5)) == array_get(`$2', decr($6))), 1, -`array2_set(`$3', `$5', `$6', array_get(`$4', `length'))dnl -copy_array2(`$4', array2_get(`$3', decr($5), decr($6)), array_get(`$4', `length'))dnl -array2_append(`$4', array_get(`$4', `length'), array_get(`$1', decr($5)))dnl -array_set(`$4', `length', incr(array_get(`$4', `length')))', -`pushdef(`idx1', array2_get(`$3', `$5', decr($6)))dnl -pushdef(`idx2', array2_get(`$3', decr($5), `$6'))dnl -ifelse(eval(array2_get(`$4', idx1, `length') > array2_get(`$4', idx2, `length')), 1, -`array2_set(`$3', `$5', `$6', idx1)', -`array2_set(`$3', `$5', `$6', idx2)'dnl -)dnl -popdef(`idx2')dnl -popdef(`idx1')dnl -'dnl -)dnl -_lcs_inner(`$1', `$2', `$3', `$4', `$5', incr($6))dnl -'dnl -)'dnl -) - -dnl copy_array2(arr2_varname, src_idx, dest_idx): -dnl arr2_varname[dest_idx]["length"] = arr2_varname[src_idx]["length"] -dnl for i = 0 to arr2_varname[src_idx]["length"] - 1 -dnl arr2_varname[dest_idx][i] = arr2_varname[src_idx][i] -define(`copy_array2', -`array2_set(`$1', `$3', `length', array2_get(`$1', `$2', `length'))dnl -_copy_array2(`$1', `$2', `$3', 0)dnl -'dnl -) - -dnl arr2_varname=$1, src_idx=$2, dest_idx=$3, i=$4 -define(`_copy_array2', -`ifelse(eval($4 < array2_get(`$1', `$2', `length')), 1, -`array2_set(`$1', `$3', `$4', array2_get(`$1', `$2', `$4'))dnl -_copy_array2(`$1', `$2', `$3', incr($4))dnl -')dnl -'dnl -) - -dnl subseq_varname=$1, src_idx=$2, result_varname=$3 -define(`_lcs_store_result', -`array_set(`$3', `length', array2_get(`$1', `$2', `length'))dnl -_lcs_store_result_inner(`$1', `$2', `$3', 0)dnl -'dnl -) - -dnl subseq_varname=$1, src_idx=$2, result_varname=$3, i=$4 -define(`_lcs_store_result_inner', -`ifelse(eval($4 < array_get(`$3', `length')), 1, -`array_set(`$3', `$4', array2_get(`$1', `$2', `$4'))dnl -_lcs_store_result_inner(`$1', `$2', `$3', incr($4))dnl -'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 2 || - !parse_int_list(`list1', ARGV1) || - !parse_int_list(`list2', ARGV2) -), 1, `show_usage()')dnl -longest_common_subsequence(`list1', `list2', `c', `subseq', `result')dnl -show_int_list(`result') - -``` - -{% endraw %} - -Longest Common Subsequence in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/mathematica/index.md b/docs/projects/longest-common-subsequence/mathematica/index.md deleted file mode 100644 index 6726fc336c..0000000000 --- a/docs/projects/longest-common-subsequence/mathematica/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-19 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2023-01-19 -layout: default -tags: -- longest-common-subsequence -- mathematica -title: Longest Common Subsequence in Mathematica -title1: Longest Common Subsequence -title2: in Mathematica ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Longest Common Subsequence option longestCommonSubsequence1 is just a Mathematica built-in - (note that Mathematica LongestCommonSubsequence searches only for contiguous subsequences): *) - -longestCommonSubsequence1 = LongestCommonSequence; - -(* If that is considered cheating, then option longestCommonSubsequence2 implements it directly: *) - -longestCommonSubsequence2 = Function[{l, r}, - (* if either list is empty, the LCS is also empty *) - If[Length[l] == 0 \[Or] Length[r] == 0, {}, - (* if first element of both lists match, recurse after removing that element *) - If[First[l] == First[r], - Prepend[longestCommonSubsequence2[Rest[l], Rest[r]], First[l]], - (* recurse by computing LCS of removing either first element from the left or from the right list *) - Module[{ll = longestCommonSubsequence2[Rest[l], r], rr = longestCommonSubsequence2[l, Rest[r]]}, - (* pick whichever produces the longest LCS *) - If[Length[ll] > Length[rr], ll, rr]]]]]; - -(* The outer function provides the 'user interface' (e.g., the string parsing): *) - -longestCommonSubsequenceMain = Function[{left, right}, - Module[{e = "Usage: please provide two lists in the format \"1,2,3,4,5\""}, - Catch[ - StringRiffle[ - longestCommonSubsequence2 @@ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct two arguments to longestCommonSubsequence: left list, right list *) - { - If[StringLength[left] > 0, StringSplit[left, ", "], Throw[e]], - If[StringLength[right] > 0, StringSplit[right, ", "], - Throw[e]] - }, - {-1} (* at each leaf *)], - ", "]]]]; - - -(* Valid Tests *) - -Print /@ Apply[longestCommonSubsequenceMain] /@ { - {"1, 4, 5, 3, 15, 6", "1, 7, 4, 5, 11, 6"}, - {"1, 4, 8, 6, 9, 3, 15, 11, 6", "1, 7, 4, 5, 8, 11, 6"} - }; - - -(* Invalid Tests *) - -longestCommonSubsequenceMain["3", ""] - -``` - -{% endraw %} - -Longest Common Subsequence in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/pascal/index.md b/docs/projects/longest-common-subsequence/pascal/index.md deleted file mode 100644 index 90fc4c8a8e..0000000000 --- a/docs/projects/longest-common-subsequence/pascal/index.md +++ /dev/null @@ -1,195 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- longest-common-subsequence -- pascal -title: Longest Common Subsequence in Pascal -title1: Longest Common -title2: Subsequence in Pascal ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program LongestCommonSubsequence; - -{$mode objfpc}{$H+} - -uses - Generics.Collections, - SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide two lists in the format "1, 2, 3, 4, 5"'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) = 0 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - - -function FormatIntegerList(const List: TIntegerList): string; -var - i: integer; - Builder: TStringBuilder; -begin - Builder := TStringBuilder.Create; - try - for i := 0 to List.Count - 1 do - begin - if i > 0 then - Builder.Append(', '); - Builder.Append(IntToStr(List[i])); - end; - Result := Builder.ToString; - finally - Builder.Free; - end; -end; - -function LongestCommonSubsequence(const A, B: TIntegerList): TIntegerList; -var - PreviousRow, CurrentRow: array of integer; - i, j: integer; -begin - if B.Count > A.Count then - Exit(LongestCommonSubsequence(B, A)); - - SetLength(PreviousRow, B.Count + 1); - SetLength(CurrentRow, B.Count + 1); - - // Build the DP table - for i := 1 to A.Count do - begin - for j := 1 to B.Count do - if A[i - 1] = B[j - 1] then - CurrentRow[j] := PreviousRow[j - 1] + 1 - else - if CurrentRow[j - 1] > PreviousRow[j] then - CurrentRow[j] := CurrentRow[j - 1] - else - CurrentRow[j] := PreviousRow[j]; - - PreviousRow := CurrentRow; - SetLength(CurrentRow, B.Count + 1); - end; - - // Reconstruct the LCS from the DP table - Result := TIntegerList.Create; - i := A.Count; - j := B.Count; - - while (i > 0) and (j > 0) do - if A[i - 1] = B[j - 1] then - begin - // If they match, append - Result.Add(A[i - 1]); - Dec(i); - Dec(j); - end - else if PreviousRow[j] > CurrentRow[j - 1] then - // Move up if the top cell has a greater value - Dec(i) - else - // Move left if the left cell has a greater value - Dec(j); - - Result.Reverse; -end; - - -var - ListA, ListB, LCSResult: TIntegerList; - i: integer; -begin - if ParamCount <> 2 then - ShowUsage; - - try - try - ListA := ParseIntegerList(ParamStr(1)); - ListB := ParseIntegerList(ParamStr(2)); - - if (ListA.Count = 0) or (ListB.Count = 0) then - ShowUsage; - - LCSResult := LongestCommonSubsequence(ListA, ListB); - - if LCSResult.Count = 0 then - Writeln('No common subsequence.') - else - Writeln(FormatIntegerList(LCSResult)); - except - on E: Exception do - ShowUsage; - end; - finally - ListA.Free; - ListB.Free; - LCSResult.Free; - end; -end. - -``` - -{% endraw %} - -Longest Common Subsequence in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/php/index.md b/docs/projects/longest-common-subsequence/php/index.md deleted file mode 100644 index 91f639d1d8..0000000000 --- a/docs/projects/longest-common-subsequence/php/index.md +++ /dev/null @@ -1,169 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2023-03-27 -layout: default -tags: -- longest-common-subsequence -- php -title: Longest Common Subsequence in PHP -title1: Longest Common -title2: Subsequence in PHP ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -// Longest Common Sequence -// Source: https://en.wikipedia.org/wiki/Longest_common_subsequence#Example_in_C# -// -// However, instead of storing lengths, and index to the subsequence is stored -function longest_common_subsequence($list1, $list2) -{ - // Initialize all subsequences to an empty sequence - $m = count($list1); - $n = count($list2); - $c = array_fill(0, $m + 1, array_fill(0, $n + 1, 0)); - $subsequences = array(array()); - - // Find the longest common subsequence using prior subsequences - for ($i = 1; $i <= $m; $i++) - { - for ($j = 1; $j <= $n; $j++) - { - // If common element found, create new subsequence based on prior - // subsequence with the common element appended - if ($list1[$i - 1] == $list2[$j - 1]) - { - $c[$i][$j] = count($subsequences); - array_push( - $subsequences, - array_merge( - $subsequences[$c[$i - 1][$j - 1]], - array($list1[$i - 1]) - ) - ); - } - // Else, reuse the longer of the two prior subsequences - else - { - $index1 = $c[$i][$j - 1]; - $index2 = $c[$i - 1][$j]; - $c[$i][$j] = - (count($subsequences[$index1]) > count($subsequences[$index2])) ? - $index1 : $index2; - } - } - } - - return $subsequences[$c[$m][$n]]; -} - -// Exit if too few arguments -if (count($argv) < 3) -{ - usage(); -} - -// Parse 1st and 2nd argument. Exit if invalid -$list1 = parse_int_array($argv[1]); -$list2 = parse_int_array($argv[2]); -if ($list1 === FALSE || $list2 === FALSE) -{ - usage(); -} - -// Get longest common subsequence and display it -$result = longest_common_subsequence($list1, $list2); -printf("%s\n", implode(", ", $result)); - -``` - -{% endraw %} - -Longest Common Subsequence in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/powershell/index.md b/docs/projects/longest-common-subsequence/powershell/index.md deleted file mode 100644 index 75fd25e8b9..0000000000 --- a/docs/projects/longest-common-subsequence/powershell/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-18 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2025-07-18 -layout: default -tags: -- longest-common-subsequence -- powershell -title: Longest Common Subsequence in PowerShell -title1: Longest Common Subsequence -title2: in PowerShell ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide two lists in the format "1, 2, 3, 4, 5"' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -# Source: https://en.wikipedia.org/wiki/Longest_common_subsequence -# However, instead of storing lengths, and index to the subsequence is stored -function Invoke-LongestCommonSubsequence([array]$List1, [array]$List2) { - # Initialize all subsequences to an empty sequence - $m = $List1.Length - $n = $List2.Length - $c = @(0..$m | ForEach-Object { , (@(0) * ($n + 1)) }) - $subsequences = @(, @()) - - # Find the longest common subsequence using prior subsequences - for ($i = 1; $i -le $m; $i++) { - for ($j = 1; $j -le $n; $j++) { - # If common element found, create new subsequence based on prior - # subsequence with the common element appended - if ($List1[$i - 1] -eq $List2[$j - 1]) { - $c[$i][$j] = $subsequences.Length - $subsequences += , ($subsequences[$c[$i - 1][$j - 1]] + $List1[$i - 1]) - } - # Else, reuse the longer of the two prior subsequences - else { - $index1 = $c[$i][$j - 1] - $index2 = $c[$i - 1][$j] - $c[$i][$j] = ($subsequences[$index1].Length -gt $subsequences[$index2].Length) ? - $index1 : $index2 - } - } - } - - $subsequences[$c[$m][$n]] -} - -if ($args.Length -lt 2 -or -not $args[0] -or -not $args[1]) { - Show-Usage -} - -try { - $list1 = Parse-IntList($args[0]) - $list2 = Parse-IntList($args[1]) -} catch { - Show-Usage -} - -$result = Invoke-LongestCommonSubsequence $list1 $list2 -Write-Output ($result -join ', ') - -``` - -{% endraw %} - -Longest Common Subsequence in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/python/index.md b/docs/projects/longest-common-subsequence/python/index.md deleted file mode 100644 index d95e9d1839..0000000000 --- a/docs/projects/longest-common-subsequence/python/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- Boot-Error -- Parker Johansen -date: 2018-10-16 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2019-03-21 -layout: default -tags: -- longest-common-subsequence -- python -title: Longest Common Subsequence in Python -title1: Longest Common -title2: Subsequence in Python ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] - - -def longest(s1, s2): - return s1 if len(s1) > len(s2) else s2 - - -def lcs(s1, s2): - if len(s1) == 0 or len(s2) == 0: - return [] - elif s1[-1] == s2[-1]: - return lcs(s1[:-1], s2[:-1]) + [s1[-1]] - elif s1[-1] != s2[-1]: - return longest(lcs(s1, s2[:-1]), lcs(s1[:-1], s2)) - - -def exit_with_error(): - print('Usage: please provide two lists in the format "1, 2, 3, 4, 5"') - sys.exit(1) - - -def main(args): - try: - lst1 = input_list(args[0]) - lst2 = input_list(args[1]) - print(lcs(lst1, lst2)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Longest Common Subsequence in [Python](/languages/python) was written by: - -- Boot-Error -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/ruby/index.md b/docs/projects/longest-common-subsequence/ruby/index.md deleted file mode 100644 index eb676da965..0000000000 --- a/docs/projects/longest-common-subsequence/ruby/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- longest-common-subsequence -- ruby -title: Longest Common Subsequence in Ruby -title1: Longest Common -title2: Subsequence in Ruby ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = 'Usage: please provide two lists in the format "1, 2, 3, 4, 5"' - -def usage! - warn USAGE - exit 1 -end - -def parse_list(str) - str.split(",").map { Integer(it.strip) } -rescue ArgumentError, NoMethodError - usage! -end - -def lcs(a, b) - n = a.size - m = b.size - - dp = Array.new(n + 1) { Array.new(m + 1, 0) } - - (1..n).each do |i| - (1..m).each do |j| - dp[i][j] = if a[i - 1] == b[j - 1] - dp[i - 1][j - 1] + 1 - else - [dp[i - 1][j], dp[i][j - 1]].max - end - end - end - - i, j = n, m - result = [] - - while i > 0 && j > 0 - if a[i - 1] == b[j - 1] - result << a[i - 1] - i -= 1 - j -= 1 - elsif dp[i - 1][j] >= dp[i][j - 1] - i -= 1 - else - j -= 1 - end - end - - result.reverse -end - -a_str, b_str = ARGV -usage! if a_str.nil? || b_str.nil? || a_str.strip.empty? || b_str.strip.empty? - -a = parse_list(a_str) -b = parse_list(b_str) - -puts lcs(a, b).join(", ") - -``` - -{% endraw %} - -Longest Common Subsequence in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/rust/index.md b/docs/projects/longest-common-subsequence/rust/index.md deleted file mode 100644 index 9190b4ac62..0000000000 --- a/docs/projects/longest-common-subsequence/rust/index.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-18 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- longest-common-subsequence -- rust -title: Longest Common Subsequence in Rust -title1: Longest Common -title2: Subsequence in Rust ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please provide two lists in the format \"1, 2, 3, 4, 5\""); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -type Matrix = Vec>; - -// Longest Common Sequence -// Source: https://en.wikipedia.org/wiki/Longest_common_subsequence#Example_in_C# -// -// However, instead of storing lengths, an index to the subsequence is stored -fn longest_common_subsequence(list1: &Vec, list2: &Vec) -> Vec -where - T: Copy + Clone + PartialEq -{ - // Initialize all subsequences to an empty sequence - let m = list1.len(); - let n = list2.len(); - let mut c: Matrix = vec![vec![0; n + 1]; m + 1]; - let mut subsequences: Matrix = vec![vec![]]; - - // Find the longest common subsequence using prior subsequences - for i in 1..=m { - for j in 1..=n { - // If common element found, create new subsequence based on prior - // subsequence with the common element appended - if list1[i - 1] == list2[j - 1] { - c[i][j] = subsequences.len(); - let mut new_subsequence = subsequences[c[i - 1][j - 1]].clone(); - new_subsequence.push(list1[i - 1]); - subsequences.push(new_subsequence); - } - // Else, reuse the longer of the two prior subsequences - else { - let index1 = c[i][j - 1]; - let index2 = c[i - 1][j]; - c[i][j] = if subsequences[index1].len() > subsequences[index2].len() { - index1 - } - else { - index2 - } - } - } - } - - subsequences[c[m][n]].clone() -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let list1: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 2nd command-line argument to list of integers - let list2: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Get longest common subsequence and display it - let result: Vec = longest_common_subsequence::(&list1, &list2); - println!("{result:?}"); -} - -``` - -{% endraw %} - -Longest Common Subsequence in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/swift/index.md b/docs/projects/longest-common-subsequence/swift/index.md deleted file mode 100644 index fbbfaf4cfe..0000000000 --- a/docs/projects/longest-common-subsequence/swift/index.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- longest-common-subsequence -- swift -title: Longest Common Subsequence in Swift -title1: Longest Common -title2: Subsequence in Swift ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide two lists in the format "1, 2, 3, 4, 5" - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseList(_ input: String?) -> [Int]? { - guard let input = input, !input.isEmpty else { return nil } - - let values = - input - .split(separator: ",") - .map { $0.trimmed } - .compactMap(Int.init) - - return values.isEmpty ? nil : values -} - -func parseInput(_ args: [String]) -> ([Int], [Int])? { - guard - let a = args.dropFirst().first, - let b = args.dropFirst().dropFirst().first, - let listA = parseList(a), - let listB = parseList(b) - else { - return nil - } - - return (listA, listB) -} - -func longestCommonSubsequence(_ a: [Int], _ b: [Int]) -> [Int] { - let n = a.count - let m = b.count - - var dp = Array( - repeating: Array(repeating: 0, count: m + 1), - count: n + 1 - ) - - for i in 1...n { - for j in 1...m { - if a[i - 1] == b[j - 1] { - dp[i][j] = dp[i - 1][j - 1] + 1 - } else { - dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) - } - } - } - - var result: [Int] = [] - var i = n - var j = m - - while i > 0 && j > 0 { - if a[i - 1] == b[j - 1] { - result.append(a[i - 1]) - i -= 1 - j -= 1 - } else if dp[i - 1][j] > dp[i][j - 1] { - i -= 1 - } else { - j -= 1 - } - } - - return result.reversed() -} - -guard let (a, b) = parseInput(CommandLine.arguments) else { - print(usage) - exit(1) -} - -let lcs = longestCommonSubsequence(a, b) -print(lcs.map(String.init).joined(separator: ", ")) - -``` - -{% endraw %} - -Longest Common Subsequence in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/tcl/index.md b/docs/projects/longest-common-subsequence/tcl/index.md deleted file mode 100644 index 106d543a61..0000000000 --- a/docs/projects/longest-common-subsequence/tcl/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- longest-common-subsequence -- tcl -title: Longest Common Subsequence in Tcl -title1: Longest Common -title2: Subsequence in Tcl ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 -package require struct::matrix - -proc usage {} { - puts stderr {Usage: please provide two lists in the format "1, 2, 3, 4, 5"} - exit 1 -} - -proc parseList {s} { - set result {} - foreach t [split $s ","] { - set t [string trim $t] - if {$t eq "" || [catch {expr {int($t)}} val]} { usage } - lappend result $val - } - return $result -} - -proc formatList {lst} { - return [join $lst ", "] -} - -proc decr {varName {by 1}} { - upvar 1 $varName v - set v [expr {$v - $by}] - return $v -} - -proc getCell {matrix i j} { - set v [eval $matrix get cell $j $i] - return [expr {($v eq "") ? 0 : $v}] -} - -proc longestCommonSubsequence {a b} { - set n [llength $a] - set m [llength $b] - - ::struct::matrix dp - dp add rows [expr {$n + 1}] - dp add columns [expr {$m + 1}] - - for {set row 1} {$row <= $n} {incr row} { - set valA [lindex $a [expr {$row - 1}]] - for {set col 1} {$col <= $m} {incr col} { - set valB [lindex $b [expr {$col - 1}]] - if {$valA eq $valB} { - set diag [getCell dp [expr {$row-1}] [expr {$col-1}]] - dp set cell $col $row [expr {$diag + 1}] - } else { - set top [getCell dp [expr {$row-1}] $col] - set left [getCell dp $row [expr {$col-1}]] - dp set cell $col $row [expr {max($top, $left)}] - } - } - } - - set lcs {} - set row $n - set col $m - while {$row > 0 && $col > 0} { - set valA [lindex $a [expr {$row - 1}]] - set valB [lindex $b [expr {$col - 1}]] - set top [getCell dp [expr {$row-1}] $col] - set left [getCell dp $row [expr {$col-1}]] - - if {$valA eq $valB} { - lappend lcs $valA - decr row; decr col - } elseif {$top >= $left} { - decr row - } else { - decr col - } - } - - return [lreverse $lcs] -} - -if {$argc != 2} { usage } - -set a [parseList [lindex $argv 0]] -set b [parseList [lindex $argv 1]] - -set lcs [longestCommonSubsequence $a $b] - -if {[llength $lcs] == 0} { - puts "No common subsequence." -} else { - puts [formatList $lcs] -} - - -``` - -{% endraw %} - -Longest Common Subsequence in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/typescript/index.md b/docs/projects/longest-common-subsequence/typescript/index.md deleted file mode 100644 index 718fe9b3c5..0000000000 --- a/docs/projects/longest-common-subsequence/typescript/index.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- longest-common-subsequence -- typescript -title: Longest Common Subsequence in TypeScript -title1: Longest Common Subsequence -title2: in TypeScript ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -"use strict"; - -function printUsage(): void { - console.error( - 'Usage: please provide two lists in the format "1, 2, 3, 4, 5"', - ); - process.exit(1); -} - -function parseInput(input: string | undefined): number[] | null { - if (!input || input.trim() === "") return null; - - const parts = input.split(",").map((s) => s.trim()); - const arr: number[] = []; - - for (const p of parts) { - if (p === "") return null; - - const val = Number.parseInt(p, 10); - if (Number.isNaN(val)) return null; - - arr.push(val); - } - - return arr; -} - -function lcs(arr1: number[], arr2: number[]): void { - const n = arr1.length; - const m = arr2.length; - - const dp: number[][] = Array.from({ length: n + 1 }, () => - Array(m + 1).fill(0), - ); - - for (let i = 1; i <= n; i++) { - for (let j = 1; j <= m; j++) { - if (arr1[i - 1] === arr2[j - 1]) { - dp[i][j] = 1 + dp[i - 1][j - 1]; - } else { - dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); - } - } - } - - const result: number[] = []; - let i = n; - let j = m; - - while (i > 0 && j > 0) { - if (arr1[i - 1] === arr2[j - 1]) { - result.push(arr1[i - 1]); - i--; - j--; - } else if (dp[i - 1][j] >= dp[i][j - 1]) { - i--; - } else { - j--; - } - } - - result.reverse(); - console.log(result.join(", ")); -} - -function main(): void { - const input1 = process.argv[2]; - const input2 = process.argv[3]; - - const arr1 = parseInput(input1); - const arr2 = parseInput(input2); - - if (!arr1 || !arr2) { - printUsage(); - } - - lcs(arr1!, arr2!); -} - -main(); - -``` - -{% endraw %} - -Longest Common Subsequence in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-common-subsequence/visual-basic/index.md b/docs/projects/longest-common-subsequence/visual-basic/index.md deleted file mode 100644 index 2f2785e6dc..0000000000 --- a/docs/projects/longest-common-subsequence/visual-basic/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: longest-common-subsequence-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- longest-common-subsequence -- visual-basic -title: Longest Common Subsequence in Visual Basic -title1: Longest Common Subsequence -title2: in Visual Basic ---- - - - -Welcome to the [Longest Common Subsequence](/projects/longest-common-subsequence) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System -Imports System.Collections.Generic - -Public Module LongestCommonSubsequence - - Public Sub Main(args As String()) - - If args.Length < 2 Then - ShowUsage() - Return - End If - - Dim list1 = Parse(args(0)) - Dim list2 = Parse(args(1)) - - If list1 Is Nothing OrElse list2 Is Nothing Then - ShowUsage() - Return - End If - - Dim result = LCS(list1, list2) - - Console.WriteLine(String.Join(", ", result)) - - End Sub - - - Private Function LCS(list1 As List(Of String), - list2 As List(Of String)) As List(Of String) - - If list1.Count = 0 OrElse list2.Count = 0 Then - Return New List(Of String) - End If - - If list1(0) = list2(0) Then - - Dim rest = LCS(list1.GetRange(1, list1.Count - 1), - list2.GetRange(1, list2.Count - 1)) - - rest.Insert(0, list1(0)) - Return rest - - End If - - Dim option1 = LCS(list1, list2.GetRange(1, list2.Count - 1)) - Dim option2 = LCS(list1.GetRange(1, list1.Count - 1), list2) - - Return If(option1.Count >= option2.Count, option1, option2) - - End Function - - - Private Function Parse(input As String) As List(Of String) - - If String.IsNullOrWhiteSpace(input) Then - Return Nothing - End If - - Dim result As New List(Of String) - - For Each part In input.Split(","c, StringSplitOptions.RemoveEmptyEntries) - result.Add(part.Trim()) - Next - - Return result - - End Function - - - Private Sub ShowUsage() - Console.WriteLine( - "Usage: please provide two lists in the format ""1, 2, 3, 4, 5""" - ) - Environment.Exit(1) - - End Sub - -End Module -``` - -{% endraw %} - -Longest Common Subsequence in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/ada/index.md b/docs/projects/longest-palindromic-substring/ada/index.md deleted file mode 100644 index c509b9f17f..0000000000 --- a/docs/projects/longest-palindromic-substring/ada/index.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-12 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-12 -layout: default -tags: -- ada -- longest-palindromic-substring -title: Longest Palindromic Substring in Ada -title1: Longest Palindromic -title2: Substring in Ada ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -pragma Ada_2022; - -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; - -procedure Longest_Palindromic_Substring is - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide a string that contains at least one palindrome"); - end Print_Usage; - - function LPS (S : String) return String is - N : constant Natural := S'Length; - - Transformed : String (1 .. 2 * N + 1); - Radius : array (1 .. 2 * N + 1) of Natural := (others => 0); - - Center : Natural := 1; - Right : Natural := 1; - - Best_Center : Natural := 1; - Best_Radius : Natural := 0; - - begin - -- build: #a#b#c# - Transformed (1) := '#'; - for I in 1 .. N loop - Transformed (2 * I) := S (I); - Transformed (2 * I + 1) := '#'; - end loop; - - for I in 2 .. Transformed'Last loop - - if I < Right then - Radius (I) := Natural'Min (Right - I, Radius (2 * Center - I)); - end if; - - while I + Radius (I) + 1 <= Transformed'Last - and then I - Radius (I) - 1 >= 1 - and then - Transformed (I + Radius (I) + 1) - = Transformed (I - Radius (I) - 1) - loop - Radius (I) := Radius (I) + 1; - end loop; - - if I + Radius (I) > Right then - Center := I; - Right := I + Radius (I); - end if; - - if Radius (I) > Best_Radius then - Best_Radius := Radius (I); - Best_Center := I; - end if; - - end loop; - - declare - Start : constant Natural := (Best_Center - Best_Radius) / 2; - begin - if Best_Radius < 2 then - return ""; - end if; - - return S (Start + 1 .. Start + Best_Radius); - end; - end LPS; - -begin - - if Argument_Count /= 1 then - Print_Usage; - return; - end if; - - declare - Input : constant String := Argument (1); - Result : constant String := LPS (Input); - begin - - if Input'Length = 0 or else Result'Length = 0 then - Print_Usage; - return; - else - Put_Line (Result); - end if; - - exception - when others => - Print_Usage; - end; - -end Longest_Palindromic_Substring; -``` - -{% endraw %} - -Longest Palindromic Substring in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/algol60/index.md b/docs/projects/longest-palindromic-substring/algol60/index.md deleted file mode 100644 index b9c69166dc..0000000000 --- a/docs/projects/longest-palindromic-substring/algol60/index.md +++ /dev/null @@ -1,203 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-10 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- algol60 -- longest-palindromic-substring -title: Longest Palindromic Substring in ALGOL 60 -title1: Longest Palindromic -title2: Substring in ALGOL 60 ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a string that contains at least one palindrome\n" - ); - stop - end usage; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - procedure outAsciiChar(ch); - value ch; - integer ch; - begin - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - outchar( - 1, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ) - end outAsciiChar; - - procedure outCharSubArray(s, left, right); - value left, right; - integer array s; - integer left, right; - begin - integer i; - for i := left step 1 until right do outAsciiChar(s[i]) - end outCharSubArray; - - comment Reference: - https://coderraj07.medium.com/expand-around-center-the-secret-weapon-for-palindrome-problems-b8e40171e538; - integer procedure longestPalindromicSubstring(s, len, left, right); - value len; - integer len, left, right; - integer array s; - begin - integer procedure expandAroundCenter(l, r); - integer l, r; - begin - comment Update left and right until out-of-bounds or non-matching - characters; - expandloop: - if l >= 1 & r <= len then - begin - if s[l] = s[r] then - begin - l := l - 1; - r := r + 1; - goto expandloop - end - end; - - comment Undo last left and right update; - l := l + 1; - r := r - 1; - expandAroundCenter := r - l + 1 - end expandAroundCenter; - - integer i, j, tempLeft, tempRight, tempLen, bestLen; - - comment Initialize left and right to start; - left := 1; - right := 1; - bestLen := 1; - - comment For each starting position (i); - for i := 1 step 1 until len do - begin - for j := 0 step 1 until 1 do - begin - comment Find longest palindromic substring for odd (j = 0) or - even (j = 1) length starting at position i; - tempLeft := i; - tempRight := i + j; - tempLen := expandAroundCenter(tempLeft, tempRight); - - comment Update left and right if longer palindromic substring found; - if tempLen > bestLen then - begin - left := tempLeft; - right := tempRight; - bestLen := tempLen - end - end - end; - - longestPalindromicSubstring := right - left + 1 - end longestPalindromicSubstring; - - integer argc, len, left, right, subLen; - integer array s[1:256]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get string as integer array. Exit if empty; - len := inCharArray(s, 256); - if len < 1 then usage; - - comment Find longest palindromic substring. Exit if length less than 2; - subLen := longestPalindromicSubstring(s, len, left, right); - if subLen < 2 then usage; - - comment Output longest palindromic substring; - outCharSubArray(s, left, right); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Longest Palindromic Substring in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/algol68/index.md b/docs/projects/longest-palindromic-substring/algol68/index.md deleted file mode 100644 index 3e15fc4ea3..0000000000 --- a/docs/projects/longest-palindromic-substring/algol68/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-13 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2023-02-13 -layout: default -tags: -- algol68 -- longest-palindromic-substring -title: Longest Palindromic Substring in ALGOL 68 -title1: Longest Palindromic -title2: Substring in ALGOL 68 ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -COMMENT -Find longest palindromic string using matching array -Source: https://www.geeksforgeeks.org/longest-palindromic-substring-using-dynamic-programming/ -COMMENT -PROC longest palindromic substring = (STRING s) STRING: -( - # Allocate array indicating whether there is a character match # - # between two characters # - INT n := UPB s; - HEAP [n, n]BOOL matches; - - # Indicate all length 1 strings match and everything else does not # - FOR i TO n - DO - FOR j TO n - DO - matches[i, j] := FALSE - OD; - - matches[i, i] := TRUE - OD; - - # Convert string to lowercase # - STRING t; - FOR i TO n - DO - t +:= tolower(s[i]) - OD; - - # Find all length 2 matches # - INT start := 1; - INT max len := 1; - FOR i TO n - 1 - DO - IF t[i] = t[i + 1] - THEN - matches[i, i + 1] := TRUE; - IF max len < 2 - THEN - start := i; - max len := 2 - FI - FI - OD; - - # Find all length 3 or higher matches # - INT j; - FOR len FROM 3 TO n - DO - # Loop through each starting character # - FOR i TO n - len + 1 - DO - # If match for one character in from start and end characters # - # and start and end characters match, set match for start and # - # end characters, and update max length # - j := i + len - 1; - IF matches[i + 1, j - 1] AND t[i] = t[j] - THEN - matches[i, j] := TRUE; - IF len > max len - THEN - max len := len; - start := i - FI - FI - OD - OD; - - s[start:start + max len - 1] -); - -PROC usage = VOID: printf(($gl$, "Usage: please provide a string that contains at least one palindrome")); - -# Error if 1st command-line argument is missing is empty # -STRING s := argv(4); -IF UPB(s) = 0 -THEN - usage; - stop -FI; - -# Get longest palindromic substring. Error if none found # -STRING longest := longest palindromic substring(s); -IF UPB(longest) < 2 -THEN - usage; - stop -FI; - -# Show longest palindromic substring # -printf(($gl$, longest)) - -``` - -{% endraw %} - -Longest Palindromic Substring in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/awk/index.md b/docs/projects/longest-palindromic-substring/awk/index.md deleted file mode 100644 index e9bc9aaa02..0000000000 --- a/docs/projects/longest-palindromic-substring/awk/index.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-28 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2025-04-28 -layout: default -tags: -- awk -- longest-palindromic-substring -title: Longest Palindromic Substring in AWK -title1: Longest Palindromic -title2: Substring in AWK ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a string that contains at least one palindrome" - exit(1) -} - -# Source: https://www.geeksforgeeks.org/longest-palindromic-substring-using-dynamic-programming/ -function longest_palindromic_substring(s, i, j, n, matches, t, start, max_len, len) { - # Indicate all length 1 strings match and everything else does not - n = length(s) - for (i = 1; i <= n; i++) { - for (j = 1; j <= n; j++) { - matches[i, j] = i == j - } - } - - # Convert string to lowercase - t = tolower(s) - - # Find all length 2 matches - start = 1 - max_len = 1 - for (i = 1; i < n; i++) { - if (substr(t, i, 1) == substr(t, i + 1, 1)) { - matches[i, i + 1] = 1 - if (max_len < 2) { - start = i - max_len = 2 - } - } - } - - # Find all length 3 or higher matches - for (len = 3; len <= n; len++) { - # Loop through each starting character - for (i = 1; i <= n - len + 1; i++) { - # If match for one character in from start and end characters - # and start and end characters match, set match for start and - # end characters, and update max length - j = i + len - 1 - if (matches[i + 1, j - 1] && substr(t, i, 1) == substr(t, j, 1)) { - matches[i, j] = 1 - if (len > max_len) { - max_len = len - start = i - } - } - } - } - - return substr(s, start, max_len) -} - -BEGIN { - if (ARGC < 2 || !ARGV[1]) { - usage() - } - - s = longest_palindromic_substring(ARGV[1]) - if (length(s) > 1) { - print s - } else { - usage() - } -} - -``` - -{% endraw %} - -Longest Palindromic Substring in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/beef/index.md b/docs/projects/longest-palindromic-substring/beef/index.md deleted file mode 100644 index cc0003e073..0000000000 --- a/docs/projects/longest-palindromic-substring/beef/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-11 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2024-02-11 -layout: default -tags: -- beef -- longest-palindromic-substring -title: Longest Palindromic Substring in Beef -title1: Longest Palindromic -title2: Substring in Beef ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace LongestPalindromicSubstring; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a string that contains at least one palindrome"); - Environment.Exit(0); - } - - // Find longest palindromic string using matching array - // Source: https://www.geeksforgeeks.org/longest-palindromic-substring-using-dynamic-programming/ - public static void LongestPalindromicSubstring(StringView str, String longest) - { - // Convert string to lowercase - String strLower = scope .(str) .. ToLower(); - - // Initialize character match matrix to indicate length 1 strings match - int n = str.Length; - bool [,] matches = scope .[n, n]; - for (int i < n) - { - matches[i, i] = true; - } - - // Find all length 2 matches - int start = 0; - int maxLen = 1; - for (int i < (n - 1)) - { - if (strLower[i] == strLower[i + 1]) - { - matches[i, i + 1] = true; - start = i; - maxLen = 2; - } - } - - // Find all length 3 or longer matches - for (int len in 3...n) - { - // Loop through each starting character - int j = len - 1; - for (int i in 0...(n - len)) - { - // If match for one character in from start and end characters - // and start and end characters match, set match for start and - // end characters, and update max length - if (matches[i + 1, j - 1] && strLower[i] == strLower[j]) - { - matches[i, j] = true; - if (len > maxLen) - { - start = i; - maxLen = len; - } - } - - j++; - } - } - - longest.Clear(); - longest.Append(str[start..<(start + maxLen)]); - } - - public static int Main(String[] args) - { - if (args.Count < 1 || args[0].Length < 1) - { - Usage(); - } - - String result = scope .(); - LongestPalindromicSubstring(args[0], result); - if (result.Length < 2) - { - Usage(); - } - - Console.WriteLine(result); - - return 0; - } -} - -``` - -{% endraw %} - -Longest Palindromic Substring in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/c-plus-plus/index.md b/docs/projects/longest-palindromic-substring/c-plus-plus/index.md deleted file mode 100644 index d9833c8304..0000000000 --- a/docs/projects/longest-palindromic-substring/c-plus-plus/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- Meet Thakur -- Ștefan-Iulian Alecu -date: 2025-10-11 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- longest-palindromic-substring -title: Longest Palindromic Substring in C++ -title1: Longest Palindromic -title2: Substring in C++ ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include - -std::string_view find_longest_palindrome(std::string_view s) { - if (s.empty()) return {}; - - std::string t; - t.reserve(s.size() * 2 + 3); - t += '^'; - for (const char c : s) { - t += '#'; - t += c; - } - t += "#$"; - - const int n = static_cast(t.size()); - std::vector radii(n, 0); - int center = 0; - int right_boundary = 0; - - for (int i = 1; i < n - 1; ++i) { - const int mirror = 2 * center - i; - - if (i < right_boundary) { - radii[i] = std::min(right_boundary - i, radii[mirror]); - } - - while (t[i + (1 + radii[i])] == t[i - (1 + radii[i])]) { - ++radii[i]; - } - - if (i + radii[i] > right_boundary) { - center = i; - right_boundary = i + radii[i]; - } - } - - const auto max_it = std::ranges::max_element(radii); - const int max_radius = *max_it; - const int center_idx = - static_cast(std::distance(radii.begin(), max_it)); - - return s.substr((center_idx - max_radius - 1) / 2, max_radius); -} - -[[noreturn]] void usage() { - std::cerr << "Usage: please provide a string that contains at least one " - "palindrome\n"; - std::exit(1); -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - std::string_view input{argv[1]}; - if (input.empty()) usage(); - - auto result = find_longest_palindrome(input); - - if (result.length() <= 1 && input.length() > 1) { - usage(); - } - - std::cout << result << "\n"; - return 0; -} -``` - -{% endraw %} - -Longest Palindromic Substring in [C++](/languages/c-plus-plus) was written by: - -- Meet Thakur -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/c-sharp/index.md b/docs/projects/longest-palindromic-substring/c-sharp/index.md deleted file mode 100644 index 223ef4bfab..0000000000 --- a/docs/projects/longest-palindromic-substring/c-sharp/index.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -authors: -- Maxwell Maslov -- Ștefan-Iulian Alecu -date: 2024-11-08 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- longest-palindromic-substring -title: Longest Palindromic Substring in C# -title1: Longest Palindromic -title2: Substring in C# ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not { Length: > 0 }) - return Usage(); - -string result = LongestPalindrome(string.Join(' ', args)); - -if (result.Length < 2) - return Usage(); - -Console.WriteLine(result); -return 0; - -static string LongestPalindrome(string input) -{ - int length = input.Length; - if (length < 2) - return ""; - - char[] transformed = new char[2 * length + 3]; - int[] radius = new int[transformed.Length]; - - int index = 0; - transformed[index++] = '^'; - - ReadOnlySpan source = input; - - foreach (char c in source) - { - transformed[index++] = '#'; - transformed[index++] = c; - } - - transformed[index++] = '#'; - transformed[index++] = '$'; - - int center = 0; - int rightBoundary = 0; - - int bestCenter = 0; - int bestRadius = 0; - - for (int i = 1; i < index - 1; i++) - { - int mirror = 2 * center - i; - int R = radius[i]; - - if (i < rightBoundary) - R = Math.Min(rightBoundary - i, radius[mirror]); - - while (transformed[i + R + 1] == transformed[i - R - 1]) - R++; - - radius[i] = R; - int expandedRight = i + R; - - center = expandedRight > rightBoundary ? i : center; - rightBoundary = Math.Max(expandedRight, rightBoundary); - - bool isBest = R > bestRadius; - bestRadius = isBest ? R : bestRadius; - bestCenter = isBest ? i : bestCenter; - } - - if (bestRadius < 2) - return ""; - - int startIndex = (bestCenter - bestRadius) / 2; - return input.AsSpan(startIndex, bestRadius).ToString(); -} - -static int Usage() -{ - Console.Error.WriteLine("Usage: please provide a string that contains at least one palindrome"); - return 1; -} - -``` - -{% endraw %} - -Longest Palindromic Substring in [C#](/languages/c-sharp) was written by: - -- Maxwell Maslov -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/c/index.md b/docs/projects/longest-palindromic-substring/c/index.md deleted file mode 100644 index ea4da915a1..0000000000 --- a/docs/projects/longest-palindromic-substring/c/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-19 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- longest-palindromic-substring -title: Longest Palindromic Substring in C -title1: Longest Palindromic -title2: Substring in C ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -#define MAX_LENGTH 1000 - -int expandAroundCenter(const char *s, int left, int right) -{ - while (left >= 0 && right < strlen(s) && s[left] == s[right]) - { - left--; - right++; - } - return right - left - 1; -} - -bool longestPalindromicSubstring(const char *s, char *result) -{ - if (s == NULL || strlen(s) == 0) - { - strcpy(result, ""); - return false; - } - - int start = 0, maxLength = 0; - int len = strlen(s); - - for (int i = 0; i < len; i++) - { - int len1 = expandAroundCenter(s, i, i); - int len2 = expandAroundCenter(s, i, i + 1); - int len = (len1 > len2) ? len1 : len2; - - if (len > maxLength) - { - start = i - (len - 1) / 2; - maxLength = len; - } - } - - if (maxLength > 1) - { - strncpy(result, s + start, maxLength); - result[maxLength] = '\0'; - return true; - } - - strcpy(result, ""); - return false; -} - -int main(int argc, char *argv[]) -{ - if (argc != 2) - { - printf("Usage: please provide a string that contains at least one " - "palindrome\n"); - return 1; - } - - const char *input = argv[1]; - char result[MAX_LENGTH]; - - if (longestPalindromicSubstring(input, result) && strlen(result) > 0) - { - printf("%s\n", result); - } - else - { - printf("Usage: please provide a string that contains at least one " - "palindrome\n"); - } - - return 0; -} - -``` - -{% endraw %} - -Longest Palindromic Substring in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/cobol/index.md b/docs/projects/longest-palindromic-substring/cobol/index.md deleted file mode 100644 index 4f8a5ffb1d..0000000000 --- a/docs/projects/longest-palindromic-substring/cobol/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- longest-palindromic-substring -title: Longest Palindromic Substring in COBOL -title1: Longest Palindromic -title2: Substring in COBOL ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. longest-palindromic-substring. - -data division. -working-storage section. - -01 ws-s pic x(200). -01 ws-len pic 9(4). - -01 ws-i pic 9(4). -01 ws-l pic 9(4). -01 ws-r pic 9(4). - -01 ws-best-l pic 9(4) value 0. -01 ws-best-r pic 9(4) value 0. -01 ws-best-len pic 9(4) value 0. -01 ws-r-len pic 9(4) value 0. - -01 ws-valid pic x value "y". - 88 is-valid value "y". - 88 is-invalid value "n". - -procedure division. - -main. - accept ws-s from argument-value - - if ws-s = spaces - perform show-usage - stop run - end-if - - move function length(function trim(ws-s)) to ws-len - - if ws-len = 0 - perform show-usage - stop run - end-if - - perform find-palindrome - - if ws-best-len < 2 - perform show-usage - stop run - end-if - - perform varying ws-i from ws-best-l by 1 until ws-i > ws-best-r - display ws-s(ws-i:1) with no advancing - end-perform - stop run. - -find-palindrome. - perform varying ws-i from 1 by 1 until ws-i > ws-len - - move ws-i to ws-l - move ws-i to ws-r - - perform expand - - move ws-i to ws-l - compute ws-r = ws-i + 1 - - perform expand - - end-perform. - -expand. - perform until ws-l < 1 or ws-r > ws-len - if ws-s(ws-l:1) not = ws-s(ws-r:1) - exit perform - end-if - - compute ws-l = ws-l - 1 - compute ws-r = ws-r + 1 - end-perform - - compute ws-l = ws-l + 1 - compute ws-r = ws-r - 1 - - compute ws-r-len = ws-r - ws-l + 1 - - if ws-r-len > ws-best-len - move ws-r-len to ws-best-len - move ws-l to ws-best-l - move ws-r to ws-best-r - end-if. - -show-usage. - display "Usage: please provide a string that contains at least one palindrome". - -``` - -{% endraw %} - -Longest Palindromic Substring in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/commodore-basic/index.md b/docs/projects/longest-palindromic-substring/commodore-basic/index.md deleted file mode 100644 index 63c4142b28..0000000000 --- a/docs/projects/longest-palindromic-substring/commodore-basic/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-14 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2023-10-14 -layout: default -tags: -- commodore-basic -- longest-palindromic-substring -title: Longest Palindromic Substring in Commodore BASIC -title1: Longest Palindromic Substring -title2: in Commodore BASIC ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM M%(99, 99): REM Match array -20 GOSUB 1000: REM Input string -30 IF S$ = "" THEN GOTO 200 -40 GOSUB 2000: REM Get longest palindromic substring -50 IF LEN(R$) < 2 THEN GOTO 200 -60 PRINT R$ -70 END -200 PRINT "Usage: please provide a string that contains at least "; -210 PRINT "one palindrome" -220 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 13 OR C = 255 THEN RETURN: REM end of value or input -1050 S$ = S$ + A$ -1060 GOTO 1020 -2000 REM Find longest palindromic substring using matching array -2001 REM Source: -2002 REM https://www.geeksforgeeks.org/ -2003 REM longest-palindromic-substring-using-dynamic-programming/ -2004 REM Inputs: S$ contains string -2005 REM Outputs: -2006 REM - R$ contains longest palindromic substring -2010 REM Indicate all length 1 strings match and everything else does not -2020 N = LEN(S$) -2030 ML% = 1: REM Maximum length -2040 SI% = 1: REM Start index -2050 IF N < 1 THEN GOTO 2420 -2060 FOR I = 0 TO N - 1 -2070 FOR J = 0 TO N - 1 -2080 M%(I, J) = 0 -2090 NEXT J -2100 M%(I, I) = 1 -2110 NEXT I -2120 REM Convert string to lowercase -2130 T$ = "" -2140 FOR I = 1 TO N -2150 C$ = MID$(S$, I, 1) -2160 IF C$ >= "A" AND C$ <= "Z" THEN C$ = CHR$(ASC(C$) + 32) -2170 T$ = T$ + C$ -2180 NEXT I -2190 REM Find all length 2 matches -2200 IF N < 2 THEN GOTO 2420 -2210 FOR I = 0 TO N - 2 -2220 IF MID$(T$, I + 1, 1) <> MID$(T$, I + 2, 1) THEN GOTO 2270 -2230 M%(I, I + 1) = 1 -2240 IF ML >= 2 THEN GOTO 2270 -2250 ML% = 2 -2260 SI% = I + 1 -2270 NEXT I -2280 REM Find all length 3 or higher matches -2290 IF N < 3 THEN GOTO 2420 -2300 FOR L = 3 TO N -2310 REM Loop through each starting character -2320 FOR I = 0 TO N - L -2330 J = I + L - 1 -2340 IF M%(I + 1, J - 1) = 0 THEN GOTO 2400 -2350 IF MID$(T$, I + 1, 1) <> MID$(T$, J + 1, 1) THEN GOTO 2400 -2360 M%(I, J) = 1 -2370 IF L <= ML% THEN GOTO 2400 -2380 ML% = L -2390 SI% = I + 1 -2400 NEXT I -2410 NEXT L -2420 R$ = MID$(S$, SI%, ML%) -2430 RETURN - -``` - -{% endraw %} - -Longest Palindromic Substring in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/euphoria/index.md b/docs/projects/longest-palindromic-substring/euphoria/index.md deleted file mode 100644 index dcec3f3258..0000000000 --- a/docs/projects/longest-palindromic-substring/euphoria/index.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-26 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2023-02-26 -layout: default -tags: -- euphoria -- longest-palindromic-substring -title: Longest Palindromic Substring in Euphoria -title1: Longest Palindromic -title2: Substring in Euphoria ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e - --- Find longest palindromic string using matching array --- Source: https://www.geeksforgeeks.org/longest-palindromic-substring-using-dynamic-programming/ -function longest_palindromic_substring(sequence s) - -- Initialize array indicating whether there is a character match - -- between two characters to indicate that nothing matches - integer n = length(s) - sequence matches = repeat(repeat(FALSE, n), n) - - -- Indicate all length 1 strings match - for i = 1 to n - do - matches[i][i] = TRUE - end for - - -- Convert string to lowercase - sequence t = lower(s) - - -- Find all length 2 matches - integer start = 1 - integer max_len = 1 - for i = 1 to n - 1 - do - if t[i] = t[i + 1] - then - matches[i][i+1] = TRUE - if max_len < 2 - then - start = i - max_len = 2 - end if - end if - end for - - -- Find all length 3 or higher matches - integer j - for len = 3 to n - do - -- Loop through each starting character - for i = 1 to n - len + 1 - do - -- If match for one character in from start and end characters - -- and start and end characters match, set match for start and - -- end characters, and update max length - j = i + len - 1 - if matches[i + 1][j - 1] and t[i] = t[j] - then - matches[i][j] = TRUE - if len > max_len - then - start = i - max_len = len - end if - end if - end for - end for - - return s[start..start + max_len - 1] -end function - -procedure usage() - puts(STDOUT, "Usage: please provide a string that contains at least one palindrome\n") - abort(0) -end procedure - --- Error if 1st command-line argument is missing is empty -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Get longest palindromic substring. Error if none found -sequence s = argv[4] -sequence longest = longest_palindromic_substring(s) -if length(longest) < 2 -then - usage() -end if - --- Show longest palindromic substring -printf(STDOUT, "%s\n", {longest}) - -``` - -{% endraw %} - -Longest Palindromic Substring in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/f-sharp/index.md b/docs/projects/longest-palindromic-substring/f-sharp/index.md deleted file mode 100644 index 0ad6bc2ac9..0000000000 --- a/docs/projects/longest-palindromic-substring/f-sharp/index.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- longest-palindromic-substring -title: Longest Palindromic Substring in F# -title1: Longest Palindromic -title2: Substring in F# ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System -open System.Text - -module LPS = - let private preprocess (s: string) = - let sb = StringBuilder("#", s.Length * 2 + 1) - s |> Seq.iter (fun ch -> sb.Append(ch).Append('#') |> ignore) - sb.ToString() - - let run (s: string) = - let t = preprocess s - let n = t.Length - let p = Array.zeroCreate n - - let mutable c, r = 0, 0 - - for i in 0 .. n - 1 do - let mirror = 2 * c - i - - if i < r then - p[i] <- min (r - i) p[mirror] - - let rec expand dist = - let left, right = i - (dist + 1), i + (dist + 1) - - if left >= 0 && right < n && t[left] = t[right] then - expand (dist + 1) - else - dist - - p[i] <- expand p[i] - - if i + p[i] > r then - c <- i - r <- i + p[i] - - let mutable maxLen = -1 - let mutable maxCenter = 0 - - for i in 0 .. n - 1 do - if p[i] > maxLen then - maxLen <- p[i] - maxCenter <- i - - s.Substring((maxCenter - maxLen) / 2, maxLen) - - -module Helpers = - let usage = "Usage: please provide a string that contains at least one palindrome" - - let private containsPalindrome (s: string) = - if isNull s || s.Length < 2 then false - else - // Check for adjacent duplicates (aa) or sandwiched characters (aba) - let rec check i = - if i >= s.Length - 1 then false - // Check for "aa" or "aba" seeds - elif s[i] = s[i + 1] || (i < s.Length - 2 && s[i] = s[i + 2]) then true - else check (i + 1) - - check 0 - - let parseArgs argv = - match argv with - | [| s |] when containsPalindrome s -> Ok s - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.map LPS.run |> Helpers.handleResult - -``` - -{% endraw %} - -Longest Palindromic Substring in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/go/index.md b/docs/projects/longest-palindromic-substring/go/index.md deleted file mode 100644 index f622209c13..0000000000 --- a/docs/projects/longest-palindromic-substring/go/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- izexi -date: 2020-10-26 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2020-10-26 -layout: default -tags: -- go -- longest-palindromic-substring -title: Longest Palindromic Substring in Go -title1: Longest Palindromic -title2: Substring in Go ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strings" -) - -const errorMessage = "Usage: please provide a string that contains at least one palindrome" - -func reverse(s string) string { - result := "" - for _, v := range s { - result = string(v) + result - } - return result -} - -func longestPalSubstr(str string) string { - result := "" - - if len(str) < 2 || str == "" { - return errorMessage - } - - for i := 1; i < len(str); i++ { - for j := 0; j < len(str)-i; j++ { - possiblePal := strings.ToLower(str[j : j+i+1]) - - if possiblePal == reverse(possiblePal) && len(possiblePal) > len(result) { - result = possiblePal - } - - } - } - - if len(result) == 0 { - result = errorMessage - } - return result -} - -func printSubStr(str string, low, high int) string { - s := "" - for i := low; i <= high; i++ { - s = s + string(str[i]) - } - - return s -} - -func main() { - if len(os.Args) < 2 { - fmt.Println(errorMessage) - } else { - fmt.Println(longestPalSubstr(os.Args[1])) - } -} - -``` - -{% endraw %} - -Longest Palindromic Substring in [Go](/languages/go) was written by: - -- izexi - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/haskell/index.md b/docs/projects/longest-palindromic-substring/haskell/index.md deleted file mode 100644 index fc19d1a2ad..0000000000 --- a/docs/projects/longest-palindromic-substring/haskell/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-11 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- haskell -- longest-palindromic-substring -title: Longest Palindromic Substring in Haskell -title1: Longest Palindromic -title2: Substring in Haskell ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Data.List (maximumBy, tails, inits) -import Data.Maybe (listToMaybe) -import Data.Function ((&)) -import Data.Ord (comparing) - -substrings :: [a] -> [[a]] -substrings = concatMap tails . inits - -longestPalindromicSubstring :: String -> Maybe String -longestPalindromicSubstring str = - case palindromes of - [] -> Nothing - _ -> Just $ maximumBy (comparing length) palindromes - where palindromes = substrings str & filter (\s -> length s > 1 && reverse s == s) - -main :: IO () -main = do - args <- getArgs - case listToMaybe args >>= longestPalindromicSubstring of - Nothing -> putStrLn "Usage: please provide a string that contains at least one palindrome" - Just res -> putStrLn res - -``` - -{% endraw %} - -Longest Palindromic Substring in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/index.md b/docs/projects/longest-palindromic-substring/index.md deleted file mode 100644 index 1a274a0343..0000000000 --- a/docs/projects/longest-palindromic-substring/index.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -date: 2020-10-17 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- longest-palindromic-substring -title: Longest Palindromic Substring -title1: Longest Palindromic -title2: Substring ---- - - - -Welcome to the Longest Palindromic Substring page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Palindrome is a phenomenon, where a string has same sequence of letters when read start --> end and end --> start. - -Let's say we have a string, - -``` -s = 'paapaapap' -``` - -Here, we have seven palindromic substrings. - -``` -sub_1 = 'aa' -sub_2 = 'paap' -sub_3 = 'paapaap' -sub_4 = 'aapaa' -sub_5 = 'apap' -sub_6 = 'pap' -sub_7 = 'apaapa' -``` - -Out of the seven, `sub_3 = 'paapaap'` is the longest. hence the output would be `'paapaap'` - - -## Requirements - -This problem can be solved using 3 methods. - -### Method 1 (Brute Force) - -The simple approach is to check each substring whether the substring is a palindrome or not. We can run three loops, the outer two loops pick all substrings one by one by fixing the corner characters, the inner loop checks whether the picked substring is palindrome or not. - -- Time complexity: O(n3) -- Auxiliary complexity: O(1) - -### Method 2 (Dynamic Programming) - -The time complexity can be reduced by storing results of subproblems. We maintain a boolean table[n][n] that is filled in bottom up manner. The value of table[i][j] is true, if the substring is palindrome, otherwise false. To calculate table[i][j], we first check the value of table[i+1][j-1], if the value is true and str[i] is same as str[j], then we make table[i][j] true. Otherwise, the value of table[i][j] is made false. - -- Time complexity: O(n2) -- Auxiliary Space: O(n2) - -### Method 3 - -The time complexity of the Dynamic Programming based solution is O(n2) and it requires O(n2) extra space. We can find the longest palindrome substring in O(n2) time with O(1) extra space. The idea is to generate all even length and odd length palindromes and keep track of the longest palindrome seen so far. - -#### Step to generate odd length palindrome: - -Fix a center and expand in both directions for longer palindromes. - -#### Step to generate even length palindrome - -Fix two center (low and high) and expand in both directions for longer palindromes. - -- Time complexity: O(n2) where n is the length of input string. -- Auxiliary Space: O(1) - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Longest Palindromic Substring. -In order to keep things simple, we split up the testing as follows: - -- Lps Valid Tests -- Lps Invalid Tests - -### Lps Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: One Palindrome | "racecar" | "racecar" | -| Sample Input: Two Palindrome | "kayak mom" | "kayak" | -| Sample Input: Complex Palindrome | "step on no pets" | "step on no pets" | - -### Lps Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: No Palindromes | "polip" | - -All of these tests should output the following: - -``` -Usage: please provide a string that contains at least one palindrome -``` - - -## Articles - -There are 28 articles: - -- [Longest Palindromic Substring in ALGOL 60](/projects/longest-palindromic-substring/algol60) -- [Longest Palindromic Substring in ALGOL 68](/projects/longest-palindromic-substring/algol68) -- [Longest Palindromic Substring in AWK](/projects/longest-palindromic-substring/awk) -- [Longest Palindromic Substring in Ada](/projects/longest-palindromic-substring/ada) -- [Longest Palindromic Substring in Beef](/projects/longest-palindromic-substring/beef) -- [Longest Palindromic Substring in C](/projects/longest-palindromic-substring/c) -- [Longest Palindromic Substring in C#](/projects/longest-palindromic-substring/c-sharp) -- [Longest Palindromic Substring in C++](/projects/longest-palindromic-substring/c-plus-plus) -- [Longest Palindromic Substring in COBOL](/projects/longest-palindromic-substring/cobol) -- [Longest Palindromic Substring in Commodore BASIC](/projects/longest-palindromic-substring/commodore-basic) -- [Longest Palindromic Substring in Euphoria](/projects/longest-palindromic-substring/euphoria) -- [Longest Palindromic Substring in F#](/projects/longest-palindromic-substring/f-sharp) -- [Longest Palindromic Substring in Go](/projects/longest-palindromic-substring/go) -- [Longest Palindromic Substring in Haskell](/projects/longest-palindromic-substring/haskell) -- [Longest Palindromic Substring in Java](/projects/longest-palindromic-substring/java) -- [Longest Palindromic Substring in JavaScript](/projects/longest-palindromic-substring/javascript) -- [Longest Palindromic Substring in Mathematica](/projects/longest-palindromic-substring/mathematica) -- [Longest Palindromic Substring in PHP](/projects/longest-palindromic-substring/php) -- [Longest Palindromic Substring in Pascal](/projects/longest-palindromic-substring/pascal) -- [Longest Palindromic Substring in PowerShell](/projects/longest-palindromic-substring/powershell) -- [Longest Palindromic Substring in Python](/projects/longest-palindromic-substring/python) -- [Longest Palindromic Substring in Ruby](/projects/longest-palindromic-substring/ruby) -- [Longest Palindromic Substring in Rust](/projects/longest-palindromic-substring/rust) -- [Longest Palindromic Substring in Swift](/projects/longest-palindromic-substring/swift) -- [Longest Palindromic Substring in Tcl](/projects/longest-palindromic-substring/tcl) -- [Longest Palindromic Substring in TypeScript](/projects/longest-palindromic-substring/typescript) -- [Longest Palindromic Substring in Visual Basic](/projects/longest-palindromic-substring/visual-basic) -- [Longest Palindromic Substring in m4](/projects/longest-palindromic-substring/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/java/index.md b/docs/projects/longest-palindromic-substring/java/index.md deleted file mode 100644 index 51aa5a337f..0000000000 --- a/docs/projects/longest-palindromic-substring/java/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Apurva Vats -date: 2025-10-30 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2025-10-30 -layout: default -tags: -- java -- longest-palindromic-substring -title: Longest Palindromic Substring in Java -title1: Longest Palindromic -title2: Substring in Java ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class LongestPalindromicSubstring { - - private static final String usage_msg = "Usage: please provide a string that contains at least one palindrome\n"; - - private static int expandAroundCenter(String s, int left, int right) { - while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { - left--; - right++; - } - return right - left - 1; - } - - private static boolean longestPalindromicSubstring(String s, StringBuilder result) { - if (s == null || s.isEmpty()) { - result.setLength(0); - return false; - } - - int start = 0, maxLength = 0; - int len = s.length(); - - for (int i = 0; i < len; i++) { - int len1 = expandAroundCenter(s, i, i); - int len2 = expandAroundCenter(s, i, i + 1); - int currLen = Math.max(len1, len2); - - if (currLen > maxLength) { - start = i - (currLen - 1) / 2; - maxLength = currLen; - } - } - - if (maxLength > 1) { - result.setLength(0); - result.append(s.substring(start, start + maxLength)); - return true; - } - - result.setLength(0); - return false; - } - - public static void main(String[] args) { - if (args.length != 1) { - System.out.print(usage_msg); - System.exit(1); - } - - String input = args[0]; - StringBuilder result = new StringBuilder(); - - if (longestPalindromicSubstring(input, result) && result.length() > 0) { - System.out.println(result); - } else { - System.out.print(usage_msg); - } - } -} - -``` - -{% endraw %} - -Longest Palindromic Substring in [Java](/languages/java) was written by: - -- Apurva Vats - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/javascript/index.md b/docs/projects/longest-palindromic-substring/javascript/index.md deleted file mode 100644 index 61fd9496c2..0000000000 --- a/docs/projects/longest-palindromic-substring/javascript/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- izexi -date: 2020-10-17 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2020-10-26 -layout: default -tags: -- javascript -- longest-palindromic-substring -title: Longest Palindromic Substring in JavaScript -title1: Longest Palindromic -title2: Substring in JavaScript ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const [, , input] = process.argv; - -const getLongestPalindromic = (string) => { - if (!string) return; - - let longestPal = ''; - - for (let i = 1; i < string.length; i++) { - for (let j = 0; j < string.length - i; j++) { - let possiblePal = string.substring(j, j + i + 1).toLowerCase(); - - if ( - possiblePal === [...possiblePal].reverse().join('') && - possiblePal.length > longestPal.length - ) - longestPal = possiblePal; - } - } - - return longestPal; -}; - -console.log( - getLongestPalindromic(input) || - 'Usage: please provide a string that contains at least one palindrome' -); -``` - -{% endraw %} - -Longest Palindromic Substring in [JavaScript](/languages/javascript) was written by: - -- izexi - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/m4/index.md b/docs/projects/longest-palindromic-substring/m4/index.md deleted file mode 100644 index 4d51032379..0000000000 --- a/docs/projects/longest-palindromic-substring/m4/index.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-25 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2025-08-31 -layout: default -tags: -- longest-palindromic-substring -- m4 -title: Longest Palindromic Substring in m4 -title1: Longest Palindromic -title2: Substring in m4 ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a string that contains at least one palindrome -m4exit(`1')') - -dnl longest_palindromic_substring(str) -dnl start = 0 -dnl max_len = 1 -dnl _lps_outer(str, 2) -dnl Return str[start:start+max_len-1] -define(`longest_palindromic_substring', -`pushdef(`start', 0)dnl -pushdef(`max_len', 1)dnl -_lps_outer(`$1', 2)dnl -substr(`$1', start, max_len)`'dnl -popdef(`max_len')dnl -popdef(`start')dnl -'dnl -) - -dnl _lps_outer(str, l) -dnl while l <= len(str): -dnl _lps_inner(str, 0, l) -dnl l = l + 1 -define(`_lps_outer', -`ifelse(eval($2 <= len(`$1')), 1, -`_lps_inner(`$1', 0, $2)dnl -_lps_outer(`$1', incr($2))'dnl -)'dnl -) - -dnl _lps_inner(str, k, l) -dnl while k <= len(str) - l and l > max_len: -dnl if is_palindrome(str, k, k+l-1): -dnl start = k -dnl max_len = l -dnl k = k + 1 -define(`_lps_inner', -`ifelse( -eval($2 <= len(`$1') - $3 && $3 > max_len), 1, -`ifelse( -eval(is_palindrome(`$1', $2, eval($2 + $3 - 1))), 1, -`define(`start', $2)dnl -define(`max_len', $3)'dnl -)dnl -_lps_inner(`$1', incr($2), $3)'dnl -)'dnl -) - -dnl is_palidrome(str, left, right) -dnl while left < right: -dnl if str[left] != str[right]: -dnl Return 0 -dnl left = left + 1 -dnl right = right - 1 -dnl Return 1 -define(`is_palindrome', -`ifelse( - eval($2 >= $3), 1, `1', - substr(`$1', $2, 1), substr(`$1', $3, 1), `is_palindrome(`$1', incr($2), decr($3))', `0'dnl -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1), 1, `show_usage()')dnl -define(`result', longest_palindromic_substring(ARGV1))dnl -ifelse(eval(len(result) < 2), 1, `show_usage()', `result') - -``` - -{% endraw %} - -Longest Palindromic Substring in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/mathematica/index.md b/docs/projects/longest-palindromic-substring/mathematica/index.md deleted file mode 100644 index a01476627b..0000000000 --- a/docs/projects/longest-palindromic-substring/mathematica/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-18 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2023-01-18 -layout: default -tags: -- longest-palindromic-substring -- mathematica -title: Longest Palindromic Substring in Mathematica -title1: Longest Palindromic -title2: Substring in Mathematica ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Brute force approach of generating all substrings and testing: *) - -longestPalindromicSubstring = word \[Function] First @ MaximalBy[ - Select[PalindromeQ][ - Flatten[Table[ - StringTake[word, {i, j}], - {i, 1, StringLength[word]}, {j, i + 1, StringLength[word]}], - 1]], - StringLength, - UpTo[1]]; - -(* The outer function provides the 'user interface' (e.g., the string parsing): *) - -longestPalindromicSubstringMain = Function[{s}, - Module[{e = "Usage: please provide a string that contains at least one palindrome"}, - Catch[ - longestPalindromicSubstring @ - If[StringLength[s] > 0, s, Throw[e]]]]]; - - -(* Valid Tests *) - -Print /@ longestPalindromicSubstringMain /@ { - "racecar", - "kayak mom", - "step on no pets" - }; - - -(* Invalid Tests *) - -longestPalindromicSubstringMain[""] - -``` - -{% endraw %} - -Longest Palindromic Substring in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/pascal/index.md b/docs/projects/longest-palindromic-substring/pascal/index.md deleted file mode 100644 index fa8ada429c..0000000000 --- a/docs/projects/longest-palindromic-substring/pascal/index.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- longest-palindromic-substring -- pascal -title: Longest Palindromic Substring in Pascal -title1: Longest Palindromic -title2: Substring in Pascal ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program LongestPalindromicSubstring; - -{$mode objfpc}{$H+} - -uses - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a string that contains at least one palindrome'); - Halt(1); -end; - -function PreprocessString(const s: string): string; -var - builder: TStringBuilder; - ch: char; -begin - builder := TStringBuilder.Create; - builder.Append('#'); - for ch in s do - begin - builder.Append(ch); - builder.Append('#'); - end; - Result := builder.ToString; -end; - -function LongestPalindromicSubstring(const s: string): string; -var - Processed: string; - PalindromeRadii: array of integer; - Center, RightBoundary, i, Mirror, LeftExpand, RightExpand, ProcessedLength: integer; - MaxPalindromeLength, MaxCenterIndex, OriginalStartIndex: integer; - - function Min(A, B: integer): integer; inline; - begin - Result := B; - if A < B then - Result := A; - end; - -begin - if s = '' then - Exit(''); - - Processed := PreprocessString(s); - ProcessedLength := Length(Processed); - SetLength(PalindromeRadii, ProcessedLength); - - Center := 0; - RightBoundary := 0; - MaxPalindromeLength := 0; - MaxCenterIndex := 0; - - for i := 0 to ProcessedLength - 1 do - begin - Mirror := 2 * Center - i; - if i < RightBoundary then - PalindromeRadii[i] := Min(RightBoundary - i, PalindromeRadii[Mirror]); - - LeftExpand := i + (1 + PalindromeRadii[i]); - RightExpand := i - (1 + PalindromeRadii[i]); - - while (LeftExpand < ProcessedLength) and (RightExpand >= 0) and - (Processed[LeftExpand + 1] = Processed[RightExpand + 1]) do - begin - Inc(PalindromeRadii[i]); - Inc(LeftExpand); - Dec(RightExpand); - end; - - if i + PalindromeRadii[i] > RightBoundary then - begin - Center := i; - RightBoundary := i + PalindromeRadii[i]; - end; - - if PalindromeRadii[i] > MaxPalindromeLength then - begin - MaxPalindromeLength := PalindromeRadii[i]; - MaxCenterIndex := i; - end; - end; - - OriginalStartIndex := ((MaxCenterIndex - MaxPalindromeLength) div 2) + 1; - Result := Copy(s, OriginalStartIndex, MaxPalindromeLength); -end; - -var - Input: string; - LongestPalindrome: string; -begin - if ParamCount <> 1 then - ShowUsage; - - Input := ParamStr(1); - - if Trim(Input) = '' then - ShowUsage; - - LongestPalindrome := LongestPalindromicSubstring(Input); - - if LongestPalindrome.Length = 1 then - ShowUsage; - - Writeln(LongestPalindrome); -end. - -``` - -{% endraw %} - -Longest Palindromic Substring in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/php/index.md b/docs/projects/longest-palindromic-substring/php/index.md deleted file mode 100644 index 02767a7b76..0000000000 --- a/docs/projects/longest-palindromic-substring/php/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- longest-palindromic-substring -- php -title: Longest Palindromic Substring in PHP -title1: Longest Palindromic -title2: Substring in PHP ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - $max_len) - { - $start = $i; - $max_len = $len; - } - } - } - } - - return substr($str, $start, $max_len); -} - -function usage() -{ - exit("Usage: please provide a string that contains at least one palindrome"); -} - -// Exit if 1st command-line argument is missing is empty -if (count($argv) < 2 || empty($argv[1])) -{ - usage(); -} - -// Get longest palindromic substring. Exit if none found -$str = $argv[1]; -$longest = longest_palindromic_substring($str); -if (strlen($longest) < 2) -{ - usage(); -} - -// Show longest palindromic substring -echo "$longest\n"; - -``` - -{% endraw %} - -Longest Palindromic Substring in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/powershell/index.md b/docs/projects/longest-palindromic-substring/powershell/index.md deleted file mode 100644 index 5cef886820..0000000000 --- a/docs/projects/longest-palindromic-substring/powershell/index.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-16 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2025-07-16 -layout: default -tags: -- longest-palindromic-substring -- powershell -title: Longest Palindromic Substring in PowerShell -title1: Longest Palindromic -title2: Substring in PowerShell ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide a string that contains at least one palindrome" - Exit 1 -} - -# Source: https://www.geeksforgeeks.org/longest-palindromic-substring-using-dynamic-programming/ -function Invoke-LongestPalindromicSubstring($Str) { - $lcStr = $Str.ToLower() - - # Initialize array indicating where match between two strings - $n = $Str.Length - $matches = @(1..$n | ForEach-Object { , (@($false) * $n) }) - - # Indicate all length 1 strings match - for ($i = 0; $i -lt $n; $i++) { - $matches[$i][$i] = $true - } - - # Find all length 2 matches - $start = 0 - $maxLen = 1 - for ($i = 0; $i -lt $n - 1; $i++) { - if ($lcStr[$i] -eq $lcStr[$i + 1]) { - $matches[$i][$i + 1] = $true - if ($maxLen -lt 2) { - $start = $i - $maxLen = 2 - } - } - } - - # Find all length 3 or higher matches - for ($len = 3; $len -le $n; $len++) { - # Loop through each starting character - for ($i = 0; $i -lt $n - $len + 1; $i++) { - # If match for one character in from start and end characters - # and start and end characters match, set match for start and - # end characters, and update max length - $j = $i + $len - 1 - if ($matches[$i + 1][$j - 1] -and $lcStr[$i] -eq $lcStr[$j]) { - $matches[$i][$j] = $true - if ($len -gt $maxLen) { - $start = $i - $maxLen = $len - } - } - } - } - - $Str.Substring($start, $maxLen) -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -$result = Invoke-LongestPalindromicSubstring $args[0] -if ($result.Length -lt 2) { - Show-Usage -} - -Write-Output $result - -``` - -{% endraw %} - -Longest Palindromic Substring in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/python/index.md b/docs/projects/longest-palindromic-substring/python/index.md deleted file mode 100644 index b1425dd8d7..0000000000 --- a/docs/projects/longest-palindromic-substring/python/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- izexi -date: 2020-10-26 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2020-10-26 -layout: default -tags: -- longest-palindromic-substring -- python -title: Longest Palindromic Substring in Python -title1: Longest Palindromic -title2: Substring in Python ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - -errorMessage = "Usage: please provide a string that contains at least one palindrome" - -def longestPalindrome(string): - longest = "" - string = string.lower() - - centres = [len(string) - 1] - for diff in range(1, len(string)): - centres.append(centres[0] + diff) - centres.append(centres[0] - diff) - - for centre in centres: - if (min(centre + 1, 2 * len(string) - 1 - centre) <= len(longest)): - break - if centre % 2 == 0: - left, right = (centre // 2) - 1, (centre // 2) + 1 - else: - left, right = centre // 2, (centre // 2) + 1 - - while left >= 0 and right < len( - string) and string[left] == string[right]: - left -= 1 - right += 1 - - if right - left > len(longest): - longest = string[left + 1:right] - - return longest - - -if __name__ == '__main__': - if (len(sys.argv) < 2): - print(errorMessage) - else: - string = sys.argv[1] - if string == "" or string == None: - print(errorMessage) - sub = longestPalindrome(string) - if len(sub) == 1: - print(errorMessage) - else: - print(sub) - -``` - -{% endraw %} - -Longest Palindromic Substring in [Python](/languages/python) was written by: - -- izexi - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/ruby/index.md b/docs/projects/longest-palindromic-substring/ruby/index.md deleted file mode 100644 index a507c7e9b9..0000000000 --- a/docs/projects/longest-palindromic-substring/ruby/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- longest-palindromic-substring -- ruby -title: Longest Palindromic Substring in Ruby -title1: Longest Palindromic -title2: Substring in Ruby ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def expand(s, l, r) - while l >= 0 && r < s.length && s[l] == s[r] - l -= 1 - r += 1 - end - - [l + 1, r - l - 1] # start, length -end - -def longest_palindromic_substring(s) - return if s.to_s.empty? - - best_start = 0 - best_len = 1 - - s.length.times do |i| - start1, len1 = expand(s, i, i) - start2, len2 = expand(s, i, i + 1) - - start, len = (len1 > len2) ? [start1, len1] : [start2, len2] - - if len > best_len - best_start, best_len = start, len - end - end - - s.slice(best_start, best_len) -end - -input = ARGV.first -result = longest_palindromic_substring(input) - -abort("Usage: please provide a string that contains at least one palindrome") if result.nil? || result.length <= 1 - -puts result - -``` - -{% endraw %} - -Longest Palindromic Substring in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/rust/index.md b/docs/projects/longest-palindromic-substring/rust/index.md deleted file mode 100644 index b044306f53..0000000000 --- a/docs/projects/longest-palindromic-substring/rust/index.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-17 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- longest-palindromic-substring -- rust -title: Longest Palindromic Substring in Rust -title1: Longest Palindromic -title2: Substring in Rust ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; - -fn usage() -> ! { - println!("Usage: please provide a string that contains at least one palindrome"); - exit(0); -} - -type Matrix = Vec>; - -// Find longest palindromic string using matching array -// Source: https://www.geeksforgeeks.org/longest-palindromic-substring-using-dynamic-programming/ -fn longest_palindromic_substring(s: &str) -> String { - // Initialize array indicating whether there is a character match - // between two characters to indicate that nothing matches - let n = s.len(); - let mut matches: Matrix = vec![vec![false; n]; n]; - - // Indicate all length 1 strings match - for i in 0..n { - matches[i][i] = true; - } - - // Convert string to a lowercase vector of characters - let chars: Vec = s - .to_lowercase() - .chars() - .collect(); - - // Find all length 2 matches - let mut start = 0; - let mut max_len = 1; - for i in 0..(n - 1) { - if chars[i] == chars[i + 1] { - matches[i][i + 1] = true; - start = i; - max_len = 2; - } - } - - // Find all length 3 or higher matches - for len in 3..=n { - // Loop through each starting character - for i in 0..(n - len + 1) { - // If match for one character in from start and end characters - // and start and end characters match, set match for start and - // end characters, and update max length - let j = i + len - 1; - if matches[i + 1][j - 1] && chars[i] == chars[j] { - matches[i][j] = true; - if len > max_len { - start = i; - max_len = len; - } - } - } - } - - chars[start..start + max_len] - .iter() - .collect() -} - -fn main() { - let mut args = args().skip(1); - - // Exit if 1st command-line argument is empty - let s: &str = &args - .next() - .unwrap_or_else(|| usage()); - if s.len() < 1 { - usage(); - } - - // Get longest palindromic substring. Error if none found - let longest = longest_palindromic_substring(s); - if longest.len() < 2 { - usage(); - } - - // Show longest palindromic substring - println!("{longest}"); -} - -``` - -{% endraw %} - -Longest Palindromic Substring in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/swift/index.md b/docs/projects/longest-palindromic-substring/swift/index.md deleted file mode 100644 index 943c792a08..0000000000 --- a/docs/projects/longest-palindromic-substring/swift/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- longest-palindromic-substring -- swift -title: Longest Palindromic Substring in Swift -title1: Longest Palindromic -title2: Substring in Swift ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a string that contains at least one palindrome - """ - -extension Collection { - subscript(safe index: Index) -> Element? { - indices.contains(index) ? self[index] : nil - } -} - -func findLongestPalindrome(_ s: String) -> String { - let originalChars = Array(s) - guard !originalChars.isEmpty else { return "" } - - let processed: [Character] = ["#"] + originalChars.flatMap { [$0, "#"] } - - let n = processed.count - var radii = Array(repeating: 0, count: n) - var center = 0 - var rightBoundary = 0 - - var maxRadius = 0 - var centerOfMax = 0 - - for i in 0..= 0 && right < n, processed[left] == processed[right] { - radii[i] += 1 - left -= 1 - right += 1 - } - - if i + radii[i] > rightBoundary { - center = i - rightBoundary = i + radii[i] - } - - if radii[i] > maxRadius { - maxRadius = radii[i] - centerOfMax = i - } - } - - guard maxRadius > 1 else { return "" } - - let start = (centerOfMax - maxRadius) / 2 - let resultRange = start..<(start + maxRadius) - - return String(originalChars[resultRange]) -} - -guard let input = CommandLine.arguments[safe: 1], !input.isEmpty else { - print(usage) - exit(1) -} - -let result = findLongestPalindrome(input) - -if result.isEmpty { - print(usage) - exit(1) -} else { - print(result) -} - -``` - -{% endraw %} - -Longest Palindromic Substring in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/tcl/index.md b/docs/projects/longest-palindromic-substring/tcl/index.md deleted file mode 100644 index eb2c712a44..0000000000 --- a/docs/projects/longest-palindromic-substring/tcl/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- longest-palindromic-substring -- tcl -title: Longest Palindromic Substring in Tcl -title1: Longest Palindromic -title2: Substring in Tcl ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a string that contains at least one palindrome} - exit 1 -} - -proc longestPalindromicSubstring {s} { - if {$s eq ""} { return "" } - - set processed "#[join [split $s ""] #]#" - set n [string length $processed] - set p [lrepeat $n 0] - - set center 0 - set right 0 - set maxLen 0 - set maxCenter 0 - - for {set i 0} {$i < $n} {incr i} { - set mirror [expr {2 * $center - $i}] - if {$i < $right} { - lset p $i [expr {min($right - $i, [lindex $p $mirror])}] - } - - while { - ($i + [lindex $p $i] + 1) < $n && - ($i - [lindex $p $i] - 1) >= 0 && - [string index $processed [expr {$i + [lindex $p $i] + 1}]] eq \ - [string index $processed [expr {$i - [lindex $p $i] - 1}]] - } { - lset p $i [expr {[lindex $p $i] + 1}] - } - - if {$i + [lindex $p $i] > $right} { - set center $i - set right [expr {$i + [lindex $p $i]}] - } - - if {[lindex $p $i] > $maxLen} { - set maxLen [lindex $p $i] - set maxCenter $i - } - } - - set start [expr {($maxCenter - $maxLen) / 2}] - - return [string range $s $start [expr {$start + $maxLen - 1}]] -} - -if {$argc != 1} { usage } - -set input [string trim [lindex $argv 0]] -if {$input eq ""} { usage } - -set result [longestPalindromicSubstring $input] -if {[string length $result] <= 1} { usage } - -puts $result - - -``` - -{% endraw %} - -Longest Palindromic Substring in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/typescript/index.md b/docs/projects/longest-palindromic-substring/typescript/index.md deleted file mode 100644 index acac7a27d0..0000000000 --- a/docs/projects/longest-palindromic-substring/typescript/index.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- longest-palindromic-substring -- typescript -title: Longest Palindromic Substring in TypeScript -title1: Longest Palindromic -title2: Substring in TypeScript ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function printUsage(): void { - console.error( - "Usage: please provide a string that contains at least one palindrome", - ); - process.exit(1); -} - -function preprocess(s: string): string { - // e.g. "abba" -> "^#a#b#b#a#$" - return "^#" + s.split("").join("#") + "#$"; -} - -function longestPalindromicSubstring(s: string): string | null { - if (!s) return null; - - const T = preprocess(s); - const n = T.length; - const P = new Array(n).fill(0); - - let C = 0; // center - let R = 0; // right boundary - - for (let i = 1; i < n - 1; i++) { - const mirror = 2 * C - i; - - if (i < R) { - P[i] = Math.min(R - i, P[mirror]); - } - - // expand around center i - while (T[i + 1 + P[i]] === T[i - 1 - P[i]]) { - P[i]++; - } - - // update center - if (i + P[i] > R) { - C = i; - R = i + P[i]; - } - } - - // find max palindrome - let maxLen = 0; - let centerIndex = 0; - - for (let i = 1; i < n - 1; i++) { - if (P[i] > maxLen) { - maxLen = P[i]; - centerIndex = i; - } - } - - if (maxLen === 0) return null; - - const start = (centerIndex - maxLen) >> 1; - return s.substring(start, start + maxLen); -} - -function main(): void { - const input = process.argv[2]; - - if (!input) { - printUsage(); - } - - const result = longestPalindromicSubstring(input); - if (!result || result?.length < 2) { - printUsage(); - } - - console.log(result); -} - -main(); - -``` - -{% endraw %} - -Longest Palindromic Substring in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-palindromic-substring/visual-basic/index.md b/docs/projects/longest-palindromic-substring/visual-basic/index.md deleted file mode 100644 index f7d728f4ce..0000000000 --- a/docs/projects/longest-palindromic-substring/visual-basic/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: longest-palindromic-substring-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- longest-palindromic-substring -- visual-basic -title: Longest Palindromic Substring in Visual Basic -title1: Longest Palindromic -title2: Substring in Visual Basic ---- - - - -Welcome to the [Longest Palindromic Substring](/projects/longest-palindromic-substring) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module LongestPalindromicSubstring - - Public Sub Main(args As String()) - - If args.Length <> 1 Then - Console.WriteLine("Usage: please provide a string that contains at least one palindrome") - Return - End If - - Dim input As String = args(0) - - If String.IsNullOrWhiteSpace(input) Then - Console.WriteLine("Usage: please provide a string that contains at least one palindrome") - Return - End If - - Dim result = LongestPalindrome(input) - If result.Length < 2 Then - Console.WriteLine("Usage: please provide a string that contains at least one palindrome") - Return - End If - - Console.WriteLine(result) - - End Sub - - - Public Function LongestPalindrome(s As String) As String - - Dim t As String = Preprocess(s) - - Dim n As Integer = t.Length - Dim p(n - 1) As Integer - - Dim center As Integer = 0 - Dim right As Integer = 0 - - Dim maxLen As Integer = 0 - Dim maxCenter As Integer = 0 - - For i As Integer = 1 To n - 2 - - Dim mirror As Integer = 2 * center - i - - If i < right Then - p(i) = Math.Min(right - i, p(mirror)) - End If - - While t(i + p(i) + 1) = t(i - p(i) - 1) - p(i) += 1 - End While - - If i + p(i) > right Then - center = i - right = i + p(i) - End If - - If p(i) > maxLen Then - maxLen = p(i) - maxCenter = i - End If - - Next - - Dim startIndex As Integer = (maxCenter - maxLen) \ 2 - Return s.Substring(startIndex, maxLen) - - End Function - - - Private Function Preprocess(s As String) As String - - Dim result As String = "^#" - - For Each c As Char In s - result &= c & "#" - Next - - result &= "$" - - Return result - - End Function - -End Module -``` - -{% endraw %} - -Longest Palindromic Substring in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/ada/index.md b/docs/projects/longest-word/ada/index.md deleted file mode 100644 index 62b3a30f49..0000000000 --- a/docs/projects/longest-word/ada/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-11 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- ada -- longest-word -title: Longest Word in Ada -title1: Longest -title2: Word in Ada ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -pragma Ada_2022; - -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; - -procedure Longest_Word is - function Is_Separator (Ch : Character) return Boolean - is (Ch = ' ' or else Ch = ASCII.LF or else Ch = ASCII.HT); - - function Longest_Word (S : String) return Natural is - Max_Len : Natural := 0; - Curr : Natural := 0; - begin - for Ch of S loop - if Is_Separator (Ch) then - Max_Len := Natural'Max (Max_Len, Curr); - Curr := 0; - else - Curr := @ + 1; - end if; - end loop; - - return Natural'Max (Max_Len, Curr); - end Longest_Word; - - procedure Print_Usage is - begin - Put_Line ("Usage: please provide a string"); - end Print_Usage; - -begin - if Argument_Count /= 1 then - Print_Usage; - return; - end if; - - declare - Input : constant String := Argument (1); - begin - if Input'Length = 0 then - Print_Usage; - return; - end if; - - Put_Line (Natural'Image (Longest_Word (Input))); - end; - -end Longest_Word; - -``` - -{% endraw %} - -Longest Word in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/algol60/index.md b/docs/projects/longest-word/algol60/index.md deleted file mode 100644 index 122a36519f..0000000000 --- a/docs/projects/longest-word/algol60/index.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-03 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-04-03 -layout: default -tags: -- algol60 -- longest-word -title: Longest Word in ALGOL 60 -title1: Longest Word -title2: in ALGOL 60 ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please provide a string\n"); - stop - end usage; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - integer procedure longestWord(s, len); - value len; - integer array s; - integer len; - begin - integer i, wordLen, maxWordLen, ch; - - wordLen := 0; - maxWordLen := 0; - for i := 1 step 1 until len do - begin - comment If whitespace, reset word length, else increment word length, - and update maximum if necessary; - ch := s[i]; - if ch = 9 | ch = 10 | ch = 13 | ch = 32 then wordLen := 0 - else - begin - wordLen := wordLen + 1; - if wordLen > maxWordLen then maxWordLen := wordLen - end - end; - - longestWord := maxWordLen - end longestWord; - - integer argc, len, maxWordLen; - integer array s[1:256]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get string as integer array. Exit if empty; - len := inCharArray(s, 256); - if len < 1 then usage; - - comment Get maximum word length and output it; - maxWordLen := longestWord(s, len); - outinteger(1, maxWordLen); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Longest Word in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/algol68/index.md b/docs/projects/longest-word/algol68/index.md deleted file mode 100644 index b075f7d1d2..0000000000 --- a/docs/projects/longest-word/algol68/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-24 -featured-image: longest-word-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- longest-word -title: Longest Word in ALGOL 68 -title1: Longest Word -title2: in ALGOL 68 ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC usage = VOID: printf(($gl$, "Usage: please provide a string")); - -PROC longest word length = (STRING s) INT: -( - INT longest word len := 0; - INT word len := 0; - FOR n TO UPB s - DO - # If whitespace, reset word length # - IF isspace(s[n]) - THEN - word len := 0 - # Else increment word length and update longest word length # - ELSE - word len +:= 1; - IF word len > longest word len - THEN - longest word len := word len - FI - FI - OD; - - longest word len -); - -# Get 1st command-line argument. Exit if empty # -STRING s := argv(4); -IF UPB s = 0 -THEN - usage; - stop -FI; - -INT longest word len := longest word length(s); -print((whole(longest word len, 0), newline)) - -``` - -{% endraw %} - -Longest Word in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/awk/index.md b/docs/projects/longest-word/awk/index.md deleted file mode 100644 index 1d150d5458..0000000000 --- a/docs/projects/longest-word/awk/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-14 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- longest-word -title: Longest Word in AWK -title1: Longest -title2: Word in AWK ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a string" - exit(1) -} - -function longest_word(s, len, max_len, k) { - split(s, arr, /\s+/) - max_len = 0 - for (k in arr) { - len = length(arr[k]) - if (len > max_len) { - max_len = len - } - } - - return max_len -} - -BEGIN { - if (ARGC < 2 || !ARGV[1]) { - usage() - } - - print longest_word(ARGV[1]) -} - -``` - -{% endraw %} - -Longest Word in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/beef/index.md b/docs/projects/longest-word/beef/index.md deleted file mode 100644 index cec045eaf9..0000000000 --- a/docs/projects/longest-word/beef/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-22 -featured-image: longest-word-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- longest-word -title: Longest Word in Beef -title1: Longest Word -title2: in Beef ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace LongestWord; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a string"); - Environment.Exit(0); - } - - public static int LongestWord(StringView str) - { - int maxLen = 0; - for (StringView word in str.Split(' ', '\t', '\r', '\n')) - { - maxLen = Math.Max(maxLen, word.Length); - } - - return maxLen; - } - - public static int Main(String[] args) - { - if (args.Count < 1 || args[0].Length < 1) - { - Usage(); - } - - int result = LongestWord(args[0]); - Console.WriteLine(result); - return 0; - } -} - -``` - -{% endraw %} - -Longest Word in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/brainfuck/index.md b/docs/projects/longest-word/brainfuck/index.md deleted file mode 100644 index 6082b302b8..0000000000 --- a/docs/projects/longest-word/brainfuck/index.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-22 -featured-image: longest-word-in-every-language.jpg -last-modified: 2023-12-22 -layout: default -tags: -- brainfuck -- longest-word -title: Longest Word in Brainfuck -title1: Longest Word -title2: in Brainfuck ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Brainfuck](/languages/brainfuck) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```brainfuck -[ - Source for comparing two numbers: - https://stackoverflow.com/questions/6168584/brainfuck-compare-2-numbers-as-greater-than-or-less-than - - Source for printing memory value as number: - https://esolangs.org/wiki/Brainfuck_algorithms#Print_value_of_cell_x_as_number_.288-bit.29 - - Source for error message - https://copy.sh/brainfuck/text.html -] -; Mem 0 = 1 (indicate no input) -+ -; Mem 1 = 0 (word length) -> -; Mem 2 = 0 (max word length) -> -; Mem 3 = input; Loop while input not null ->,[ - ; Mem 5 = 1 (assume whitespace) - >>+ - ; Mem 0 = 0 (indicate input) - <<<<<[-] - ; Sub 9 from Mem 3; If not zero (not tab) - >>>---------[ - ; Dec Mem 3; If not zero (not newline) - -[ - ; Sub 3 from Mem 3; If not zero (not carriage return) - ---[ - ; Sub 19 from Mem 3; If not zero (not space) - >[-]+++[ ; Mem 4 = 3 - <------ ; Sub 6 from Mem 3 - >- ; Dec Mem 4 - ] - <- ; Dec Mem 3 - [ - ; Inc Mem 1 (word length) - <<+ - ; Copy Mem 1 (word length) to Mem 7 and Mem 9; Mem 1 = 0 - [ - >>>>>>+ ; Inc Mem 7 - >>+ ; Inc Mem 9 - <<<<<<<<- ; Dec Mem 1 - ] - ; Copy Mem 2 (max word length) to Mem 6 and 10; Mem 2 = 0 - >[ - >>>>+ ; Inc Mem 6 - >>>>+ ; Inc Mem 10 - <<<<<<<<- ; Dec Mem 2 - ] - ; Mem 3 = 0 - >[-] - ; Mem 4 = 1 - >+ - ; Mem 5 = 0 - >- - ; Mem 8 = 0 - >>>[-] - ; If Mem 6 (max word length) less than Mem 7 (word length); - ; pointer is 6; Mem 6 is 0; Mem 7 is word length minus max word length; - ; else pointer is 5; Mem 5 is 0; Mem 6 is max word length minus word length - <+<+[->-[>]<<] - ; If less than - <<[ - ; Increment Mem 10 (max word length) - >>>>>>+ - ; Move pointer to Mem 3 - <<<<<<< - ] - ; Mem 6 = 0 - >>>[-] - ; Mem 7 = 0 - >[-] - ; Copy Mem 9 (word length) back to Mem 1; Mem 9 = 0 - >>[ - <<<<<<<<+ ; Inc Mem 1 - >>>>>>>>- ; Dec Mem 9 - ] - ; Copy Mem 10 (max word length) back to Mem 2; Mem 10 = 0 - >[ - <<<<<<<<+ ; Inc Mem 2 - >>>>>>>>- ; Dec Mem 10 - ] - ; Set pointer to Mem 3 - <<<<<<< - ] - ] - ] - ] - - ; If Mem 5 not zero (whitespace) - >>[ - ; Mem 1 = 0 (word length) - <<<<[-] - - ; Mem 5 = 0 - >>>>[-] - ] - ; Mem 4 = 0 - <[-] - ; Mem 3 = input - <, -] -; If Mem 2 (max word length) not zero -<[ - ; Display it as a number - >>++++++++++<<[->+>-[>+>>]>[+[-<+>]>+>>]<<<<<<]>>[-]>>>++++++++++<[->-[>+>>]>[+[- - <+>]>+>>]<<<<<]>[-]>>[>++++++[-<++++++++>]<.<<+>+>[-]]<[<[->-<]++++++[->++++++++ - <]>.[-]]<<++++++[-<++++++++>]<.[-]<<[-<+>]< - ; Clear it - [-] -] -; If no input; display error message -<<[ - [-] - -[--->+<]>. - +[--->+<]>+. - ++[->+++<]>++. - ++++++. - --. - +++[->+++<]>++. - [-->+<]>+++. - [-->+++++++<]>. - ----. - -------. - ----. - --[--->+<]>--. - ++++[->+++<]>. - --[--->+<]>-. - [-->+++++++<]>. - ++. - ---. - +++++++. - [------>+<]>. - -----. - +. - --[--->+<]>-. - [->+++<]>+. - -[->+++<]>. - ---[->++++<]>-. - +. - --. - ---------. - +++++. - -------. - [-] -] - -``` - -{% endraw %} - -Longest Word in [Brainfuck](/languages/brainfuck) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/c-plus-plus/index.md b/docs/projects/longest-word/c-plus-plus/index.md deleted file mode 100644 index 0174753850..0000000000 --- a/docs/projects/longest-word/c-plus-plus/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Jeremy Grifski -- sachchu007 -- Ștefan-Iulian Alecu -date: 2022-10-02 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- longest-word -title: Longest Word in C++ -title1: Longest -title2: Word in C++ ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please provide a string\n"; - std::exit(1); -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - std::string_view input = argv[1]; - if (input.empty()) usage(); - - auto is_space = [](unsigned char c) { return std::isspace(c) != 0; }; - - size_t best = 0; - size_t cur = 0; - - for (unsigned char c : input) { - if (is_space(c)) { - best = std::max(best, cur); - cur = 0; - } else { - ++cur; - } - } - - std::cout << std::max(best, cur) << '\n'; -} -``` - -{% endraw %} - -Longest Word in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- sachchu007 -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/c-sharp/index.md b/docs/projects/longest-word/c-sharp/index.md deleted file mode 100644 index a273177cfc..0000000000 --- a/docs/projects/longest-word/c-sharp/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- f3liz -- Ștefan-Iulian Alecu -date: 2024-11-08 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- longest-word -title: Longest Word in C# -title1: Longest -title2: Word in C# ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var sentence] || string.IsNullOrWhiteSpace(sentence)) - return Usage(); - -int max = 0, - cur = 0; - -foreach (char c in sentence) -{ - if (char.IsWhiteSpace(c)) - { - cur = 0; - continue; - } - - cur++; - max = Math.Max(cur, max); -} - -Console.WriteLine(max); -return 0; - -static int Usage() -{ - Console.Error.WriteLine("Usage: please provide a string"); - return 1; -} - -``` - -{% endraw %} - -Longest Word in [C#](/languages/c-sharp) was written by: - -- f3liz -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/c/index.md b/docs/projects/longest-word/c/index.md deleted file mode 100644 index 16fd1238d9..0000000000 --- a/docs/projects/longest-word/c/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- sachchu007 -- Ștefan-Iulian Alecu -date: 2022-10-08 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- longest-word -title: Longest Word in C -title1: Longest -title2: Word in C ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -void error() -{ - printf("Usage: please provide a string\n"); - exit(0); -} - -int main(int argc, char *argv[]) -{ - if (argc < 2 || strlen(argv[1]) <= 0) - error(); - - int max = -1; - char *word = strtok(argv[1], " ,\n\t"); - while (word != NULL) - { - int len = strlen(word); - if (len > max) - max = len; - word = strtok(NULL, " ,\n\t"); - } - - printf("%d", max); - - return 0; -} - -``` - -{% endraw %} - -Longest Word in [C](/languages/c) was written by: - -- sachchu007 -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/cobol/index.md b/docs/projects/longest-word/cobol/index.md deleted file mode 100644 index fb2cf8c09d..0000000000 --- a/docs/projects/longest-word/cobol/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- longest-word -title: Longest Word in COBOL -title1: Longest Word -title2: in COBOL ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. longest-word. - -data division. -working-storage section. - -01 ws-input pic x(200). -01 ws-temp pic x(200). -01 ws-pos pic 9(4) value 1. - -01 ws-word-len pic 9(4) value 0. -01 ws-max-len pic 9(4) value 0. - -01 ws-char pic x. - -01 ws-valid pic x value "y". - 88 is-valid value "y". - 88 is-invalid value "n". -01 ws-out-num pic -(9)9. - -procedure division. - -main. - accept ws-input from argument-value - - if ws-input = spaces - perform show-usage - stop run - end-if - - perform compute-max - - move ws-max-len to ws-out-num - display function trim(ws-out-num) - stop run. - - -compute-max. - move 1 to ws-pos - move 0 to ws-word-len - move 0 to ws-max-len - - perform until ws-pos > function length(function trim(ws-input)) - - move ws-input(ws-pos:1) to ws-char - - if ws-char = " " or ws-char = x"09" or ws-char = x"0A" or ws-char = x"0D" - compute ws-max-len = function max(ws-word-len, ws-max-len) - move 0 to ws-word-len - else - add 1 to ws-word-len - end-if - - add 1 to ws-pos - - end-perform - - if ws-word-len > ws-max-len - move ws-word-len to ws-max-len - end-if. - - -show-usage. - display "Usage: please provide a string". -``` - -{% endraw %} - -Longest Word in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/coffeescript/index.md b/docs/projects/longest-word/coffeescript/index.md deleted file mode 100644 index c8d95a1fd5..0000000000 --- a/docs/projects/longest-word/coffeescript/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- stefanurkal -date: 2024-12-08 -featured-image: longest-word-in-every-language.jpg -last-modified: 2024-12-08 -layout: default -tags: -- coffeescript -- longest-word -title: Longest Word in CoffeeScript -title1: Longest Word in -title2: CoffeeScript ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -findLongestWord = (inputString) -> - - return usage() if not inputString - - words = inputString.split(/[" "\n]+/) # Split the input string into words - - longestWord = "" - - for word in words - if word.length > longestWord.length - longestWord = word - - return longestWord.length - -usage = () -> - "Usage: please provide a string" - -main = () -> - args = process.argv - return findLongestWord(args[2]) - - -console.log main() - - - -``` - -{% endraw %} - -Longest Word in [CoffeeScript](/languages/coffeescript) was written by: - -- stefanurkal - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/commodore-basic/index.md b/docs/projects/longest-word/commodore-basic/index.md deleted file mode 100644 index 728edba803..0000000000 --- a/docs/projects/longest-word/commodore-basic/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: longest-word-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- longest-word -title: Longest Word in Commodore BASIC -title1: Longest Word in -title2: Commodore BASIC ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input string -10 GOSUB 1000 -20 IF S$ = "" OR S$ = CHR$(13) THEN GOTO 160 -25 REM Keep track of length of longest word -30 LW% = 0: REM longest word length so far -40 LC% = 0: REM current word length -50 FOR K = 1 TO LEN(S$) -60 A$ = MID$(S$, K, 1) -70 IF A$ = CHR$(9) OR A$ = CHR$(10) OR A$ = CHR$(13) THEN GOTO 120 -80 IF A$ = " " THEN GOTO 120: REM can't put on same line, too long -90 LC% = LC% + 1 -100 IF LC% > LW% THEN LW% = LC% -110 GOTO 130 -120 LC% = 0 -130 NEXT K -140 PRINT MID$(STR$(LW%), 2) -150 END -160 PRINT "Usage: please provide a string" -170 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 255 THEN RETURN: REM end of input -1050 S$ = S$ + A$ -1060 GOTO 1020 - -``` - -{% endraw %} - -Longest Word in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/dart/index.md b/docs/projects/longest-word/dart/index.md deleted file mode 100644 index 58658b401f..0000000000 --- a/docs/projects/longest-word/dart/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- gangaasoonu -date: 2025-10-04 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-10-04 -layout: default -tags: -- dart -- longest-word -title: Longest Word in Dart -title1: Longest Word -title2: in Dart ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -//Issue 4972 - -void main(List argv){ - const String error_message = "Usage: please provide a string"; - if (argv.isEmpty || argv[0].isEmpty){ - print(error_message); - return; - } - - String sentence = argv[0]; - String raw = sentence.replaceAll(r'\t', '\t').replaceAll(r'\r', '\r').replaceAll(r'\n', '\n'); - List words = raw.split(RegExp(r'\s+')); - int max_length= 0; - - for (String each_word in words){ - if (each_word.length > max_length){ - max_length = each_word.length; - } - } - print(max_length); -} - -``` - -{% endraw %} - -Longest Word in [Dart](/languages/dart) was written by: - -- gangaasoonu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/euphoria/index.md b/docs/projects/longest-word/euphoria/index.md deleted file mode 100644 index 71501486e8..0000000000 --- a/docs/projects/longest-word/euphoria/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-17 -featured-image: longest-word-in-every-language.jpg -last-modified: 2023-02-17 -layout: default -tags: -- euphoria -- longest-word -title: Longest Word in Euphoria -title1: Longest Word -title2: in Euphoria ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/regex.e as re -include std/text.e -include std/math.e - -function longest_word(sequence s) - -- Trim off leading and trailing whitespace, then split into words - sequence words = split(re:new(`\s+`), trim(s)) - - -- Find longest word - integer longest = 0 - for n = 1 to length(words) - do - longest = max({longest, length(words[n])}) - end for - - return longest -end function - -procedure usage() - printf(STDOUT, "Usage: please provide a string") - abort(0) -end procedure - --- Parse 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Get longest word length and display it -sequence s = argv[4] -printf(STDOUT, "%d\n", longest_word(s)) - -``` - -{% endraw %} - -Longest Word in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/f-sharp/index.md b/docs/projects/longest-word/f-sharp/index.md deleted file mode 100644 index e2909807ea..0000000000 --- a/docs/projects/longest-word/f-sharp/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-08 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-04-08 -layout: default -tags: -- f-sharp -- longest-word -title: Longest Word in F# -title1: Longest -title2: Word in F# ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module LongestWord = - let run (s: string) = - s - |> Seq.fold - (fun (maxLen, currLen) ch -> - if Char.IsWhiteSpace ch then - (max maxLen currLen, 0) - else - (maxLen, currLen + 1)) - (0, 0) - |> fun (maxLen, currLen) -> max maxLen currLen - -module Helpers = - let usage = "Usage: please provide a string" - - let parseArgs argv = - match argv with - | [| s |] when not (String.IsNullOrEmpty s) -> Ok s - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%d" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.map LongestWord.run |> Helpers.handleResult - -``` - -{% endraw %} - -Longest Word in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/go/index.md b/docs/projects/longest-word/go/index.md deleted file mode 100644 index 8d18b20335..0000000000 --- a/docs/projects/longest-word/go/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- alope107 -date: 2023-03-19 -featured-image: longest-word-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- go -- longest-word -title: Longest Word in Go -title1: Longest -title2: Word in Go ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strings" -) - -const errorMessage = "Usage: please provide a string" - -// longestWordLength returns the length of the longest word -// in a string. The words in the string should be separated -// by spaces, tabs, newlines, and/or carriage returns. -func longestWordLength(str string) int { - words := strings.FieldsFunc(str, isLimitedWhitespace) - return longestStringLength(words) -} - -// isLimitedWhitespace returns whether a rune is one of four -// whitespace runes: ' ', '\t', '\n', '\r' -// Note that this is NOT equivalent to unicode.IsSpace which -// includes addtional whitespace runes -func isLimitedWhitespace(r rune) bool { - return strings.ContainsRune(" \t\n\r", r) -} - -// longestStringLength returns the length of the longest string -// in the slice -func longestStringLength(strs []string) (longest int) { - for _, str := range strs { - if len(str) > longest { - longest = len(str) - } - } - return -} - -func main() { - if len(os.Args) < 2 || len(os.Args[1]) == 0 { - fmt.Println(errorMessage) - } else { - fmt.Println(longestWordLength(os.Args[1])) - } -} - -``` - -{% endraw %} - -Longest Word in [Go](/languages/go) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/haskell/index.md b/docs/projects/longest-word/haskell/index.md deleted file mode 100644 index 6db2fca235..0000000000 --- a/docs/projects/longest-word/haskell/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-04-29 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-04-29 -layout: default -tags: -- haskell -- longest-word -title: Longest Word in Haskell -title1: Longest Word -title2: in Haskell ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Data.Function ((&)) - -usage :: String -usage = "Usage: please provide a string" - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - -verifyStringNotEmpty :: String -> Maybe String -verifyStringNotEmpty "" = Nothing -verifyStringNotEmpty xs = Just xs - -main :: IO () -main = do - args <- getArgs - let inputStr = headMaybe args >>= verifyStringNotEmpty - case inputStr of - Just str -> str & words & map length & maximum & print - Nothing -> putStrLn "Usage: please provide a string" - -``` - -{% endraw %} - -Longest Word in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/index.md b/docs/projects/longest-word/index.md deleted file mode 100644 index 185a1e222b..0000000000 --- a/docs/projects/longest-word/index.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -date: 2022-04-28 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- longest-word -title: Longest Word -title1: Longest -title2: Word ---- - - - -Welcome to the Longest Word page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Given a string, this program should break it up into words and determine -the length of the longest word. In this case, a word is defined as anything -surrounded by whitespace. For simplicity, we'll restrict whitespace to the -following four special characters: - -- Spaces: " " -- Tabs: "\t" -- Newlines: "\n" -- Carriage Returns: "\r" - -For example, if we had a string, "How now brown cow", we can figure out which -word is the longest by breaking up the string into words. In this case, this -string has the following four words: - -- "How" -- "now" -- "brown" -- "cow" - -In this case, "brown" is clearly the longest word, so we'll return 5 as a result. - - -## Requirements - -To satisfy the requirements, a program must accept a string on the command line -and return the length of the longest word in the string: - -```shell -$ ./longest-word-in-string.lang "Google do a barrel roll" -$ 6 -``` - -In this case, we have a string with 5 words. It appears that there are two words -that share the largest number of characters: Google and barrel. Naturally, we -don't care to decide between the two words. Instead, we return the length of them -both: 6. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Longest Word. -In order to keep things simple, we split up the testing as follows: - -- Longest Word Valid Tests -- Longest Word Invalid Tests - -### Longest Word Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: Many Words | "May the force be with you" | "5" | -| Sample Input: Single Word | "Floccinaucinihilipilification" | "29" | -| Sample Input: Multiline | "Hi,\nMy name is Paul!" | "5" | - -### Longest Word Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | - -All of these tests should output the following: - -``` -Usage: please provide a string -``` - - -## Articles - -There are 37 articles: - -- [Longest Word in ALGOL 60](/projects/longest-word/algol60) -- [Longest Word in ALGOL 68](/projects/longest-word/algol68) -- [Longest Word in AWK](/projects/longest-word/awk) -- [Longest Word in Ada](/projects/longest-word/ada) -- [Longest Word in Beef](/projects/longest-word/beef) -- [Longest Word in Brainfuck](/projects/longest-word/brainfuck) -- [Longest Word in C](/projects/longest-word/c) -- [Longest Word in C#](/projects/longest-word/c-sharp) -- [Longest Word in C++](/projects/longest-word/c-plus-plus) -- [Longest Word in COBOL](/projects/longest-word/cobol) -- [Longest Word in CoffeeScript](/projects/longest-word/coffeescript) -- [Longest Word in Commodore BASIC](/projects/longest-word/commodore-basic) -- [Longest Word in Dart](/projects/longest-word/dart) -- [Longest Word in Euphoria](/projects/longest-word/euphoria) -- [Longest Word in F#](/projects/longest-word/f-sharp) -- [Longest Word in Go](/projects/longest-word/go) -- [Longest Word in Haskell](/projects/longest-word/haskell) -- [Longest Word in Java](/projects/longest-word/java) -- [Longest Word in JavaScript](/projects/longest-word/javascript) -- [Longest Word in Julia](/projects/longest-word/julia) -- [Longest Word in Kotlin](/projects/longest-word/kotlin) -- [Longest Word in Lua](/projects/longest-word/lua) -- [Longest Word in Mathematica](/projects/longest-word/mathematica) -- [Longest Word in Odin](/projects/longest-word/odin) -- [Longest Word in PHP](/projects/longest-word/php) -- [Longest Word in Pascal](/projects/longest-word/pascal) -- [Longest Word in Perl](/projects/longest-word/perl) -- [Longest Word in PowerShell](/projects/longest-word/powershell) -- [Longest Word in Python](/projects/longest-word/python) -- [Longest Word in R](/projects/longest-word/r) -- [Longest Word in Ruby](/projects/longest-word/ruby) -- [Longest Word in Rust](/projects/longest-word/rust) -- [Longest Word in Swift](/projects/longest-word/swift) -- [Longest Word in Tcl](/projects/longest-word/tcl) -- [Longest Word in TypeScript](/projects/longest-word/typescript) -- [Longest Word in Visual Basic](/projects/longest-word/visual-basic) -- [Longest Word in m4](/projects/longest-word/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/longest-word/java/index.md b/docs/projects/longest-word/java/index.md deleted file mode 100644 index 7bee45e34b..0000000000 --- a/docs/projects/longest-word/java/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Vipin Yadav -date: 2022-10-03 -featured-image: longest-word-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- java -- longest-word -title: Longest Word in Java -title1: Longest Word -title2: in Java ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -class LongestWord { - public static void error() { - System.out.println("Usage: please provide a string"); - } - - public static void main(String[] args) { - if (args.length <= 0) { - error(); - } else if (args[0].length() == 0) { - error(); - } else { - String inputStr = args[0]; - String[] words = inputStr.split("\\s+"); - int max = -1; - for (String word : words) { - if (word.length() > max) { - max = word.length(); - } - } - System.out.println(max); - } - } -} -``` - -{% endraw %} - -Longest Word in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/javascript/index.md b/docs/projects/longest-word/javascript/index.md deleted file mode 100644 index 582fdc748d..0000000000 --- a/docs/projects/longest-word/javascript/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Raakesh.R -date: 2023-10-24 -featured-image: longest-word-in-every-language.jpg -last-modified: 2023-10-24 -layout: default -tags: -- javascript -- longest-word -title: Longest Word in JavaScript -title1: Longest Word -title2: in JavaScript ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const error_msg = "Usage: please provide a string"; -if (process.argv.length != 3) { - console.log(error_msg); - process.exit(1); -} - -const inputString = process.argv[2].replace(/\n|\t|\r/g, " "); -if (inputString.trim().length == 0) { - console.log(error_msg); - process.exit(1); -} - -const words = inputString.trim().split(" "); - -let longestWordLength = 0; - -for (const word of words) { - if (word.length > longestWordLength) { - longestWordLength = word.length; - } -} - -console.log(longestWordLength); - -``` - -{% endraw %} - -Longest Word in [JavaScript](/languages/javascript) was written by: - -- Raakesh.R - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/julia/index.md b/docs/projects/longest-word/julia/index.md deleted file mode 100644 index 6593b6abbe..0000000000 --- a/docs/projects/longest-word/julia/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- brittLiban -date: 2024-11-09 -featured-image: longest-word-in-every-language.jpg -last-modified: 2024-11-09 -layout: default -tags: -- julia -- longest-word -title: Longest Word in Julia -title1: Longest Word -title2: in Julia ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -function longest_word_length(text::String) - # Split on exactly the specified whitespace characters: space, tab, newline, carriage return - words = split(text, r"[ \t\n\r]+") - - # Find the maximum length of the words array - return maximum(length.(words)) -end - -# Command-line argument handling -if length(ARGS) == 0 || strip(ARGS[1]) == "" - println("Usage: please provide a string") - exit(1) -end - -input_string = ARGS[1] -println(longest_word_length(input_string)) - -``` - -{% endraw %} - -Longest Word in [Julia](/languages/julia) was written by: - -- brittLiban - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/kotlin/index.md b/docs/projects/longest-word/kotlin/index.md deleted file mode 100644 index 10441bb49a..0000000000 --- a/docs/projects/longest-word/kotlin/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- mechance782 -date: 2024-11-11 -featured-image: longest-word-in-every-language.jpg -last-modified: 2024-11-11 -layout: default -tags: -- kotlin -- longest-word -title: Longest Word in Kotlin -title1: Longest Word -title2: in Kotlin ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) { - - fun longestWord(sentence: String): Any { - // if sentence is empty, ask for a String - if (sentence.length == 0){ - return "Usage: please provide a string" - } else { - // split sentence from these delimeters and put resulting strings into words list - var words = sentence.split(" ", "\t", "\n", "\r") - var longest = 0 - // iterate through words list and compare each word length to longest var - // if word length is larger, then the var longest will be assigned the word length - for (word in words){ - when { - word.length > longest -> longest = word.length - } - } - // return var longest which holds the largest string length in the sentence parameter - return longest - } - } - - // if console input is null, ask for String - if (args.isNullOrEmpty()){ - println("Usage: please provide a string") - } else { - // if console input is not null, then find longestWord of input String - println(longestWord(args[0])) - } - -} -``` - -{% endraw %} - -Longest Word in [Kotlin](/languages/kotlin) was written by: - -- mechance782 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/lua/index.md b/docs/projects/longest-word/lua/index.md deleted file mode 100644 index c2ae3bb607..0000000000 --- a/docs/projects/longest-word/lua/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- alexborovets11 -date: 2025-03-26 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-03-26 -layout: default -tags: -- longest-word -- lua -title: Longest Word in Lua -title1: Longest -title2: Word in Lua ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -if #arg < 1 then - print("Usage: please provide a string") - os.exit(1) -end - -local input = arg[1] - -function longest_word_length(str) - local max_length = 0 - local found_word = false - - for word in string.gmatch(str, "%S+") do - found_word = true - local length = #word - if length > max_length then - max_length = length - end - end - - if not found_word then - print("Usage: please provide a string") - os.exit(1) - end - - return max_length -end - - -print(longest_word_length(input)) -``` - -{% endraw %} - -Longest Word in [Lua](/languages/lua) was written by: - -- alexborovets11 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/m4/index.md b/docs/projects/longest-word/m4/index.md deleted file mode 100644 index 3a6a5e3385..0000000000 --- a/docs/projects/longest-word/m4/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-16 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-08-16 -layout: default -tags: -- longest-word -- m4 -title: Longest Word in m4 -title1: Longest -title2: Word in m4 ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a string -m4exit(`1')') - -dnl Commas are intepreted as argument separators, so need to change them to something that -dnl won't appear in the argument -define(`escape', `translit(``$1'', `,', `«')') - -dnl max(a, b) -define(`max', `ifelse(eval(`$1' > `$2'), 1, `$1', `$2')') - -dnl longest_word(str) -define(`longest_word', `_longest_word(escape(`$1'), 0, 0)') - -dnl _longest_word(str, curr_len, max_len) -dnl for each character in str (ch): -dnl if ch is whitespace: -dnl curr_len = 0 -dnl else: -dnl curr_len = curr_len + 1 -dnl max_len = max(curr_len, max_len) -dnl Return max_len -define(`_longest_word', -`ifelse(len(`$1'), 0, `$3', -regexp(substr(`$1', 0, 1), `\s'), 0, -`_longest_word(substr(`$1', 1), 0, `$3')', -`_longest_word(substr(`$1', 1), incr(`$2'), max(incr(`$2'), `$3'))'dnl -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1), 1, `show_usage()', `longest_word(ARGV1)') - -``` - -{% endraw %} - -Longest Word in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/mathematica/index.md b/docs/projects/longest-word/mathematica/index.md deleted file mode 100644 index 0f0870db8d..0000000000 --- a/docs/projects/longest-word/mathematica/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-16 -featured-image: longest-word-in-every-language.jpg -last-modified: 2023-01-16 -layout: default -tags: -- longest-word -- mathematica -title: Longest Word in Mathematica -title1: Longest Word -title2: in Mathematica ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Trivial: *) - -longestWord = s \[Function] Max @@ StringLength /@ StringSplit[s]; - -(* The outer function provides the 'user interface' (e.g., the string parsing): *) - -longestWordMain = Function[{s}, - Module[{e = "Usage: please provide a string"}, - Catch[ - longestWord @ - If[StringLength[s] > 0, s, Throw[e]]]]]; - - -(* Valid Tests *) - -Print /@ longestWord /@ { - "May the force be with you", - "Floccinaucinihilipilification", - "Hi,\nMy name is Paul!" - }; - - -(* Invalid Tests *) - -longestWordMain[""] - -``` - -{% endraw %} - -Longest Word in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/odin/index.md b/docs/projects/longest-word/odin/index.md deleted file mode 100644 index f30f608f46..0000000000 --- a/docs/projects/longest-word/odin/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- nallovint -date: 2024-08-03 -featured-image: longest-word-in-every-language.jpg -last-modified: 2024-08-03 -layout: default -tags: -- longest-word -- odin -title: Longest Word in Odin -title1: Longest Word -title2: in Odin ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main - -import "core:fmt" -import "core:strings" -import "core:os" - -main :: proc() { - if len(os.args) != 2 { - usage() - return - } - text := os.args[1] - get_longest_word(text) -} - -get_longest_word :: proc (words: string) -> int { - if len(words) == 0 { - usage() - return 0 - } - - cleaned, _ := strings.replace_all(words, "\t", " ") - cleaned, _ = strings.replace_all(cleaned, "\r", " ") - cleaned, _ = strings.replace_all(cleaned, "\n", " ") - string_split := strings.split(cleaned, " ") - - count := 0 - for word in string_split { - if len(word) > count { - count = len(word) - } - } - fmt.println(count) - return count -} - -usage :: proc() { - fmt.eprintln("Usage: please provide a string") -} - -``` - -{% endraw %} - -Longest Word in [Odin](/languages/odin) was written by: - -- nallovint - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/pascal/index.md b/docs/projects/longest-word/pascal/index.md deleted file mode 100644 index 80f8946f79..0000000000 --- a/docs/projects/longest-word/pascal/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- longest-word -- pascal -title: Longest Word in Pascal -title1: Longest Word -title2: in Pascal ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program LongestWord; - -{$mode objfpc}{$H+} - -uses - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a string'); - Halt(1); -end; - -function FindLongestWordLength(const input: string): integer; -var - i, currentLength, longestLength: integer; -begin - currentLength := 0; - longestLength := 0; - - for i := 1 to Length(input) do - if input[i] in [' ', #9, #10, #13] then - begin - // Update longestLength if we encountered the end of a word - if currentLength > longestLength then - longestLength := currentLength; - - // Reset for the next word - currentLength := 0; - end - else - // Increase the length of the current word - Inc(currentLength); - - // Final check for the last word in the string (if no trailing space) - if currentLength > longestLength then - longestLength := currentLength; - - Result := longestLength; -end; - -var - input: string; - Result: integer; -begin - if ParamCount <> 1 then - ShowUsage; - - input := ParamStr(1); - - if Trim(input) = '' then - ShowUsage; - - Result := FindLongestWordLength(input); - Writeln(Result); -end. - -``` - -{% endraw %} - -Longest Word in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/perl/index.md b/docs/projects/longest-word/perl/index.md deleted file mode 100644 index 6b2e376ac8..0000000000 --- a/docs/projects/longest-word/perl/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- longest-word -- perl -title: Longest Word in Perl -title1: Longest Word -title2: in Perl ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; -use List::Util qw/max/; - -sub usage { say "Usage: please provide a string"; exit } - -my $input = "@ARGV"; -$input =~ s/^\s+|\s+$//g; - -usage unless length $input; -say max map length, split /\s+/, $input; -``` - -{% endraw %} - -Longest Word in [Perl](/languages/perl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/php/index.md b/docs/projects/longest-word/php/index.md deleted file mode 100644 index 10399fa27a..0000000000 --- a/docs/projects/longest-word/php/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-23 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- longest-word -- php -title: Longest Word in PHP -title1: Longest -title2: Word in PHP ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Longest Word](/projects/longest-word) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide a string" - Exit 1 -} - -function Get-LongestWord([string]$Str) { - ($Str -split "\s+" | ForEach-Object { $_.Length } | Measure-Object -Maximum).Maximum -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -Write-Host (Get-LongestWord $args[0]) - -``` - -{% endraw %} - -Longest Word in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/python/index.md b/docs/projects/longest-word/python/index.md deleted file mode 100644 index 3875953e17..0000000000 --- a/docs/projects/longest-word/python/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2022-05-13 -featured-image: longest-word-in-every-language.jpg -last-modified: 2022-05-13 -layout: default -tags: -- longest-word -- python -title: Longest Word in Python -title1: Longest Word -title2: in Python ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - -error = "Usage: please provide a string" - -if len(sys.argv) == 1 or sys.argv[1] == "": - print(error) - sys.exit(1) - -input_string = sys.argv[1] -longest_word = max(len(word) for word in input_string.split()) -print(longest_word) - -``` - -{% endraw %} - -Longest Word in [Python](/languages/python) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/r/index.md b/docs/projects/longest-word/r/index.md deleted file mode 100644 index 00549791ed..0000000000 --- a/docs/projects/longest-word/r/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Tav Singh -date: 2024-11-21 -featured-image: longest-word-in-every-language.jpg -last-modified: 2024-11-21 -layout: default -tags: -- longest-word -- r -title: Longest Word in R -title1: Longest -title2: Word in R ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -longest_word_length <- function(input_string) { - # Checking input - args <- commandArgs(trailingOnly = TRUE) - - if (length(args) == 0 || args == "") { - cat("Usage: please provide a string\n") - } else { - # Split the string by whitespace and find the maximum word length in one line - cat(max(nchar(unlist(strsplit(args[1], "[ \t\n\r]+")))), "\n") - } -} - -longest_word_length() -``` - -{% endraw %} - -Longest Word in [R](/languages/r) was written by: - -- Tav Singh - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/ruby/index.md b/docs/projects/longest-word/ruby/index.md deleted file mode 100644 index 2f1cdd1dae..0000000000 --- a/docs/projects/longest-word/ruby/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- reetansingh -- Ștefan-Iulian Alecu -date: 2025-03-26 -featured-image: longest-word-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- longest-word -- ruby -title: Longest Word in Ruby -title1: Longest Word -title2: in Ruby ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -input = ARGV.join(" ").strip - -abort("Usage: please provide a string") if input.empty? - -puts input.split.map(&:length).max - -``` - -{% endraw %} - -Longest Word in [Ruby](/languages/ruby) was written by: - -- reetansingh -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/rust/index.md b/docs/projects/longest-word/rust/index.md deleted file mode 100644 index 4256366705..0000000000 --- a/docs/projects/longest-word/rust/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-09 -featured-image: longest-word-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- longest-word -- rust -title: Longest Word in Rust -title1: Longest Word -title2: in Rust ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; - -fn usage() -> ! { - println!("Usage: please provide a string"); - exit(0); -} - -fn get_longest_word_len(s: &str) -> usize { - s.trim() - .split_whitespace() - .map(|t| t.len()) - .max() - .unwrap() -} - -fn main() { - let mut args = args().skip(1); - - // Exit if 1st command-line argument is empty - let s: &str = &args - .next() - .unwrap_or_else(|| usage()); - if s.len() < 1 { - usage(); - } - - // Get longest word length and display it - println!("{}", get_longest_word_len(s)); -} - -``` - -{% endraw %} - -Longest Word in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/swift/index.md b/docs/projects/longest-word/swift/index.md deleted file mode 100644 index cd4b91adb9..0000000000 --- a/docs/projects/longest-word/swift/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- ShawnN003 -date: 2025-02-18 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-02-18 -layout: default -tags: -- longest-word -- swift -title: Longest Word in Swift -title1: Longest Word -title2: in Swift ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -if (CommandLine.arguments.count < 2) { - print("Usage: please provide a string") -} -else -{ - var sentence = CommandLine.arguments[1] - sentence = sentence.replacingOccurrences(of: "\n", with: "") //removing the break line if it contains any - longestWord(input : sentence) -} - -func longestWord(input : String) -> Void -{ - var longest = 0 - var testWord = "" - - if(input == "") - { - print("Usage: please provide a string") //checking for empty string - } - - else - { - var substrings: [Substring] = [] //array to hold the array of the input strings - substrings = input.split(separator: " ") //splitting the array by spaces - - for word in substrings //iterate through the array - { - testWord = word.trimmingCharacters(in: CharacterSet(charactersIn: " ")) - if(testWord.count > longest) - { - longest = testWord.count //obtaining the longest count of words - } - } - print(longest) - } -} - -``` - -{% endraw %} - -Longest Word in [Swift](/languages/swift) was written by: - -- ShawnN003 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/tcl/index.md b/docs/projects/longest-word/tcl/index.md deleted file mode 100644 index fc5d59a833..0000000000 --- a/docs/projects/longest-word/tcl/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- longest-word -- tcl -title: Longest Word in Tcl -title1: Longest -title2: Word in Tcl ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a string} - exit 1 -} - -proc longestWordLength {s} { - set s [string trim $s] - if {$s eq ""} { usage } - - set maxLen 0 - set curLen 0 - set len [string length $s] - - for {set i 0} {$i < $len} {incr i} { - set ch [string index $s $i] - if {[string is space $ch]} { - if {$curLen > $maxLen} { set maxLen $curLen } - set curLen 0 - } else { - incr curLen - } - } - - if {$curLen > $maxLen} { set maxLen $curLen } - - return $maxLen -} - -if {$argc != 1} { usage } - -set input [lindex $argv 0] -if {[string trim $input] eq ""} { usage } - -puts [longestWordLength $input] - -``` - -{% endraw %} - -Longest Word in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/typescript/index.md b/docs/projects/longest-word/typescript/index.md deleted file mode 100644 index 5deb6b6571..0000000000 --- a/docs/projects/longest-word/typescript/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- TiaMarieG -date: 2024-11-09 -featured-image: longest-word-in-every-language.jpg -last-modified: 2024-11-09 -layout: default -tags: -- longest-word -- typescript -title: Longest Word in TypeScript -title1: Longest Word -title2: in TypeScript ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -if (process.argv.length < 3 || process.argv[2].length < 1) { - console.log("Usage: please provide a string") - process.exit(0) -} - -let testString: string = process.argv[2].replace(/\n|\t|\r/g, " "); - -const separatedWords: string[] = testString.split(' '); - -let longestWord: string = ""; -let wordLength: number = 0; - -for (let word of separatedWords) { - if (word.length > longestWord.length) { - longestWord = word; - wordLength = word.length; - } -} - -console.log(wordLength); - -``` - -{% endraw %} - -Longest Word in [TypeScript](/languages/typescript) was written by: - -- TiaMarieG - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/longest-word/visual-basic/index.md b/docs/projects/longest-word/visual-basic/index.md deleted file mode 100644 index 944a39052f..0000000000 --- a/docs/projects/longest-word/visual-basic/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- JSaiyan -date: 2025-02-18 -featured-image: longest-word-in-every-language.jpg -last-modified: 2025-02-18 -layout: default -tags: -- longest-word -- visual-basic -title: Longest Word in Visual Basic -title1: Longest Word in -title2: Visual Basic ---- - - - -Welcome to the [Longest Word](/projects/longest-word) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module LongestWord - Public Sub Main(args As String()) - ' Check if input is provided - If args.Length = 0 Then - Usage() - Exit Sub - End If - - ' Join the arguments to form the full input string - Dim multi As String = String.Join(" ", args).Trim() - - ' Replace newlines, carriage returns, and tabs with spaces - multi = multi.Replace(vbCrLf, " ").Replace(vbCr, " ").Replace(vbLf, " ").Replace(vbTab, " ") - - ' Split the string into words by spaces, removing empty entries - Dim words As String() = multi.Split(" "c, StringSplitOptions.RemoveEmptyEntries) - - ' If there are no words, print usage - If words.Length = 0 Then - Usage() - Exit Sub - End If - - ' Find the longest word length - Dim longestWord As String = "" - Dim maxLength As Integer = 0 - - ' Loop through the words and find the longest - For Each word As String In words - If word.Length > maxLength Then - longestWord = word - maxLength = word.Length - End If - Next - - ' Output the length of the longest word - System.Console.WriteLine(maxLength) - End Sub - - Public Sub Usage() - System.Console.WriteLine("Usage: please provide a string") - End Sub -End Module -``` - -{% endraw %} - -Longest Word in [Visual Basic](/languages/visual-basic) was written by: - -- JSaiyan - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/ada/index.md b/docs/projects/maximum-array-rotation/ada/index.md deleted file mode 100644 index 93f5977525..0000000000 --- a/docs/projects/maximum-array-rotation/ada/index.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-11 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- ada -- maximum-array-rotation -title: Maximum Array Rotation in Ada -title1: Maximum Array -title2: Rotation in Ada ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Strings.Maps; use Ada.Strings.Maps; -with Ada.Containers.Vectors; - -procedure Maximum_Array_Rotation is - - Data_Format_Error : exception; - - function Clean (S : String) return String - is (Trim (S, Ada.Strings.Both)); - - function To_Int (S : String) return Integer is - Cleaned : constant String := Clean (S); - begin - return Integer'Value (Cleaned); - exception - when Constraint_Error => - raise Data_Format_Error with "Invalid integer: '" & Cleaned & "'"; - end To_Int; - - package Integer_Vectors is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - subtype Int_List is Integer_Vectors.Vector; - - function To_Int_List (Raw_String : String) return Int_List is - Result : Int_List; - Start : Positive := Raw_String'First; - Finish : Natural; - Seps : constant Character_Set := To_Set (", "); - begin - while Start <= Raw_String'Last loop - Find_Token - (Raw_String, Seps, Start, Ada.Strings.Outside, Start, Finish); - - exit when Start > Finish; - - Result.Append (To_Int (Raw_String (Start .. Finish))); - - Start := Finish + 1; - end loop; - - if Result.Is_Empty then - raise Data_Format_Error with "List is empty"; - end if; - - return Result; - end To_Int_List; - - function Max_Rotation (A : Int_List) return Integer is - N : constant Natural := Natural (A.Length); - - Total : Integer := 0; - Curr : Integer := 0; - Best : Integer; - begin - if N = 0 then - return 0; - end if; - - for I in A.First_Index .. A.Last_Index loop - Total := Total + A.Element (I); - Curr := Curr + (I - A.First_Index) * A.Element (I); - end loop; - - Best := Curr; - - for K in 1 .. N - 1 loop - Curr := Curr + Total - N * A.Element (A.Last_Index - K + 1); - Best := Integer'Max (Best, Curr); - end loop; - - return Best; - end Max_Rotation; - - procedure Print_Usage is - begin - Put_Line - ("Usage: please provide a list of integers (e.g. ""8, 3, 1, 2"")"); - end Print_Usage; - -begin - if Argument_Count /= 1 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - begin - declare - Arr : constant Int_List := To_Int_List (Argument (1)); - begin - Put_Line (Integer'Image (Max_Rotation (Arr))); - end; - exception - when Data_Format_Error | Constraint_Error => - Print_Usage; - Set_Exit_Status (Failure); - end; - -end Maximum_Array_Rotation; -``` - -{% endraw %} - -Maximum Array Rotation in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/algol60/index.md b/docs/projects/maximum-array-rotation/algol60/index.md deleted file mode 100644 index 842840aa2f..0000000000 --- a/docs/projects/maximum-array-rotation/algol60/index.md +++ /dev/null @@ -1,234 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-18 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- maximum-array-rotation -title: Maximum Array Rotation in ALGOL 60 -title1: Maximum Array -title2: Rotation in ALGOL 60 ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - integer procedure maximumArrayRotation(arr, n); - value n; - integer array arr; - integer n; - begin - integer i, s, w, wmax; - - comment Calculate sum and initial array rotation; - s := 0; - w := 0; - for i := 1 step 1 until n do - begin - s := s + arr[i]; - w := w + (i - 1) * arr[i] - end; - - comment Initialize maximum array rotation; - wmax := w; - - comment Adjust array rotation and update maximum; - for i := 1 step 1 until n - 1 do - begin - w := w + n * arr[i] - s; - if w > wmax then wmax := w - end; - - maximumArrayRotation := wmax - end maximumArrayRotation; - - integer argc, arrLen, result; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 1 then usage; - - comment Find maximum array rotation and display result; - result := maximumArrayRotation(arr, arrLen); - outinteger(1, result); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Maximum Array Rotation in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/algol68/index.md b/docs/projects/maximum-array-rotation/algol68/index.md deleted file mode 100644 index fa6539c467..0000000000 --- a/docs/projects/maximum-array-rotation/algol68/index.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-01 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2023-02-01 -layout: default -tags: -- algol68 -- maximum-array-rotation -title: Maximum Array Rotation in ALGOL 68 -title1: Maximum Array -title2: Rotation in ALGOL 68 ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a list of integers (e.g. ""8, 3, 1, 2"")")) -); - -COMMENT -Find maximum array rotation, max{W(k), k=0..N-1}, where: - - W(k) = sum{i*a[i+k mod N], i=0..N-1} - -The value of W(k) can be calculated from W(k-1) as follows: - - W(k) = W(k-1) - S + N*a[k-1] - -where: - - S = sum{a[i], i=0..N-1} = sum{a[i+x mod N], i=0..N-1} - -where: x is any arbitary value - -Proof: - -- Set up initial assumption for W(k): - - W(k-1) - S + N*a[k-1] = sum{i*a[i+k-1 mod N], i=0..N-1} - sum{a[i+k-1 mod N}, i=0..N-1} + N*a[k-1] - -- Combine the two sums: - - = sum{(i-1)*a[i+k-1 mod N], i=0..N-1} + N*a[k-1] - -- Pull out the i=0 term: - = -a[k-1] + sum{(i-1)*a[i+k-1 mod N], i=1..N-1} + N*a[k-1] - -- Combine the a[k-1] terms: - - = sum{(i-1}*a[i+k-1 mod N], i=1..N-1) + (N-1)*a[k-1] - -- Change indexing from i=1..N-1 to 0..N-2: - - = sum{i*a[i+k mod N], i=0..N-2} + (N-1)*a[k-1] - -- Bring the i=N-1 term back into the sum since N-1+k mod N equals k-1: - - = sum{i*a[i+k mod N], i=0..N-1} - -- The above equals W(k) -COMMENT -PROC maximum array rotation = (REF []INT values) INT: -( - # Calculate sum and initial array rotation # - INT s := 0; - INT w := 0; - INT n = UPB values; - FOR i TO n - DO - s +:= values[i]; - w +:= (i - 1) * values[i] - OD; - - # Initialize maximum array rotation # - INT wmax := w; - - # Adjust array rotation and update maximum # - FOR i TO n - 1 - DO - w +:= n * values[i] - s; - IF w > wmax - THEN - wmax := w - FI - OD; - - wmax -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result -THEN - usage; - stop -FI; - -# Find maximum array rotation and display result # -INT value = maximum array rotation(values); -printf(($gl$, whole(value, 0))) - -``` - -{% endraw %} - -Maximum Array Rotation in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/awk/index.md b/docs/projects/maximum-array-rotation/awk/index.md deleted file mode 100644 index cddf900dd6..0000000000 --- a/docs/projects/maximum-array-rotation/awk/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-24 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2025-04-24 -layout: default -tags: -- awk -- maximum-array-rotation -title: Maximum Array Rotation in AWK -title1: Maximum Array -title2: Rotation in AWK ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -function maximum_array_rotation(arr, n, i, s, w, wmax) { - # Calculate sum and initial array rotation - for (i = 1; i <= n; i++) { - s += arr[i] - w += (i - 1) * arr[i] - } - - # Initialize maximum array rotation - wmax = w - - # Adjust array rotation and update maximum - for (i = 1; i < n; i++) { - w += n * arr[i] - s - if (w > wmax) { - wmax = w - } - } - return wmax -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], arr) - arr_len = length(arr) - if (!arr_len || arr[1] == "ERROR") { - usage() - } - - result = maximum_array_rotation(arr, arr_len) - printf("%d\n", result) -} - -``` - -{% endraw %} - -Maximum Array Rotation in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/beef/index.md b/docs/projects/maximum-array-rotation/beef/index.md deleted file mode 100644 index 95f788ef23..0000000000 --- a/docs/projects/maximum-array-rotation/beef/index.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-09 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2024-02-09 -layout: default -tags: -- beef -- maximum-array-rotation -title: Maximum Array Rotation in Beef -title1: Maximum Array -title2: Rotation in Beef ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace MaximumArrayRotation; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide a list of integers (e.g. "8, 3, 1, 2") - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Find maximum array rotation, max{W(k), k=0..N-1}, where: - // - // W(k) = sum{i*a[i+k mod N], i=0..N-1} - // - // The value of W(k) can be calculated from W(k-1) as follows: - // - // W(k) = W(k-1) - S + N*a[k-1] - // - // where: - // - // S = sum{a[i], i=0..N-1} = sum{a[i+x mod N], i=0..N-1} - // - // where: x is any arbitary value - // - // Proof: - // - // - Set up initial assumption for W(k): - // - // W(k-1) - S + N*a[k-1] = sum{i*a[i+k-1 mod N], i=0..N-1} - sum{a[i+k-1 mod N], i=0..N-1} + N*a[k-1] - // - // - Combine the two sums: - // - // = sum{(i-1)*a[i+k-1 mod N], i=0..N-1} + N*a[k-1] - // - // - Pull out the i=0 term: - // = -a[k-1] + sum{(i-1)*a[i+k-1 mod N], i=1..N-1} + N*a[k-1] - // - // - Combine the a[k-1] terms: - // - // = sum{(i-1)*a[i+k-1 mod N], i=1..N-1} + (N-1)*a[k-1] - // - // - Change indexing from i=1..N-1 to 0..N-2: - // - // = sum{i*a[i+k mod N], i=0..N-2} + (N-1)*a[k-1] - // - // - Bring the i=N-1 term back into the sum since N-1+k mod N equals k-1: - // - // = sum{i*a[i+k mod N], i=0..N-1} - // - // - The above equals W(k) - public static T MaximumArrayRotation(List arr) - where T : operator explicit int, operator T * T, operator T + T, operator T - T - where int : operator T <=> T - { - T s = default(T); - T w = default(T); - int n = arr.Count; - for (int i < n) - { - s += arr[i]; - w += (T)i * arr[i]; - } - - T wmax = w; - for (T val in arr[...^2]) - { - w += (T)n * val - s; - wmax = Math.Max(w, wmax); - } - - return wmax; - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - List arr = scope .(); - if (ParseIntList(args[0], arr) case .Err) - { - Usage(); - } - - int32 result = MaximumArrayRotation(arr); - Console.WriteLine(result); - - return 0; - } -} - -``` - -{% endraw %} - -Maximum Array Rotation in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/c-plus-plus/index.md b/docs/projects/maximum-array-rotation/c-plus-plus/index.md deleted file mode 100644 index 597fba2478..0000000000 --- a/docs/projects/maximum-array-rotation/c-plus-plus/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Jake-G123 -- Ștefan-Iulian Alecu -date: 2025-10-29 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- maximum-array-rotation -title: Maximum Array Rotation in C++ -title1: Maximum Array -title2: Rotation in C++ ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a list of integers (e.g. "8, 3, 1, 2"))" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.empty() ? std::nullopt : std::make_optional(out); -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - std::string_view input = argv[1]; - if (input.empty()) usage(); - - const auto vec_opt = parse_vec(input); - if (!vec_opt) usage(); - - auto& vec = *vec_opt; - - const int n = static_cast(vec.size()); - long long sum = 0, cur = 0; - - for (int i = 0; i < n; ++i) { - sum += vec[i]; - cur += static_cast(i) * vec[i]; - } - - long long best = cur; - - for (int k = 1; k < n; ++k) { - long long moved = vec[n - k]; - cur += sum - static_cast(n) * moved; - best = std::max(best, cur); - } - - std::cout << best << '\n'; -} -``` - -{% endraw %} - -Maximum Array Rotation in [C++](/languages/c-plus-plus) was written by: - -- Jake-G123 -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/c-sharp/index.md b/docs/projects/maximum-array-rotation/c-sharp/index.md deleted file mode 100644 index 72648684d0..0000000000 --- a/docs/projects/maximum-array-rotation/c-sharp/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-29 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- maximum-array-rotation -title: Maximum Array Rotation in C# -title1: Maximum Array -title2: Rotation in C# ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var input] || !TryParseList(input.AsSpan(), out var numbers)) - return ExitWithUsage(); - -Console.WriteLine(MaximumRotationSum(numbers)); -return 0; - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return numbers.Count > 0; -} - -static int MaximumRotationSum(List numbers) -{ - int n = numbers.Count; - - int totalSum = numbers[0]; - int rotationSum = 0; - - for (int i = 1; i < n; i++) - { - int v = numbers[i]; - totalSum += v; - rotationSum += v * i; - } - - int best = rotationSum; - - for (int i = 1, last = n - 1; i < n; i++, last--) - { - rotationSum += totalSum - n * numbers[last]; - best = Math.Max(best, rotationSum); - } - - return best; -} - -static int ExitWithUsage() -{ - Console.WriteLine( - "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")" - ); - return 1; -} - -``` - -{% endraw %} - -Maximum Array Rotation in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/c/index.md b/docs/projects/maximum-array-rotation/c/index.md deleted file mode 100644 index 63b1f3c5cb..0000000000 --- a/docs/projects/maximum-array-rotation/c/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-19 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- maximum-array-rotation -title: Maximum Array Rotation in C -title1: Maximum Array -title2: Rotation in C ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -void calculate_maximum_rotation(char *input) -{ - // Parse the input string into an array of integers - int arr[100], n = 0; - char *token = strtok(input, ","); - - while (token != NULL) - { - arr[n++] = atoi(token); - token = strtok(NULL, ","); - } - - // Edge case: No input or empty input - if (n == 0) - { - printf( - "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")\n"); - return; - } - - // Calculate initial weighted sum - int total_sum = 0, weighted_sum = 0; - - for (int i = 0; i < n; i++) - { - weighted_sum += i * arr[i]; - total_sum += arr[i]; - } - - int max_weighted_sum = weighted_sum; - - // Calculate maximum weighted sum after rotations - for (int i = 1; i < n; i++) - { - weighted_sum = weighted_sum + total_sum - n * arr[n - i]; - if (weighted_sum > max_weighted_sum) - max_weighted_sum = weighted_sum; - } - - printf("%d\n", max_weighted_sum); -} - -int main(int argc, char *argv[]) -{ - if (argc != 2) - { - printf( - "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")\n"); - return 1; - } - - calculate_maximum_rotation(argv[1]); - return 0; -} - -``` - -{% endraw %} - -Maximum Array Rotation in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/cobol/index.md b/docs/projects/maximum-array-rotation/cobol/index.md deleted file mode 100644 index 6bc487c4e3..0000000000 --- a/docs/projects/maximum-array-rotation/cobol/index.md +++ /dev/null @@ -1,150 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- maximum-array-rotation -title: Maximum Array Rotation in COBOL -title1: Maximum Array -title2: Rotation in COBOL ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. maximum-array-rotation. - -data division. -working-storage section. - -01 ws-input pic x(200). -01 ws-temp pic x(200). -01 ws-pos pic 9(4) value 1. - -01 ws-n pic 9(4) value 0. -01 ws-i pic 9(4). -01 ws-j pic 9(4). -01 ws-k pic 9(4). - -01 ws-max-sum pic s9(18) value 0. -01 ws-sum pic s9(18) value 0. - -01 ws-arr occurs 50 times pic s9(9). -01 ws-rotated occurs 50 times pic s9(9). - -01 ws-num pic s9(9). - -01 ws-out pic -(9)9. - -01 ws-valid pic x value "y". - 88 is-valid value "y". - 88 is-invalid value "n". - -procedure division. -main. - accept ws-input from argument-value - - if ws-input = spaces - perform show-usage - stop run - end-if - - perform parse-input - - if is-invalid - perform show-usage - stop run - end-if - - perform compute-maximum-rotation - - move ws-max-sum to ws-out - display function trim(ws-out) - stop run. - -parse-input. - set is-valid to true - move 0 to ws-n - move 1 to ws-pos - move ws-input to ws-temp - - perform until ws-pos > function length(function trim(ws-temp)) - - unstring ws-temp - delimited by "," - into ws-num - with pointer ws-pos - end-unstring - - add 1 to ws-n - move ws-num to ws-arr(ws-n) - - end-perform - - if ws-n = 0 - set is-invalid to true - end-if. - -compute-maximum-rotation. - move 0 to ws-max-sum - - perform varying ws-k from 0 by 1 until ws-k >= ws-n - - move 0 to ws-sum - - perform varying ws-i from 1 by 1 until ws-i > ws-n - - compute ws-j = ws-i + ws-k - if ws-j > ws-n - compute ws-j = ws-j - ws-n - end-if - - compute ws-sum = ws-sum + ws-arr(ws-j) * (ws-i - 1) - - end-perform - - if ws-sum > ws-max-sum - move ws-sum to ws-max-sum - end-if - - end-perform. - -show-usage. - display 'Usage: please provide a list of integers (e.g. "8, 3, 1, 2")'. -``` - -{% endraw %} - -Maximum Array Rotation in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/commodore-basic/index.md b/docs/projects/maximum-array-rotation/commodore-basic/index.md deleted file mode 100644 index 1ad3baa833..0000000000 --- a/docs/projects/maximum-array-rotation/commodore-basic/index.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-14 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2023-10-14 -layout: default -tags: -- commodore-basic -- maximum-array-rotation -title: Maximum Array Rotation in Commodore BASIC -title1: Maximum Array Rotation -title2: in Commodore BASIC ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -20 GOSUB 2000: REM Get array -25 REM Error if invalid or not end of input/value -30 IF V = 0 OR C >= 0 THEN GOTO 200 -40 GOSUB 3000: REM Perform maximum array rotation -50 S$ = STR$(WM) -60 IF WM >= 0 THEN S$ = MID$(S$, 2) -70 PRINT S$ -80 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide a list of integers "; -220 PRINT "(e.g. "; Q$; "8, 3, 1, 2"; Q$; ")" -230 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Maximum array rotation -3001 REM Inputs: -3002 REM - A contains array -3003 REM - NA contains size of array -3004 REM Outputs: WM contains answer -3010 REM Calculate initial sum and inital array rotation -3020 S = 0 -3030 W = 0 -3040 IF NA < 1 THEN GOTO 3090 -3050 FOR I = 0 TO NA - 1 -3060 S = S + A(I) -3070 W = W + I * A(I) -3080 NEXT I -3090 REM Initialize maximum array rotation -3110 WM = W -3120 IF NA < 2 THEN GOTO 3180 -3130 REM Adjust array rotation and update maximum -3140 FOR I = 0 TO NA - 2 -3150 W = W + NA * A(I) - S -3160 IF W > WM THEN WM = W -3170 NEXT I -3180 RETURN - -``` - -{% endraw %} - -Maximum Array Rotation in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/euphoria/index.md b/docs/projects/maximum-array-rotation/euphoria/index.md deleted file mode 100644 index c58d083132..0000000000 --- a/docs/projects/maximum-array-rotation/euphoria/index.md +++ /dev/null @@ -1,197 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-25 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2023-02-25 -layout: default -tags: -- euphoria -- maximum-array-rotation -title: Maximum Array Rotation in Euphoria -title1: Maximum Array -title2: Rotation in Euphoria ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/math.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts(STDOUT, "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")\n") - abort(0) -end procedure - --- Find maximum array rotation, max{W(k), k=0..N-1}, where: --- --- W(k) = sum{i*a[i+k mod N], i=0..N-1} --- --- The value of W(k) can be calculated from W(k-1) as follows: --- --- W(k) = W(k-1) - S + N*a[k-1] --- --- where: --- --- S = sum{a[i], i=0..N-1} = sum{a[i+x mod N], i=0..N-1} --- --- where: x is any arbitary value --- --- Proof: --- --- - Set up initial assumption for W(k): --- --- W(k-1) - S + N*a[k-1] = sum{i*a[i+k-1 mod N], i=0..N-1} - sum{a[i+k-1 mod N}, i=0..N-1} + N*a[k-1] --- --- - Combine the two sums: --- --- = sum{(i-1)*a[i+k-1 mod N], i=0..N-1} + N*a[k-1] --- --- - Pull out the i=0 term: --- = -a[k-1] + sum{(i-1)*a[i+k-1 mod N], i=1..N-1} + N*a[k-1] --- --- - Combine the a[k-1] terms: --- --- = sum{(i-1}*a[i+k-1 mod N], i=1..N-1) + (N-1)*a[k-1] --- --- - Change indexing from i=1..N-1 to 0..N-2: --- --- = sum{i*a[i+k mod N], i=0..N-2} + (N-1)*a[k-1] --- --- - Bring the i=N-1 term back into the sum since N-1+k mod N equals k-1: --- --- = sum{i*a[i+k mod N], i=0..N-1} --- --- - The above equals W(k) -function maximum_array_rotation(sequence values) - -- Calculate sum and initial array rotation - integer s = 0 - integer w = 0 - integer n = length(values) - for i = 1 to n - do - s += values[i] - w += (i - 1) * values[i] - end for - - -- Initialize maximum array rotation - integer wmax = w - - -- Adjust array rotation and update maximum - for i = 1 to n - 1 - do - w += n * values[i] - s - wmax = max({w, wmax}) - end for - - return wmax -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int_list(argv[4]) -sequence values = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] -then - usage() -end if - --- Find maximum array rotation and display result -integer value = maximum_array_rotation(values) -printf(STDOUT, "%d\n", value) - -``` - -{% endraw %} - -Maximum Array Rotation in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/f-sharp/index.md b/docs/projects/maximum-array-rotation/f-sharp/index.md deleted file mode 100644 index d52381745f..0000000000 --- a/docs/projects/maximum-array-rotation/f-sharp/index.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-09 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-04-09 -layout: default -tags: -- f-sharp -- maximum-array-rotation -title: Maximum Array Rotation in F# -title1: Maximum Array -title2: Rotation in F# ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module MaximumArrayRotation = - let run (arr: int[]) = - let n = int64 arr.Length - - if n = 0L then - 0L - else - let sumAll = Array.sumBy int64 arr - let r0 = arr |> Array.indexed |> Array.sumBy (fun (i, v) -> int64 i * int64 v) - - seq { 1 .. int n - 1 } - |> Seq.scan (fun prevSum i -> prevSum + sumAll - n * int64 arr[int n - i]) r0 - |> Seq.max - -module Helpers = - let usage = "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")" - - let private (|IntArray|_|) (s: string) = - let parts = s.Split(',', StringSplitOptions.RemoveEmptyEntries) - - let rec parseAll i acc = - if i = parts.Length then - List.rev acc |> List.toArray |> Some - else - match parts[i] |> _.Trim() |> Int32.TryParse with - | true, n -> parseAll (i + 1) (n :: acc) - | false, _ -> None - - if parts.Length = 0 then None else parseAll 0 [] - - let parseArgs argv = - match argv with - | [| IntArray numbers |] -> Ok(numbers) - | _ -> Error usage - - - let handleResult = - function - | Ok result -> - printfn "%d" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map MaximumArrayRotation.run - |> Helpers.handleResult - -``` - -{% endraw %} - -Maximum Array Rotation in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/go/index.md b/docs/projects/maximum-array-rotation/go/index.md deleted file mode 100644 index 7f95c81758..0000000000 --- a/docs/projects/maximum-array-rotation/go/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- dangrabo -date: 2025-02-18 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2025-02-18 -layout: default -tags: -- go -- maximum-array-rotation -title: Maximum Array Rotation in Go -title1: Maximum Array -title2: Rotation in Go ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "unicode" -) - -func main() { - if len(os.Args) != 2 { - printError() - } else { - if len(createSlice()) == 0 { - printError() - } else { - fmt.Println(getMaxWeightedSum(createSlice())) - } - } -} - -func createSlice() (slice []int) { - stringSlice := os.Args[1] - for _, char := range stringSlice { - if unicode.IsDigit(char) { - slice = append(slice, int(char)-'0') - } - } - return -} - -func getWeightedSum(slice []int) (sum int) { - for i, num := range slice { - sum += i * num - } - return -} - -func getMaxWeightedSum(slice []int) (max int) { - max = 0 - for i := 0; i < len(slice); i++ { - if getWeightedSum(slice) > max { - max = getWeightedSum(slice) - } - slice = rotateSlice(slice) - } - return -} - -func rotateSlice(slice []int) (rotatedSlice []int) { - first := slice[0] - slice = slice[1:] - slice = append(slice, first) - rotatedSlice = slice - return -} - -func printError() { - fmt.Println("Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")") -} - -``` - -{% endraw %} - -Maximum Array Rotation in [Go](/languages/go) was written by: - -- dangrabo - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/haskell/index.md b/docs/projects/maximum-array-rotation/haskell/index.md deleted file mode 100644 index b41219244a..0000000000 --- a/docs/projects/maximum-array-rotation/haskell/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-04-29 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-04-29 -layout: default -tags: -- haskell -- maximum-array-rotation -title: Maximum Array Rotation in Haskell -title1: Maximum Array -title2: Rotation in Haskell ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read -import Data.List (tails) - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - -verifyListNotEmpty :: [a] -> Maybe [a] -verifyListNotEmpty [] = Nothing -verifyListNotEmpty xs = Just xs - --- get all rotated versions of the list xs -rotations :: [a] -> [[a]] -rotations xs = - let n = length xs - in take n $ map (take n) $ tails (cycle xs) - -main :: IO () -main = do - args <- getArgs - let xs = headMaybe args >>= stringToListMaybe >>= verifyListNotEmpty - case xs of - Just xs -> print $ maximum $ map (sum . zipWith (*) [0..]) $ rotations xs - Nothing -> putStrLn "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")" - - -``` - -{% endraw %} - -Maximum Array Rotation in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/index.md b/docs/projects/maximum-array-rotation/index.md deleted file mode 100644 index 1fc3ff024b..0000000000 --- a/docs/projects/maximum-array-rotation/index.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -date: 2021-10-05 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- maximum-array-rotation -title: Maximum Array Rotation -title1: Maximum Array -title2: Rotation ---- - - - -Welcome to the Maximum Array Rotation page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -## Description - -Given a list, L, of integers, we can compute the weighted sum, W, as followed: - -``` -W = L[0] * 0 + L[1] * 1 + ... + L[N - 1] * (N - 1) -``` - -In this case, N is the length of the list. As a result, if the list contained 5 items, -the last term in the list would be multiplied by 4. - -Given that we can compute the weighted sum, the purpose of this project is to -find the maximum array rotation. In other words, if we were to rotate the list N -times (note: rotation direction does not matter), what's the largest weighted sum -we could get? Here's what that would look like with this list (2, 8, 3, 1): - -1. `(2, 8, 3, 1) = (2 * 0) + (8 * 1) + (3 * 2) + (1 * 3) = 0 + 8 + 6 + 3 = 17` -2. `(1, 2, 8, 3) = (1 * 0) + (2 * 1) + (8 * 2) + (3 * 3) = 0 + 2 + 16 + 9 = 27` -3. `(3, 1, 2, 8) = (3 * 0) + (1 * 1) + (2 * 2) + (8 * 3) = 0 + 1 + 4 + 24 = 29` -4. `(8, 3, 1, 2) = (8 * 0) + (3 * 1) + (1 * 2) + (2 * 3) = 0 + 3 + 2 + 6 = 11` - -Ultimately, we want to find the largest sum. That appears to happen during our -second rotation (i.e. line 3) where we get a weighted sum of 29. - - -## Requirements - -A Maximum Array Rotation program should function as follows: - -```shell -$ ./maximum-array-rotation.lang "8, 3, 1, 2" -$ 29 -``` - -In other words, the user should call the program on the command line with a string -of comma separeted integers. If done properly, the program should output the -Maximum Array Rotation. See the following testing section for more specific requirements. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Maximum Array Rotation. -In order to keep things simple, we split up the testing as follows: - -- Maximimum Array Rotation Valid Tests -- Maximimum Array Rotation Invalid Tests - -### Maximimum Array Rotation Valid Tests - -| Description | Input | -| ----------- | ----- | -| Sample Input No Rotation | "3, 1, 2, 8" | -| Sample Input One Rotation | "1, 2, 8, 3" | -| Sample Input Many Rotations | "8, 3, 1, 2" | - -All of these tests should output the following: - -``` -29 -``` - -### Maximimum Array Rotation Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | - -All of these tests should output the following: - -``` -Usage: please provide a list of integers (e.g. "8, 3, 1, 2") -``` - - -## Articles - -There are 28 articles: - -- [Maximum Array Rotation in ALGOL 60](/projects/maximum-array-rotation/algol60) -- [Maximum Array Rotation in ALGOL 68](/projects/maximum-array-rotation/algol68) -- [Maximum Array Rotation in AWK](/projects/maximum-array-rotation/awk) -- [Maximum Array Rotation in Ada](/projects/maximum-array-rotation/ada) -- [Maximum Array Rotation in Beef](/projects/maximum-array-rotation/beef) -- [Maximum Array Rotation in C](/projects/maximum-array-rotation/c) -- [Maximum Array Rotation in C#](/projects/maximum-array-rotation/c-sharp) -- [Maximum Array Rotation in C++](/projects/maximum-array-rotation/c-plus-plus) -- [Maximum Array Rotation in COBOL](/projects/maximum-array-rotation/cobol) -- [Maximum Array Rotation in Commodore BASIC](/projects/maximum-array-rotation/commodore-basic) -- [Maximum Array Rotation in Euphoria](/projects/maximum-array-rotation/euphoria) -- [Maximum Array Rotation in F#](/projects/maximum-array-rotation/f-sharp) -- [Maximum Array Rotation in Go](/projects/maximum-array-rotation/go) -- [Maximum Array Rotation in Haskell](/projects/maximum-array-rotation/haskell) -- [Maximum Array Rotation in Java](/projects/maximum-array-rotation/java) -- [Maximum Array Rotation in JavaScript](/projects/maximum-array-rotation/javascript) -- [Maximum Array Rotation in Mathematica](/projects/maximum-array-rotation/mathematica) -- [Maximum Array Rotation in PHP](/projects/maximum-array-rotation/php) -- [Maximum Array Rotation in Pascal](/projects/maximum-array-rotation/pascal) -- [Maximum Array Rotation in PowerShell](/projects/maximum-array-rotation/powershell) -- [Maximum Array Rotation in Python](/projects/maximum-array-rotation/python) -- [Maximum Array Rotation in Ruby](/projects/maximum-array-rotation/ruby) -- [Maximum Array Rotation in Rust](/projects/maximum-array-rotation/rust) -- [Maximum Array Rotation in Swift](/projects/maximum-array-rotation/swift) -- [Maximum Array Rotation in Tcl](/projects/maximum-array-rotation/tcl) -- [Maximum Array Rotation in TypeScript](/projects/maximum-array-rotation/typescript) -- [Maximum Array Rotation in Visual Basic](/projects/maximum-array-rotation/visual-basic) -- [Maximum Array Rotation in m4](/projects/maximum-array-rotation/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/java/index.md b/docs/projects/maximum-array-rotation/java/index.md deleted file mode 100644 index 2178e81723..0000000000 --- a/docs/projects/maximum-array-rotation/java/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- java -- maximum-array-rotation -title: Maximum Array Rotation in Java -title1: Maximum Array -title2: Rotation in Java ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.Arrays; - -public class MaximumArrayRotation { - public static void main(String[] args) { - int[] input = parse(args); - System.out.println(maximumRotationSum(input)); - } - - private static void usage() { - System.err.println("Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")"); - System.exit(1); - } - - private static int[] parse(String[] args) { - if (args.length != 1 || args[0] == null || args[0].isBlank()) { - usage(); - } - - try { - int[] values = Arrays.stream(args[0].split(",")) - .map(String::trim) - .mapToInt(Integer::parseInt) - .toArray(); - - if (values.length == 0) { - usage(); - } - - return values; - - } catch (NumberFormatException e) { - usage(); - return new int[0]; // unreachable - } - } - - private static long maximumRotationSum(int[] values) { - int n = values.length; - if (n == 0) { - usage(); - } - - long sum = 0; - long currentSum = 0; - - for (int i = 0; i < n; i++) { - sum += values[i]; - currentSum += (long) values[i] * i; - } - - long maxSum = currentSum; - - for (int i = 1; i < n; i++) { - currentSum += sum - (long) n * values[n - i]; - maxSum = Math.max(maxSum, currentSum); - } - - return maxSum; - } -} -``` - -{% endraw %} - -Maximum Array Rotation in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/javascript/index.md b/docs/projects/maximum-array-rotation/javascript/index.md deleted file mode 100644 index 7d95f342a9..0000000000 --- a/docs/projects/maximum-array-rotation/javascript/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- javascript -- maximum-array-rotation -title: Maximum Array Rotation in JavaScript -title1: Maximum Array Rotation -title2: in JavaScript ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -"use strict"; - -const USAGE = 'Usage: please provide a list of integers (e.g. "8, 3, 1, 2")'; - -const parse = (s) => - s - .split(",") - .filter((x) => x.trim() !== "") - .map((x) => Number(x.trim())); - -const maxArrayRotation = (arr) => { - const n = arr.length; - if (n === 0) return 0; - - let currentSum = 0; - let totalSum = 0; - - for (let i = 0; i < n; i++) { - totalSum += arr[i]; - currentSum += i * arr[i]; - } - - let maxSum = currentSum; - - for (let k = 1; k < n; k++) { - const droppedValue = arr[n - k]; - currentSum = currentSum + totalSum - n * droppedValue; - - if (currentSum > maxSum) { - maxSum = currentSum; - } - } - - return maxSum; -}; - -const run = () => { - const [, , input] = process.argv; - - if (!input) { - console.error(USAGE); - process.exit(1); - } - - const arr = parse(input); - - if (arr.length === 0 || arr.some(Number.isNaN)) { - console.error(USAGE); - process.exit(1); - } - - console.log(maxArrayRotation(arr)); -}; - -run(); - -``` - -{% endraw %} - -Maximum Array Rotation in [JavaScript](/languages/javascript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/m4/index.md b/docs/projects/maximum-array-rotation/m4/index.md deleted file mode 100644 index 80e4b7bf7f..0000000000 --- a/docs/projects/maximum-array-rotation/m4/index.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-09-13 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2025-09-13 -layout: default -tags: -- m4 -- maximum-array-rotation -title: Maximum Array Rotation in m4 -title1: Maximum Array -title2: Rotation in m4 ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of integers (e.g. "8, 3, 1, 2") -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl M4 does not have infinity so choose smallest integer value as minus infinity -define(`MINUS_INF', -2147483648) - -dnl max(a, b) -define(`max', `ifelse(eval($1 > $2), 1, `$1', `$2')') - -dnl maximum_array_rotation(varname): -dnl wmax = -infinity -dnl for n = 0 to varname[length] - 1: -dnl w = array_rotation_sum(varname, n, varname[length]) -dnl wmax = max(wmax, w) -dnl return wmax -define(`maximum_array_rotation', `_maxmimum_array_rotation(`$1', 0, MINUS_INF)') -define(`_maxmimum_array_rotation', -`ifelse( -eval($2 >= array_get(`$1', `length')), 1, `$3', -`_maxmimum_array_rotation(`$1', incr($2), - max($3, array_rotation_sum(`$1', $2, array_get(`$1', `length'))))'`'dnl -)'dnl -) - -dnl array_rotation_sum(varname, offset, mod): -dnl w = 0 -dnl for n = 0 to mod - 1: -dnl w = w + n * varname[(n + offset) % mod] -dnl return w -define(`array_rotation_sum', `_array_rotation_sum(`$1', $2, $3, 0, 0)') -define(`_array_rotation_sum', -`ifelse( -eval($4 >= $3), 1, `$5', -`_array_rotation_sum(`$1', $2, $3, incr($4), - eval($5 + $4 * array_get(`$1', eval(($4 + $2) % $3))))'`'dnl -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !parse_int_list(`arr', ARGV1)), 1, `show_usage()')dnl -maximum_array_rotation(`arr') - -``` - -{% endraw %} - -Maximum Array Rotation in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/mathematica/index.md b/docs/projects/maximum-array-rotation/mathematica/index.md deleted file mode 100644 index abef561e89..0000000000 --- a/docs/projects/maximum-array-rotation/mathematica/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-19 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2023-01-19 -layout: default -tags: -- mathematica -- maximum-array-rotation -title: Maximum Array Rotation in Mathematica -title1: Maximum Array Rotation -title2: in Mathematica ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual maximum array rotation operating on Mathematica lists: *) - -longestArrayRotation = a \[Function] Max @@ - Table[ - Dot[ (* inner product *) - RotateRight[a, i], (* rotated input list *) - Range[0, Length[a] - 1](* list of weights *)], - {i, Length[a]}]; - -(* The outer function provides the 'user interface': *) - -longestArrayRotationMain = l \[Function] - Module[{e = "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")"}, - Catch[ - longestArrayRotation @@ Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct argument to array rotation *) - {StringSplit[If[StringLength[l] > 0, l, Throw[e]], ", "]}, - {-1} (* at each leaf *)]]]; - - -(* Valid Tests *) - -Print /@ longestArrayRotationMain /@ { - "3, 1, 2, 8", - "1, 2, 8, 3", - "8, 3, 1, 2" - }; - - -(* Invalid Tests *) - -longestArrayRotationMain[""] - -``` - -{% endraw %} - -Maximum Array Rotation in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/pascal/index.md b/docs/projects/maximum-array-rotation/pascal/index.md deleted file mode 100644 index 657020676b..0000000000 --- a/docs/projects/maximum-array-rotation/pascal/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-21 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2025-07-21 -layout: default -tags: -- maximum-array-rotation -- pascal -title: Maximum Array Rotation in Pascal -title1: Maximum Array -title2: Rotation in Pascal ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program MaximumArrayRotation; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of integers (e.g. "8, 3, 1, 2")'); - Halt(1); -end; - -type - TIntegerList = specialize TList; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) = 0 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function MaximumRotationSum(const Numbers: TIntegerList): integer; -var - N, i, TotalSum, CurrentWeightedSum, MaxWeightedSum: integer; -begin - N := Numbers.Count; - if N = 0 then - ShowUsage; - - TotalSum := 0; - CurrentWeightedSum := 0; - for i := 0 to N - 1 do - begin - TotalSum += Numbers[i]; - CurrentWeightedSum += Numbers[i] * i; - end; - - MaxWeightedSum := CurrentWeightedSum; - - for i := 1 to N - 1 do - begin - CurrentWeightedSum := CurrentWeightedSum + TotalSum - N * Numbers[N - i]; - if MaxWeightedSum < CurrentWeightedSum then - MaxWeightedSum := CurrentWeightedSum; - end; - - Result := MaxWeightedSum; -end; - -var - InputList: TIntegerList; -begin - if ParamCount <> 1 then - ShowUsage; - - InputList := ParseIntegerList(ParamStr(1)); - try - Writeln(MaximumRotationSum(InputList)); - finally - InputList.Free; - end; -end. - -``` - -{% endraw %} - -Maximum Array Rotation in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/php/index.md b/docs/projects/maximum-array-rotation/php/index.md deleted file mode 100644 index 53b3a20d89..0000000000 --- a/docs/projects/maximum-array-rotation/php/index.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- maximum-array-rotation -- php -title: Maximum Array Rotation in PHP -title1: Maximum Array -title2: Rotation in PHP ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - - -// Find maximum array rotation, max{W(k), k=0..N-1}, where: -// -// W(k) = sum{i*a[i+k mod N], i=0..N-1} -// -// The value of W(k) can be calculated from W(k-1) as follows: -// -// W(k) = W(k-1) - S + N*a[k-1] -// -// where: -// -// S = sum{a[i], i=0..N-1} = sum{a[i+x mod N], i=0..N-1} -// -// where: x is any arbitary value -// -// Proof: -// -// - Set up initial assumption for W(k): -// -// W(k-1) - S + N*a[k-1] = sum{i*a[i+k-1 mod N], i=0..N-1} - sum{a[i+k-1 mod N}, i=0..N-1} + N*a[k-1] -// -// - Combine the two sums: -// -// = sum{(i-1)*a[i+k-1 mod N], i=0..N-1} + N*a[k-1] -// -// - Pull out the i=0 term: -// = -a[k-1] + sum{(i-1)*a[i+k-1 mod N], i=1..N-1} + N*a[k-1] -// -// - Combine the a[k-1] terms: -// -// = sum{(i-1}*a[i+k-1 mod N], i=1..N-1) + (N-1)*a[k-1] -// -// - Change indexing from i=1..N-1 to 0..N-2: -// -// = sum{i*a[i+k mod N], i=0..N-2} + (N-1)*a[k-1] -// -// - Bring the i=N-1 term back into the sum since N-1+k mod N equals k-1: -// -// = sum{i*a[i+k mod N], i=0..N-1} -// -// - The above equals W(k) -function maximum_array_rotation($values) -{ - // Calculate sum and initial array rotation - $s = array_sum($values); - $w = 0; - foreach ($values as $i => $value) - { - $w += $i * $value; - } - - // Initialize maximum array rotation - $wmax = $w; - - // Adjust array rotation and update maximum - $n = count($values); - foreach (array_slice($values, 0, $n - 1) as $value) - { - $w += $n * $value - $s; - $wmax = max($w, $wmax); - } - - return $wmax; -} - -// Exit if too few arguments -if (count($argv) < 2) -{ - usage(); -} - -// Parse 1st command-line argument. Exit if invalid -$values = parse_int_array($argv[1]); -if ($values === FALSE) -{ - usage(); -} - -// Calculate maximum array rotation and display -$max_value = maximum_array_rotation($values); -echo "$max_value\n"; - -``` - -{% endraw %} - -Maximum Array Rotation in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/powershell/index.md b/docs/projects/maximum-array-rotation/powershell/index.md deleted file mode 100644 index 147858523b..0000000000 --- a/docs/projects/maximum-array-rotation/powershell/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-16 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2025-07-16 -layout: default -tags: -- maximum-array-rotation -- powershell -title: Maximum Array Rotation in PowerShell -title1: Maximum Array Rotation -title2: in PowerShell ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of integers (e.g. "8, 3, 1, 2")' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -function Invoke-MaximumArrayRotation([array]$Values) { - # Calculate sum and initial array rotation - $s = ($Values | Measure-Object -Sum).Sum - $w = 0 - for ($i = 0; $i -lt $Values.Length; $i++) { - $w += $i * $Values[$i] - } - - # Initialize maximum array rotation - $wMax = $w - - # Adjust array rotation and update maximum - $n = $Values.Length - for ($i = 0; $i -lt ($n - 1); $i++) { - $w += $n * $Values[$i] - $s - $wMax = [int][Math]::Max($wMax, $w) - } - - $wMax -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $values = Parse-IntList $args[0] -} catch { - Show-Usage -} - -$maxValue = Invoke-MaximumArrayRotation $values -Write-Host $maxValue - -``` - -{% endraw %} - -Maximum Array Rotation in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/python/index.md b/docs/projects/maximum-array-rotation/python/index.md deleted file mode 100644 index 811bc49f9c..0000000000 --- a/docs/projects/maximum-array-rotation/python/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Tanisha Banik -date: 2021-10-05 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2022-05-10 -layout: default -tags: -- maximum-array-rotation -- python -title: Maximum Array Rotation in Python -title1: Maximum Array -title2: Rotation in Python ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - -def findMax(arr): - maxSum = 0 - for i in range(len(arr)): - val = arr.pop(0) - arr.append(val) - sum_ = [ele*j for j,ele in enumerate(arr)] - sum_ = sum(sum_) - if sum_ > maxSum: - maxSum = sum_ - return maxSum - -try: - arr = [int(ele) for ele in sys.argv[1].split(",")] - print(str(findMax(arr))) - -except: - print('Usage: please provide a list of integers (e.g. "8, 3, 1, 2")') - -``` - -{% endraw %} - -Maximum Array Rotation in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Tanisha Banik - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/ruby/index.md b/docs/projects/maximum-array-rotation/ruby/index.md deleted file mode 100644 index 8fcab04903..0000000000 --- a/docs/projects/maximum-array-rotation/ruby/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- maximum-array-rotation -- ruby -title: Maximum Array Rotation in Ruby -title1: Maximum Array -title2: Rotation in Ruby ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = 'Usage: please provide a list of integers (e.g. "8, 3, 1, 2")' - -def usage! - warn USAGE - exit 1 -end - -def parse_list(str) - str.split(",").map { Integer(it.strip) } -rescue ArgumentError, NoMethodError - usage! -end - -def max_rotation_sum(arr) - n = arr.size - total_sum = arr.sum - current = arr.each_with_index.sum { |v, i| i * v } - - max = current - - (1...n).each do |i| - last = arr[n - i] - current += total_sum - n * last - max = current if current > max - end - - max -end - -raw = ARGV.first -usage! if raw.nil? || raw.strip.empty? - -arr = parse_list(raw) - -puts max_rotation_sum(arr) - -``` - -{% endraw %} - -Maximum Array Rotation in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/rust/index.md b/docs/projects/maximum-array-rotation/rust/index.md deleted file mode 100644 index aebe8f6ef8..0000000000 --- a/docs/projects/maximum-array-rotation/rust/index.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-09 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- maximum-array-rotation -- rust -title: Maximum Array Rotation in Rust -title1: Maximum Array -title2: Rotation in Rust ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::cmp::max; - -fn usage() -> ! { - println!("Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -// Find maximum array rotation, max{W(k), k=0..N-1}, where: -// -// W(k) = sum{i*a[i+k mod N], i=0..N-1} -// -// The value of W(k) can be calculated from W(k-1) as follows: -// -// W(k) = W(k-1) - S + N*a[k-1] -// -// where: -// -// S = sum{a[i], i=0..N-1} = sum{a[i+x mod N], i=0..N-1} -// -// where: x is any arbitary value -// -// Proof: -// -// - Set up initial assumption for W(k): -// -// W(k-1) - S + N*a[k-1] = sum{i*a[i+k-1 mod N], i=0..N-1} - sum{a[i+k-1 mod N}, i=0..N-1} + N*a[k-1] -// -// - Combine the two sums: -// -// = sum{(i-1)*a[i+k-1 mod N], i=0..N-1} + N*a[k-1] -// -// - Pull out the i=0 term: -// = -a[k-1] + sum{(i-1)*a[i+k-1 mod N], i=1..N-1} + N*a[k-1] -// -// - Combine the a[k-1] terms: -// -// = sum{(i-1}*a[i+k-1 mod N], i=1..N-1) + (N-1)*a[k-1] -// -// - Change indexing from i=1..N-1 to 0..N-2: -// -// = sum{i*a[i+k mod N], i=0..N-2} + (N-1)*a[k-1] -// -// - Bring the i=N-1 term back into the sum since N-1+k mod N equals k-1: -// -// = sum{i*a[i+k mod N], i=0..N-1} -// -// - The above equals W(k) -fn maximum_array_rotation(arr: &Vec) -> i32 { - // Calculate sum and initial array rotation - let s: i32 = arr.iter() - .sum::(); - let n: usize = arr.len(); - let mut w: i32 = (0..n) - .map(|i| (i as i32) * arr[i]) - .sum::(); - - // Initialize maximum array rotation - let mut wmax: i32 = w; - - // Adjust array rotation and update maximum - for value in arr.iter().take(n - 1) { - w += (n as i32) * value - s; - wmax = max(w, wmax); - } - - wmax -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Get maximum array rotation and display it - println!("{}", maximum_array_rotation(&arr)); -} - -``` - -{% endraw %} - -Maximum Array Rotation in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/swift/index.md b/docs/projects/maximum-array-rotation/swift/index.md deleted file mode 100644 index f389661c14..0000000000 --- a/docs/projects/maximum-array-rotation/swift/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- maximum-array-rotation -- swift -title: Maximum Array Rotation in Swift -title1: Maximum Array -title2: Rotation in Swift ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of integers (e.g. "8, 3, 1, 2") - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseList(_ input: String?) -> [Int]? { - guard let input = input, !input.isEmpty else { return nil } - - let values = - input - .split(separator: ",") - .map { $0.trimmed } - .compactMap(Int.init) - - return values.isEmpty ? nil : values -} - -func maximumArrayRotation(_ nums: [Int]) -> Int { - let n = nums.count - let totalSum = nums.reduce(0, +) - - var current = nums.enumerated().reduce(0) { $0 + $1.element * $1.offset } - var best = current - - var suffix = nums - - for _ in 1.. - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a list of integers (e.g. "8, 3, 1, 2")} - exit 1 -} - -proc parseList {s} { - set tokens [split [string trim $s] ","] - if {[llength $tokens] < 1} { usage } - - set result {} - - set result {} - foreach token $tokens { - set t [string trim $token] - if {$t eq "" || [catch {expr {int($t)}} val]} usage - lappend result $val - } - return $result -} - -proc maximumRotationSum {numbers} { - set n [llength $numbers] - if {$n == 0} { usage } - - set totalSum 0 - set currentSum 0 - for {set i 0} {$i < $n} {incr i} { - set val [lindex $numbers $i] - incr totalSum $val - incr currentSum [expr {$val * $i}] - } - - set maxSum $currentSum - - for {set i 1} {$i < $n} {incr i} { - set rotatedVal [lindex $numbers [expr {$n - $i}]] - set currentSum [expr {$currentSum + $totalSum - $n * $rotatedVal}] - if {$currentSum > $maxSum} { set maxSum $currentSum } - } - - return $maxSum -} - -if {$argc != 1} { usage } - -set numbers [parseList [lindex $argv 0]] -puts [maximumRotationSum $numbers] - -``` - -{% endraw %} - -Maximum Array Rotation in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/typescript/index.md b/docs/projects/maximum-array-rotation/typescript/index.md deleted file mode 100644 index 6716034b58..0000000000 --- a/docs/projects/maximum-array-rotation/typescript/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- maximum-array-rotation -- typescript -title: Maximum Array Rotation in TypeScript -title1: Maximum Array Rotation -title2: in TypeScript ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function printUsage(): void { - console.error('Usage: please provide a list of integers (e.g. "8, 3, 1, 2")'); - process.exit(1); -} - -function parse(input: string): number[] { - return input - .split(",") - .map((s) => s.trim()) - .filter((s) => s.length > 0) - .map((s) => Number(s)); -} - -function maxArrayRotation(arr: number[]): number { - const n = arr.length; - if (n === 0) return 0; - - let totalSum = 0; - let currentSum = 0; - - for (let i = 0; i < n; i++) { - totalSum += arr[i]; - currentSum += i * arr[i]; - } - - let maxSum = currentSum; - - for (let k = 1; k < n; k++) { - const droppedValue = arr[n - k]; - currentSum = currentSum + totalSum - n * droppedValue; - - if (currentSum > maxSum) { - maxSum = currentSum; - } - } - - return maxSum; -} - -function main(): void { - const input = process.argv[2]; - - if (!input) { - printUsage(); - } - - const arr = parse(input); - - if (arr.length === 0 || arr.some((n) => Number.isNaN(n))) { - printUsage(); - } - - console.log(maxArrayRotation(arr)); -} - -main(); - -``` - -{% endraw %} - -Maximum Array Rotation in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-array-rotation/visual-basic/index.md b/docs/projects/maximum-array-rotation/visual-basic/index.md deleted file mode 100644 index d662543d3e..0000000000 --- a/docs/projects/maximum-array-rotation/visual-basic/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: maximum-array-rotation-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- maximum-array-rotation -- visual-basic -title: Maximum Array Rotation in Visual Basic -title1: Maximum Array Rotation -title2: in Visual Basic ---- - - - -Welcome to the [Maximum Array Rotation](/projects/maximum-array-rotation) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module MaximumArrayRotation - - Private Sub ShowUsage() - Console.Error.WriteLine( - "Usage: please provide a list of integers (e.g. ""8, 3, 1, 2"")" - ) - Environment.Exit(1) - End Sub - - - Private Function ParseList(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - ShowUsage() - End If - - Dim result As New List(Of Integer) - - For Each part In input.Split(","c, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) - - Dim value As Integer - - If Not Integer.TryParse(part, value) OrElse value < 0 Then - ShowUsage() - End If - - result.Add(value) - - Next - - If result.Count = 0 Then - ShowUsage() - End If - - Return result - - End Function - - - Private Function MaximumRotationSum(numbers As List(Of Integer)) As Integer - - Dim n As Integer = numbers.Count - - If n = 0 Then - ShowUsage() - End If - - Dim totalSum As Integer = 0 - Dim currentWeightedSum As Integer = 0 - - For i As Integer = 0 To n - 1 - totalSum += numbers(i) - currentWeightedSum += numbers(i) * i - Next - - Dim maxWeightedSum As Integer = currentWeightedSum - - For i As Integer = 1 To n - 1 - - currentWeightedSum = - currentWeightedSum + totalSum - n * numbers(n - i) - - If currentWeightedSum > maxWeightedSum Then - maxWeightedSum = currentWeightedSum - End If - - Next - - Return maxWeightedSum - - End Function - - - Public Function Main(args As String()) As Integer - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim inputList = ParseList(args(0)) - - Console.WriteLine(MaximumRotationSum(inputList)) - - Return 0 - - End Function - -End Module -``` - -{% endraw %} - -Maximum Array Rotation in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/ada/index.md b/docs/projects/maximum-subarray/ada/index.md deleted file mode 100644 index ebe0107f2f..0000000000 --- a/docs/projects/maximum-subarray/ada/index.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-11 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- ada -- maximum-subarray -title: Maximum Subarray in Ada -title1: Maximum -title2: Subarray in Ada ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Ada](/languages/ada) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ada -pragma Ada_2022; - -with Ada.Text_IO; use Ada.Text_IO; -with Ada.Command_Line; use Ada.Command_Line; -with Ada.Strings.Fixed; use Ada.Strings.Fixed; -with Ada.Strings.Maps; use Ada.Strings.Maps; -with Ada.Containers.Vectors; - -procedure Maximum_Array_Rotation is - - Data_Format_Error : exception; - - function Clean (S : String) return String - is (Trim (S, Ada.Strings.Both)); - - function To_Int (S : String) return Integer is - Cleaned : constant String := Clean (S); - begin - return Integer'Value (Cleaned); - exception - when Constraint_Error => - raise Data_Format_Error with "Invalid integer: '" & Cleaned & "'"; - end To_Int; - - package Integer_Vectors is new - Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); - - subtype Int_List is Integer_Vectors.Vector; - - function To_Int_List (Raw_String : String) return Int_List is - Result : Int_List; - Start : Positive := Raw_String'First; - Finish : Natural; - Seps : constant Character_Set := To_Set (", "); - begin - while Start <= Raw_String'Last loop - Find_Token - (Raw_String, Seps, Start, Ada.Strings.Outside, Start, Finish); - - exit when Start > Finish; - - Result.Append (To_Int (Raw_String (Start .. Finish))); - - Start := Finish + 1; - end loop; - - if Result.Is_Empty then - raise Data_Format_Error with "List is empty"; - end if; - - return Result; - end To_Int_List; - - function Max_Subarray (A : Int_List) return Integer is - Current : Integer; - Best : Integer; - - Max_Element : Integer; - All_Negative : Boolean := True; - First : Boolean := True; - begin - if A.Is_Empty then - return 0; - end if; - - Max_Element := A.Element (A.First_Index); - - for X of A loop - Max_Element := Integer'Max (@, X); - All_Negative := @ and then X < 0; - - if First then - Current := X; - Best := X; - First := False; - else - Current := Integer'Max (X, @ + X); - Best := Integer'Max (@, Current); - end if; - end loop; - - return (if All_Negative then Max_Element else Best); - end Max_Subarray; - - procedure Print_Usage is - begin - Put_Line - ("Usage: Please provide a list of integers in the format: ""1, 2, 3, 4, 5"""); - end Print_Usage; - -begin - if Argument_Count /= 1 then - Print_Usage; - Set_Exit_Status (Failure); - return; - end if; - - begin - declare - Arr : constant Int_List := To_Int_List (Argument (1)); - begin - Put_Line (Integer'Image (Max_Subarray (Arr))); - end; - exception - when Data_Format_Error | Constraint_Error => - Print_Usage; - Set_Exit_Status (Failure); - end; - -end Maximum_Array_Rotation; - -``` - -{% endraw %} - -Maximum Subarray in [Ada](/languages/ada) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/algol60/index.md b/docs/projects/maximum-subarray/algol60/index.md deleted file mode 100644 index bc48213534..0000000000 --- a/docs/projects/maximum-subarray/algol60/index.md +++ /dev/null @@ -1,233 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-18 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- maximum-subarray -title: Maximum Subarray in ALGOL 60 -title1: Maximum Subarray -title2: in ALGOL 60 ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: Please provide a list of integers in the format: " - "\"1, 2, 3, 4, 5\"\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - integer procedure max(a, b); - value a, b; - integer a, b; - begin - max := if a > b then a else b - end max; - - comment Source: - https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted; - integer procedure maximumSubarray(arr, n); - value n; - integer array arr; - integer n; - begin - integer bestSum, currentSum, i; - - bestSum := -maxint - 1; - currentSum := 0; - for i := 1 step 1 until n do - begin - currentSum := arr[i] + max(0, currentSum); - bestSum := max(bestSum, currentSum) - end; - - maximumSubarray := bestSum - end maximumSubarray; - - integer argc, arrLen, result; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 1 then usage; - - comment Find maximum subarray and display result; - result := maximumSubarray(arr, arrLen); - outinteger(1, result); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Maximum Subarray in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/algol68/index.md b/docs/projects/maximum-subarray/algol68/index.md deleted file mode 100644 index 0775d7f555..0000000000 --- a/docs/projects/maximum-subarray/algol68/index.md +++ /dev/null @@ -1,178 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-06 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2023-02-06 -layout: default -tags: -- algol68 -- maximum-subarray -title: Maximum Subarray in ALGOL 68 -title1: Maximum Subarray -title2: in ALGOL 68 ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: printf(($gl$, "Usage: Please provide a list of integers in the format: ""1, 2, 3, 4, 5""")); - -PROC max = (INT a, INT b) INT: (a > b | a | b); - -COMMENT -Find maximum subarray using Kadane's algorithm. -Source: https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted -COMMENT -PROC maximum subarray = (REF []INT values) INT: -( - INT best sum := -max int; - INT current sum := 0; - FOR k TO UPB values - DO - current sum := values[k] + max(0, current sum); - best sum := max(best sum, current sum) - OD; - - best sum -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result -THEN - usage; - stop -FI; - -# Calculate maximum subarray and display # -INT max value = maximum subarray(values); -printf(($gl$, whole(max value, 0))) - -``` - -{% endraw %} - -Maximum Subarray in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/awk/index.md b/docs/projects/maximum-subarray/awk/index.md deleted file mode 100644 index 27929091c2..0000000000 --- a/docs/projects/maximum-subarray/awk/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-23 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-04-23 -layout: default -tags: -- awk -- maximum-subarray -title: Maximum Subarray in AWK -title1: Maximum -title2: Subarray in AWK ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -function max(a, b) { - return (a > b) ? a : b -} - -# Find maximum subarray using Kadane's algorithm. -# Source: https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted -function maximum_subarray(arr, n, i, best_sum, current_sum) { - # Awk doesn't have minus infinity, so use large negative number - best_sum = -1e999 - current_sum = 0 - for (i = 1; i <=n ; i++) { - current_sum = arr[i] + max(0, current_sum) - best_sum = max(current_sum, best_sum) - } - - return best_sum -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], arr) - arr_len = length(arr) - if (!arr_len || arr[1] == "ERROR") { - usage() - } - - result = maximum_subarray(arr, arr_len) - printf("%d\n", result) -} - -``` - -{% endraw %} - -Maximum Subarray in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/beef/index.md b/docs/projects/maximum-subarray/beef/index.md deleted file mode 100644 index 0f235181d7..0000000000 --- a/docs/projects/maximum-subarray/beef/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-15 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2024-02-15 -layout: default -tags: -- beef -- maximum-subarray -title: Maximum Subarray in Beef -title1: Maximum Subarray -title2: in Beef ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace MaximumSubarray; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5" - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Find maximum subarray using Kadane's algorithm. - // Source: https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted - public static T MaximumSubarray(List arr) - where T : operator explicit int, operator T + T, IMinMaxValue - where int : operator T <=> T - { - T bestSum = T.MinValue; - T currentSum = default(T); - for (T val in arr) - { - currentSum = val + Math.Max(default(T), currentSum); - bestSum = Math.Max(currentSum, bestSum); - } - - return bestSum; - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - List arr = scope .(); - if (ParseIntList(args[0], arr) case .Err) - { - Usage(); - } - - int32 result = MaximumSubarray(arr); - Console.WriteLine(result); - - return 0; - } -} - -``` - -{% endraw %} - -Maximum Subarray in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/c-plus-plus/index.md b/docs/projects/maximum-subarray/c-plus-plus/index.md deleted file mode 100644 index e275c5442a..0000000000 --- a/docs/projects/maximum-subarray/c-plus-plus/index.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -authors: -- Meet Thakur -- Ștefan-Iulian Alecu -date: 2025-10-11 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- maximum-subarray -title: Maximum Subarray in C++ -title1: Maximum -title2: Subarray in C++ ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cout << "Usage: Please provide a list of integers in the format: \"1, " - "2, 3, 4, 5\"\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.empty() ? std::nullopt : std::make_optional(out); -} - -int max_subarray_sum(const std::vector& arr) { - int best = arr[0]; - int current = 0; - - for (int x : arr) { - current = std::max(x, current + x); - best = std::max(best, current); - } - - return best; -} - -int main(int argc, char* argv[]) { - if (argc < 2) usage(); - - if (auto vec = parse_vec(argv[1]); vec) - std::cout << max_subarray_sum(*vec) << '\n'; - else - usage(); -} -``` - -{% endraw %} - -Maximum Subarray in [C++](/languages/c-plus-plus) was written by: - -- Meet Thakur -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/c-sharp/index.md b/docs/projects/maximum-subarray/c-sharp/index.md deleted file mode 100644 index 20504b7135..0000000000 --- a/docs/projects/maximum-subarray/c-sharp/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-29 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- maximum-subarray -title: Maximum Subarray in C# -title1: Maximum -title2: Subarray in C# ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if ( - args is not [var input] - || string.IsNullOrWhiteSpace(input) - || !TryParseList(input.AsSpan(), out var numbers) -) - return ExitWithUsage(); - -Console.WriteLine(MaximumSubarraySum(numbers)); -return 0; - -static int MaximumSubarraySum(List numbers) -{ - int current = numbers[0]; - int best = numbers[0]; - - for (int i = 1; i < numbers.Count; i++) - { - int v = numbers[i]; - current = Math.Max(v, current + v); - best = Math.Max(current, best); - } - - return best; -} - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return true; -} - -static int ExitWithUsage() -{ - Console.Error.WriteLine( - "Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"" - ); - return 1; -} - -``` - -{% endraw %} - -Maximum Subarray in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/c/index.md b/docs/projects/maximum-subarray/c/index.md deleted file mode 100644 index 8d8a78838e..0000000000 --- a/docs/projects/maximum-subarray/c/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-19 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- maximum-subarray -title: Maximum Subarray in C -title1: Maximum -title2: Subarray in C ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include - -void print_usage() -{ - printf("Usage: Please provide a list of integers in the format: \"1, 2, 3, " - "4, 5\"\n"); -} - -int max_subarray_sum(int *arr, int n) -{ - int max_so_far = INT_MIN; - int max_ending_here = 0; - - for (int i = 0; i < n; i++) - { - max_ending_here += arr[i]; - - if (max_so_far < max_ending_here) - max_so_far = max_ending_here; - - if (max_ending_here < 0) - max_ending_here = 0; - } - - return max_so_far; -} - -int main(int argc, char *argv[]) -{ - if (argc < 2) - { - print_usage(); - return 1; - } - - // Check if input is empty - if (strlen(argv[1]) == 0) - { - print_usage(); - return 1; - } - - // Parse input string - char *token; - int arr[100]; // Assuming a maximum of 100 integers - int count = 0; - - token = strtok(argv[1], ","); - while (token != NULL) - { - arr[count++] = atoi(token); - token = strtok(NULL, ","); - } - - // If less than two integers were provided - if (count == 1) - { - printf("%d\n", arr[0]); - return 0; - } - else if (count < 2) - { - print_usage(); - return 1; - } - - // Calculate maximum subarray sum - int result = max_subarray_sum(arr, count); - - printf("%d\n", result); - - return 0; -} - -``` - -{% endraw %} - -Maximum Subarray in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/cobol/index.md b/docs/projects/maximum-subarray/cobol/index.md deleted file mode 100644 index 2dd2331a40..0000000000 --- a/docs/projects/maximum-subarray/cobol/index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-05 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- cobol -- maximum-subarray -title: Maximum Subarray in COBOL -title1: Maximum Subarray -title2: in COBOL ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. maximum-subarray. - -data division. -working-storage section. - -01 ws-input pic x(200). -01 ws-temp pic x(200). -01 ws-pos pic 9(4) value 1. - -01 ws-n pic 9(4) value 0. -01 ws-i pic 9(4). - -01 ws-num pic s9(9). - -01 ws-arr occurs 100 times pic s9(9). - -01 ws-current-sum pic s9(18) value 0. -01 ws-max-sum pic s9(18) value 0. - -01 ws-has-negative pic x value "n". - 88 has-negative value "y". - 88 no-negative value "n". - -01 ws-out pic -(9)9. - -procedure division. -main. - accept ws-input from argument-value - - if ws-input = spaces - perform show-usage - stop run - end-if - - perform parse-input - - if ws-n < 1 - perform show-usage - stop run - end-if - - perform check-negatives - perform compute-kadane - - move ws-max-sum to ws-out - display function trim(ws-out) - stop run. - -parse-input. - move 0 to ws-n - move 1 to ws-pos - move ws-input to ws-temp - - perform until ws-pos > function length(function trim(ws-temp)) - - unstring ws-temp - delimited by "," - into ws-num - with pointer ws-pos - end-unstring - - add 1 to ws-n - move ws-num to ws-arr(ws-n) - - end-perform. - -check-negatives. - set no-negative to true - - perform varying ws-i from 1 by 1 until ws-i > ws-n - if ws-arr(ws-i) < 0 - set has-negative to true - end-if - end-perform. - - -compute-kadane. - move ws-arr(1) to ws-current-sum - move ws-arr(1) to ws-max-sum - - perform varying ws-i from 2 by 1 until ws-i > ws-n - - if ws-current-sum + ws-arr(ws-i) > ws-arr(ws-i) - add ws-arr(ws-i) to ws-current-sum - else - move ws-arr(ws-i) to ws-current-sum - end-if - - if ws-current-sum > ws-max-sum - move ws-current-sum to ws-max-sum - end-if - - end-perform - - if no-negative - move 0 to ws-max-sum - perform varying ws-i from 1 by 1 until ws-i > ws-n - add ws-arr(ws-i) to ws-max-sum - end-perform - end-if. - -show-usage. - display 'Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"'. -``` - -{% endraw %} - -Maximum Subarray in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/commodore-basic/index.md b/docs/projects/maximum-subarray/commodore-basic/index.md deleted file mode 100644 index ae7c9c8b2d..0000000000 --- a/docs/projects/maximum-subarray/commodore-basic/index.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-14 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2023-10-14 -layout: default -tags: -- commodore-basic -- maximum-subarray -title: Maximum Subarray in Commodore BASIC -title1: Maximum Subarray -title2: in Commodore BASIC ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -20 GOSUB 2000: REM Get array -25 REM Error if invalid or not end of input/value -30 IF V = 0 OR C >= 0 THEN GOTO 200 -40 GOSUB 3000: REM Perform maximum subarray -50 S$ = STR$(BS) -60 IF BS >= 0 THEN S$ = MID$(S$, 2) -70 PRINT S$ -80 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: Please provide a list of integers in the format: "; -220 PRINT Q$; "1, 2, 3, 4, 5"; Q$ -230 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Find maximum subarray using Kadane's algorithm. -3001 REM Source: -3002 REM https://en.wikipedia.org/wiki/Maximum_subarray_problem -3003 REM #No_empty_subarrays_admitted -3004 REM Inputs: -3005 REM - A contains array -3006 REM - NA contains size of array -3007 REM Outputs: BS contains answer -3010 REM Initialize best sum to -infinity and current sum to 0 -3020 BS = -1.70141183E38: REM (smallest negative number) -3030 CS = 0 -3040 IF NA < 1 THEN BS = 0: GOTO 3130 -3050 FOR I = 0 TO NA - 1 -3060 REM If current sum < 0, set it to current value -3070 REM Else, add current value to current sum -3080 IF CS < 0 THEN CS = 0 -3090 CS = CS + A(I) -3100 REM If current sum greater than best sum, update best sum -3110 IF CS > BS THEN BS = CS -3120 NEXT I -3130 RETURN - -``` - -{% endraw %} - -Maximum Subarray in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/euphoria/index.md b/docs/projects/maximum-subarray/euphoria/index.md deleted file mode 100644 index 5bb8ab9aa5..0000000000 --- a/docs/projects/maximum-subarray/euphoria/index.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-28 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2023-02-28 -layout: default -tags: -- euphoria -- maximum-subarray -title: Maximum Subarray in Euphoria -title1: Maximum Subarray -title2: in Euphoria ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/math.e -include std/mathcons.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts(STDOUT, "Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"\n") - abort(0) -end procedure - --- Find maximum subarray using Kadane's algorithm. --- Source: https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted -function maximum_subarray(sequence values) - atom best_sum = MINF - integer current_sum = 0 - for k = 1 to length(values) - do - current_sum = values[k] + max({0, current_sum}) - best_sum = max({best_sum, current_sum}) - end for - - return best_sum -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int_list(argv[4]) -sequence values = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] -then - usage() -end if - --- Calculate maximum subarray and display -integer max_value = maximum_subarray(values) -printf(STDOUT, "%d\n", max_value) - -``` - -{% endraw %} - -Maximum Subarray in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/f-sharp/index.md b/docs/projects/maximum-subarray/f-sharp/index.md deleted file mode 100644 index 3ce585d1c4..0000000000 --- a/docs/projects/maximum-subarray/f-sharp/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-09 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-04-09 -layout: default -tags: -- f-sharp -- maximum-subarray -title: Maximum Subarray in F# -title1: Maximum -title2: Subarray in F# ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module MaximumSubarray = - let run = - Array.fold (fun (currentMax, globalMax) x -> - let x = int64 x - let newCurrent = max x (currentMax + x) - (newCurrent, max globalMax newCurrent) - ) (0L, Int64.MinValue) - >> snd - -module Helpers = - let usage = - "Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"" - - let private (|IntArray|_|) (s: string) = - let parts = s.Split(',', StringSplitOptions.RemoveEmptyEntries) - - let rec parseAll i acc = - if i = parts.Length then - List.rev acc |> List.toArray |> Some - else - match parts[i] |> _.Trim() |> Int32.TryParse with - | true, n -> parseAll (i + 1) (n :: acc) - | false, _ -> None - - if parts.Length = 0 then None else parseAll 0 [] - - let parseArgs argv = - match argv with - | [| IntArray numbers |] -> Ok(numbers) - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%d" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map MaximumSubarray.run - |> Helpers.handleResult -``` - -{% endraw %} - -Maximum Subarray in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/go/index.md b/docs/projects/maximum-subarray/go/index.md deleted file mode 100644 index cffa42cde2..0000000000 --- a/docs/projects/maximum-subarray/go/index.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -authors: -- Jessica Hebert -date: 2025-10-31 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-10-31 -layout: default -tags: -- go -- maximum-subarray -title: Maximum Subarray in Go -title1: Maximum -title2: Subarray in Go ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" - "strings" -) - -func max(a, b int) int { - if a > b { - return a - } - return b -} - -func main() { - if len(os.Args) < 2 || strings.TrimSpace(os.Args[1]) == "" { - fmt.Println(`Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"`) - return - } - input := strings.Join(os.Args[1:], "") - parts := strings.Split(input, ",") - nums := make([]int, len(parts)) - - for i, p := range parts { - p = strings.TrimSpace(p) - n, _ := strconv.Atoi(p) - nums[i] = n - - } - - maxSum := nums[0] - blockSum := nums[0] - - for i := 1; i < len(nums); i++ { - blockSum = max(nums[i], blockSum+nums[i]) - if maxSum < blockSum { - maxSum = blockSum - - } - - } - fmt.Println(maxSum) - -} - -``` - -{% endraw %} - -Maximum Subarray in [Go](/languages/go) was written by: - -- Jessica Hebert - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/haskell/index.md b/docs/projects/maximum-subarray/haskell/index.md deleted file mode 100644 index f615e50c39..0000000000 --- a/docs/projects/maximum-subarray/haskell/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-04-29 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-04-29 -layout: default -tags: -- haskell -- maximum-subarray -title: Maximum Subarray in Haskell -title1: Maximum Subarray -title2: in Haskell ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - -verifyListNotEmpty :: [a] -> Maybe [a] -verifyListNotEmpty [] = Nothing -verifyListNotEmpty xs = Just xs - -main :: IO () -main = do - args <- getArgs - let xs = headMaybe args >>= stringToListMaybe >>= verifyListNotEmpty - case xs of - Just xs -> print $ maximum $ scanr1 (\x acc -> if acc < 0 then x else x + acc) xs - Nothing -> putStrLn "Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"" - -``` - -{% endraw %} - -Maximum Subarray in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/index.md b/docs/projects/maximum-subarray/index.md deleted file mode 100644 index a2f5cefad5..0000000000 --- a/docs/projects/maximum-subarray/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -date: 2020-10-14 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- maximum-subarray -title: Maximum Subarray -title1: Maximum -title2: Subarray ---- - - - -Welcome to the Maximum Subarray page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Given an array, the maximum subarray is the subarray which gives the maximum sum possible in the array. -Kadane's algorithm is a popular algorithm used to find out this maximum sum value. - -Note: A subarray is any continuous portion of an array. - -For example: - -Given array: `[-1, -2, 1, 2, 3, 4, 5, 23]` - -Max sum value of a subarray: `38` - -Explanation: The subarray `[1, 2, 3, 4, 5, 23]` gives the max sum value. `(1 + 2 + 3 + 4 + 5 + 23 = 38)` - - -## Requirements - -You must write an executable program that accepts a string of comma separated integers on `standard input` via the sys args, and outputs the maximum subarray sum value to `standard output`. - -Note that the Kadane's algorithm assumes that there is atleast 1 negative integer in the array. -If there is no negative integer, then the max subarray sum value is the sum of all the elements of the array. - -Also note that if the input string is empty, then the output is "Usage: Please provide a list of at least two integers to sort in the format: '1, 2, 3, 4, 5'". - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Maximum Subarray. -In order to keep things simple, we split up the testing as follows: - -- Maximum Subarray Valid Tests -- Maximum Subarray Invalid Tests - -### Maximum Subarray Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: One Element | "1" | "1" | -| Sample Input: Many Positive Values | "1, 2, 3" | "6" | -| Sample Input: Many Negative Values | "-1, -2, -3" | "-1" | -| Sample Input: Many Negative Followed By Positive Values | "-2, -1, 3, 4, 5" | "12" | -| Sample Input: Many Alternating Positive And Negative Values | "-1, -4, 2, 3, -3, -4, 9" | "9" | - -### Maximum Subarray Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | - -All of these tests should output the following: - -``` -Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5" -``` - - -## Articles - -There are 28 articles: - -- [Maximum Subarray in ALGOL 60](/projects/maximum-subarray/algol60) -- [Maximum Subarray in ALGOL 68](/projects/maximum-subarray/algol68) -- [Maximum Subarray in AWK](/projects/maximum-subarray/awk) -- [Maximum Subarray in Ada](/projects/maximum-subarray/ada) -- [Maximum Subarray in Beef](/projects/maximum-subarray/beef) -- [Maximum Subarray in C](/projects/maximum-subarray/c) -- [Maximum Subarray in C#](/projects/maximum-subarray/c-sharp) -- [Maximum Subarray in C++](/projects/maximum-subarray/c-plus-plus) -- [Maximum Subarray in COBOL](/projects/maximum-subarray/cobol) -- [Maximum Subarray in Commodore BASIC](/projects/maximum-subarray/commodore-basic) -- [Maximum Subarray in Euphoria](/projects/maximum-subarray/euphoria) -- [Maximum Subarray in F#](/projects/maximum-subarray/f-sharp) -- [Maximum Subarray in Go](/projects/maximum-subarray/go) -- [Maximum Subarray in Haskell](/projects/maximum-subarray/haskell) -- [Maximum Subarray in Java](/projects/maximum-subarray/java) -- [Maximum Subarray in JavaScript](/projects/maximum-subarray/javascript) -- [Maximum Subarray in Mathematica](/projects/maximum-subarray/mathematica) -- [Maximum Subarray in PHP](/projects/maximum-subarray/php) -- [Maximum Subarray in Pascal](/projects/maximum-subarray/pascal) -- [Maximum Subarray in PowerShell](/projects/maximum-subarray/powershell) -- [Maximum Subarray in Python](/projects/maximum-subarray/python) -- [Maximum Subarray in Ruby](/projects/maximum-subarray/ruby) -- [Maximum Subarray in Rust](/projects/maximum-subarray/rust) -- [Maximum Subarray in Swift](/projects/maximum-subarray/swift) -- [Maximum Subarray in Tcl](/projects/maximum-subarray/tcl) -- [Maximum Subarray in TypeScript](/projects/maximum-subarray/typescript) -- [Maximum Subarray in Visual Basic](/projects/maximum-subarray/visual-basic) -- [Maximum Subarray in m4](/projects/maximum-subarray/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/maximum-subarray/java/index.md b/docs/projects/maximum-subarray/java/index.md deleted file mode 100644 index b11404c80a..0000000000 --- a/docs/projects/maximum-subarray/java/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- java -- maximum-subarray -title: Maximum Subarray in Java -title1: Maximum Subarray -title2: in Java ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.Arrays; - -public class MaximumSubarray { - - public static void main(String[] args) { - int[] input = parse(args); - System.out.println(maximumSubarraySum(input)); - } - - private static void usage() { - System.err.println("Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\""); - System.exit(1); - } - - private static int[] parse(String[] args) { - if (args.length != 1 || args[0] == null || args[0].isBlank()) { - usage(); - } - - try { - int[] values = Arrays.stream(args[0].split(",")) - .map(String::trim) - .mapToInt(Integer::parseInt) - .toArray(); - - if (values.length == 0) { - usage(); - } - - return values; - - } catch (NumberFormatException e) { - usage(); - return new int[0]; // unreachable - } - } - - - private static long maximumSubarraySum(int[] numbers) { - if (numbers.length == 0) { - return 0; - } - - int currentSum = numbers[0]; - int maxSum = numbers[0]; - - for (int i = 1; i < numbers.length; i++) { - int number = numbers[i]; - currentSum = Math.max(number, currentSum + number); - maxSum = Math.max(maxSum, currentSum); - } - - return maxSum; - } -} -``` - -{% endraw %} - -Maximum Subarray in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/javascript/index.md b/docs/projects/maximum-subarray/javascript/index.md deleted file mode 100644 index 7e84bb62ae..0000000000 --- a/docs/projects/maximum-subarray/javascript/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Meet Thakur -date: 2025-10-12 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-10-12 -layout: default -tags: -- javascript -- maximum-subarray -title: Maximum Subarray in JavaScript -title1: Maximum Subarray -title2: in JavaScript ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -function printUsage() { - console.log( - 'Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"', - ); -} - -function maxSubarraySum(arr) { - let maxSoFar = -Infinity; - let maxEndingHere = 0; - - for (let num of arr) { - maxEndingHere += num; - - if (maxSoFar < maxEndingHere) { - maxSoFar = maxEndingHere; - } - - if (maxEndingHere < 0) { - maxEndingHere = 0; - } - } - - return maxSoFar; -} - -function main() { - const args = process.argv.slice(2); - - if (args.length < 1 || args[0] === "") { - printUsage(); - process.exit(1); - } - const input = args[0]; - const arr = input.split(",").map((token) => parseInt(token.trim(), 10)); - - if (arr.length === 1) { - console.log(arr[0]); - return; - } else if (arr.length === 0) { - printUsage(); - process.exit(1); - } - const result = maxSubarraySum(arr); - - console.log(result); -} - -main(); - -``` - -{% endraw %} - -Maximum Subarray in [JavaScript](/languages/javascript) was written by: - -- Meet Thakur - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/m4/index.md b/docs/projects/maximum-subarray/m4/index.md deleted file mode 100644 index 88228e0452..0000000000 --- a/docs/projects/maximum-subarray/m4/index.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-09-07 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-09-07 -layout: default -tags: -- m4 -- maximum-subarray -title: Maximum Subarray in m4 -title1: Maximum -title2: Subarray in m4 ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5" -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl M4 does not have infinity so choose smallest integer value as minus infinity -define(`MINUS_INF', -2147483648) - -dnl max(a, b) -define(`max', `ifelse(eval($1 > $2), 1, `$1', `$2')') - -dnl Find maximum subarray using Kadane's algorithm. -dnl Source: https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted -dnl -dnl maximum_subarray(varname): -dnl best_sum = -infinity -dnl current_sum = 0 -dnl for n = 0 to varname[length] - 1 -dnl current_sum = varname[n] + max(0, current_sum) -dnl best_sum = max(current_sum, best_sum) -dnl return best_sum -define(`maximum_subarray', -`pushdef(`current_sum', 0)dnl -_maximum_subarray(`$1', 0, MINUS_INF)`'dnl -popdef(`current_sum')'dnl -) -define(`_maximum_subarray', -`ifelse( -eval($2 >= array_get(`$1', `length')), 1, `$3', -`define(`current_sum', eval(array_get(`$1', $2) + max(0, current_sum)))dnl -_maximum_subarray(`$1', incr($2), max(current_sum, $3))'`'dnl -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !parse_int_list(`arr', ARGV1)), 1, `show_usage()')dnl -maximum_subarray(`arr') - -``` - -{% endraw %} - -Maximum Subarray in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/mathematica/index.md b/docs/projects/maximum-subarray/mathematica/index.md deleted file mode 100644 index a57131d4b7..0000000000 --- a/docs/projects/maximum-subarray/mathematica/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Ben Hekster -- rzuckerm -date: 2023-01-20 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2023-02-06 -layout: default -tags: -- mathematica -- maximum-subarray -title: Maximum Subarray in Mathematica -title1: Maximum Subarray -title2: in Mathematica ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual maximum subarray operating on Mathematica lists, using essentially Kadane's algorithm: *) - -maximumSubarray = a \[Function] Max[ - FoldList[ - Max[#2 (* A[i] *) , #2 + #1 (* A[i] + local-maximum *)] &, - a]]; - -(* The outer function provides the 'user interface': *) - -maximumSubarrayMain = l \[Function] Catch[ - Module[{e = "Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\"", - fromNegativeDigits}, - (* oddly, Mathematica doesn't appear to provide a function which can parse strings representing negative integers *) - fromNegativeDigits = Piecewise[{ - {FromDigits[#], StringMatchQ[#, DigitCharacter ..]}, - {-FromDigits[StringDrop[#, 1]], - StringMatchQ[#, "-" ~~ DigitCharacter ..]}}, - Throw[e]] &; - maximumSubarray @ Map[ - (* convert string to integer, or throw *) - fromNegativeDigits, - (* construct arguments to maximum subarray *) - StringSplit[If[StringLength[l] > 0, l, Throw[e]], ", "], - {-1} (* at each leaf *)]]]; - - -(* Valid Tests *) - -Print /@ maximumSubarrayMain /@ { - "1, 2, 3", - "-1, -2, -3", - "-2, -1, 3, 4, 5", - "-1, -4, 2, 3, -3, -4, 9", - "-1, -4, 2, 9, -3, -4, 9" - }; - - -(* Invalid Tests *) - -maximumSubarrayMain[""] - -``` - -{% endraw %} - -Maximum Subarray in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/pascal/index.md b/docs/projects/maximum-subarray/pascal/index.md deleted file mode 100644 index 4fa3dd6258..0000000000 --- a/docs/projects/maximum-subarray/pascal/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- maximum-subarray -- pascal -title: Maximum Subarray in Pascal -title1: Maximum Subarray -title2: in Pascal ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program MaximumArrayRotation; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"'); - Halt(1); -end; - -type - TIntegerList = specialize TList; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) = 0 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function MaximumSubarraySum(const Numbers: TIntegerList): integer; -var - CurrentSum, MaxSum, Number, i: integer; -begin - if Numbers.Count = 0 then - Exit(0); - - CurrentSum := Numbers[0]; - MaxSum := Numbers[0]; - - for i := 1 to Numbers.Count - 1 do - begin - Number := Numbers[i]; - if (CurrentSum + Number) > Number then - CurrentSum := CurrentSum + Number - else - CurrentSum := Number; - - if CurrentSum > MaxSum then - MaxSum := CurrentSum; - end; - - Result := MaxSum; -end; - -var - InputList: TIntegerList; -begin - if ParamCount <> 1 then - ShowUsage; - - InputList := ParseIntegerList(ParamStr(1)); - try - Writeln(MaximumSubarraySum(InputList)); - finally - InputList.Free; - end; -end. - -``` - -{% endraw %} - -Maximum Subarray in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/php/index.md b/docs/projects/maximum-subarray/php/index.md deleted file mode 100644 index 7fe9aa567b..0000000000 --- a/docs/projects/maximum-subarray/php/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- maximum-subarray -- php -title: Maximum Subarray in PHP -title1: Maximum -title2: Subarray in PHP ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -// Find maximum subarray using Kadane's algorithm. -// Source: https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted -function maximum_subarray($values) -{ - $best_sum = PHP_INT_MIN; - $current_sum = 0; - foreach ($values as $value) - { - $current_sum = $value + max(0, $current_sum); - $best_sum = max($best_sum, $current_sum); - } - - return $best_sum; -} - -// Exit if too few arguments -if (count($argv) < 2) -{ - usage(); -} - -// Parse 1st command-line argument. Exit if invalid -$values = parse_int_array($argv[1]); -if ($values === FALSE) -{ - usage(); -} - -// Calculate maximum subarray and display -$max_value = maximum_subarray($values); -echo "$max_value\n"; - -``` - -{% endraw %} - -Maximum Subarray in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/powershell/index.md b/docs/projects/maximum-subarray/powershell/index.md deleted file mode 100644 index 73188cffc8..0000000000 --- a/docs/projects/maximum-subarray/powershell/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-16 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-07-16 -layout: default -tags: -- maximum-subarray -- powershell -title: Maximum Subarray in PowerShell -title1: Maximum Subarray -title2: in PowerShell ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -# Find maximum subarray using Kadane's algorithm. -# Source: https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted -function Invoke-MaximumSubarray([array]$Values) { - $bestSum = [int]::MinValue - $currentSum = 0 - foreach ($value in $Values) { - $currentSum = $value + [int][Math]::Max(0, $currentSum) - $bestSum = [int][Math]::Max($bestSum, $currentSum) - } - - $bestSum -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $values = Parse-IntList $args[0] -} catch { - Show-Usage -} - -$maxValue = Invoke-MaximumSubarray $values -Write-Host $maxValue - -``` - -{% endraw %} - -Maximum Subarray in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/python/index.md b/docs/projects/maximum-subarray/python/index.md deleted file mode 100644 index 342477e5ad..0000000000 --- a/docs/projects/maximum-subarray/python/index.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -authors: -- Divyansh Agarwal -- Jeremy Grifski -- rzuckerm -date: 2020-10-14 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- maximum-subarray -- python -title: Maximum Subarray in Python -title1: Maximum Subarray -title2: in Python ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys -from typing import List - - -def error_handling(argv: List) -> List[int]: - str_input = (','.join(i for i in argv[1:])).strip() - if str_input == "": - print('Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"') - sys.exit(1) - nums = [int(num) for num in str_input.split(',')] - return nums - - -def maximum_subarray(nums: List[int]) -> int: - local_max = 0 - global_max = nums[0] - for num in nums: - local_max += num - if (local_max < 0): - local_max = 0 - elif global_max < local_max: - global_max = local_max - return global_max - - -if __name__ == "__main__": - nums = error_handling(sys.argv) - print(maximum_subarray(nums)) - -``` - -{% endraw %} - -Maximum Subarray in [Python](/languages/python) was written by: - -- Divyansh Agarwal -- Jeremy Grifski -- rzuckerm - -This article was written by: - -- Divyansh Agarwal -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's look at the code in detail. - -### Main Function - -```python -if __name__ == "__main__": - nums = error_handling(sys.argv) - print(maximum_subarray(nums)) -``` - -This bit of code checks to see if this is the `main` module run. If true, then it calls the `error_handling` -function to convert the command-line arguments to a list of integers. It calls the `maximum_subarray` -function to calculate the maximum subarray value. Finally, it calls the `print` function to display -the value. - -### Error Handling Function - -```python -def error_handling(argv: List) -> List[int]: - str_input = (','.join(i for i in argv[1:])).strip() - if str_input == "": - print('Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"') - sys.exit(1) - nums = [int(num) for num in str_input.split(',')] - return nums -``` - -This bit of code takes a comma-separated string of integers from the command-line (via the `sys.argv`). It then converts the string into an array of integer. It also deals with the edge case which arises when there is no input or the input string is empty (blank string). -If it is empty, the usage is displayed, and the program exits. Otherwise, the command-separated string is converted to a list of integers. - -### Maximum Subarray - -```python -def maximum_subarray(nums: List[int]) -> int: - local_max = 0 - global_max = nums[0] - for num in nums: - local_max += num - if (local_max < 0): - local_max = 0 - elif global_max < local_max: - global_max = local_max - return global_max -``` - -This function implements Kadane's algorithm. It first initializes `global_max` -(the final value to be returned from the function) to the first element of the array (`nums`) -and `local_max` as 0. It then iterates through the array, keeps adding values to `local_max`. -If `local_max` goes to less than 0, then `local_max` is set to 0. Otherwise, if `local_max` -is greater than `global_max`, `global_max` is set to the value of `local_max`. - -Once all the values are processed, `global_max` is returned. - -For example, if `-1, -2, 1, 2, 3` is the input: - -- Initialize `local_max` to `-1` (the first value) and `global_max` to `0`. -- Now, iterator through all of the values. -- For the first two values, the value of `local_max` is `0`: `0 + (-1) < 0` and `0 + (-2) < 0`, so `-1` and `-2` are skipped. -- For the remaining values, `local_max` is accumulated and `global_max` is updated with `local_max`: - - `local_max` is `0 + 1 = 1`, and `1 < 0` is false, so `local_max` is not reset, and `-1 < 1`, so `global_max` is set to `1` - - `local_max` is `1 + 2 = 3`, and `3 < 0` is false, so `local_max` is not reset, and `1 < 3`, so `global_max` is set to `3` - - `local_max` is `3 + 3 = 6`, and `6 < 0` is false, so `local_max` is not reset, and `3 < 6`, so `global_max` is set to `6` -- Finally, `global_max` (`6`) is returned - - -## How to Run the Solution - -If you want to run this program, you can download a copy of [Maximum Subarray in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/maximum_subarray.py). - -Next, make sure you have the [latest Python interpreter](https://www.python.org/downloads/). - -Finally, open a terminal in the directory of the downloaded file and run the following command: - -`python maximum_subarray.py 1,2,3,4` - -Replace `1,2,3,4` with input of your choice (comma separated integers). - -Alternatively, copy the solution into an online [Python interpreter](https://www.online-python.com/) and hit run. diff --git a/docs/projects/maximum-subarray/ruby/index.md b/docs/projects/maximum-subarray/ruby/index.md deleted file mode 100644 index 82fdc03bb7..0000000000 --- a/docs/projects/maximum-subarray/ruby/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- maximum-subarray -- ruby -title: Maximum Subarray in Ruby -title1: Maximum Subarray -title2: in Ruby ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = 'Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"' - -def usage! - warn USAGE - exit 1 -end - -def parse_list(str) - str.split(",").map { Integer(it.strip) } -rescue ArgumentError, NoMethodError - usage! -end - -def max_subarray_sum(arr) - return arr.first if arr.length == 1 - return arr.sum if arr.none?(&:negative?) - - current = max = arr.first - - arr[1..].each do |x| - current = [x, current + x].max - max = [max, current].max - end - - max -end - -raw = ARGV.first -usage! if raw.nil? || raw.strip.empty? - -arr = parse_list(raw) -usage! if arr.length < 1 - -puts max_subarray_sum(arr) - -``` - -{% endraw %} - -Maximum Subarray in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/rust/index.md b/docs/projects/maximum-subarray/rust/index.md deleted file mode 100644 index 48807942f2..0000000000 --- a/docs/projects/maximum-subarray/rust/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-09 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- maximum-subarray -- rust -title: Maximum Subarray in Rust -title1: Maximum Subarray -title2: in Rust ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::cmp::max; - -fn usage() -> ! { - println!("Usage: Please provide a list of integers in the format: \"1, 2, 3, 4, 5\""); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -// Find maximum subarray using Kadane's algorithm. -// Source: https://en.wikipedia.org/wiki/Maximum_subarray_problem#No_empty_subarrays_admitted -fn maximum_subarray(arr: &Vec) -> i32 { - let mut best_sum: i32 = i32::MIN; - let mut current_sum: i32 = 0; - for value in arr { - current_sum = value + max(0, current_sum); - best_sum = max(current_sum, best_sum); - } - - best_sum -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let mut arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Get maximum subarray and display - println!("{}", maximum_subarray(&arr)); -} - -``` - -{% endraw %} - -Maximum Subarray in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/swift/index.md b/docs/projects/maximum-subarray/swift/index.md deleted file mode 100644 index d5d1481491..0000000000 --- a/docs/projects/maximum-subarray/swift/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- maximum-subarray -- swift -title: Maximum Subarray in Swift -title1: Maximum Subarray -title2: in Swift ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5" - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -extension Collection { - subscript(safe index: Index) -> Element? { - indices.contains(index) ? self[index] : nil - } -} - -func parseList(_ input: String?) -> [Int]? { - guard let input = input, !input.isEmpty else { return nil } - - let values = - input - .split(separator: ",") - .map { $0.trimmed } - .compactMap(Int.init) - - return values.isEmpty ? nil : values -} - -func maxSubarraySum(_ numbers: [Int]) -> Int { - var best = numbers[0] - var current = numbers[0] - - for value in numbers.dropFirst() { - current = max(value, current + value) - best = max(best, current) - } - - return best -} - -let args = CommandLine.arguments - -guard let list = parseList(args[safe: 1]) else { - print(usage) - exit(1) -} - -let result = maxSubarraySum(list) -print(result) - -``` - -{% endraw %} - -Maximum Subarray in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/tcl/index.md b/docs/projects/maximum-subarray/tcl/index.md deleted file mode 100644 index 71fcd263aa..0000000000 --- a/docs/projects/maximum-subarray/tcl/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- maximum-subarray -- tcl -title: Maximum Subarray in Tcl -title1: Maximum -title2: Subarray in Tcl ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"} - exit 1 -} - -proc parseList {s} { - set tokens [split [string trim $s] ","] - if {[llength $tokens] < 1} { usage } - - set result {} - - set result {} - foreach token $tokens { - set t [string trim $token] - if {$t eq "" || [catch {expr {int($t)}} val]} usage - lappend result $val - } - return $result -} - -proc maximumSubarraySum {numbers} { - if {[llength $numbers] == 0} { return 0 } - - set currentSum [lindex $numbers 0] - set maxSum $currentSum - - for {set i 1} {$i < [llength $numbers]} {incr i} { - set val [lindex $numbers $i] - set currentSum [expr {max($val, $currentSum + $val)}] - set maxSum [expr {max($maxSum, $currentSum)}] - } - - return $maxSum -} - -if {$argc != 1} { usage } - -set numbers [parseList [lindex $argv 0]] -puts [maximumSubarraySum $numbers] - -``` - -{% endraw %} - -Maximum Subarray in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/typescript/index.md b/docs/projects/maximum-subarray/typescript/index.md deleted file mode 100644 index 94f7b0e20a..0000000000 --- a/docs/projects/maximum-subarray/typescript/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Meet Thakur -date: 2025-10-11 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2025-10-11 -layout: default -tags: -- maximum-subarray -- typescript -title: Maximum Subarray in TypeScript -title1: Maximum Subarray -title2: in TypeScript ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function printUsage(): void { - console.log('Usage: Please provide a list of integers in the format: "1, 2, 3, 4, 5"'); -} - -function maxSubarraySum(arr: number[]): number { - let maxSoFar = Number.MIN_SAFE_INTEGER; - let maxEndingHere = 0; - - for (let i = 0; i < arr.length; i++) { - maxEndingHere += arr[i]; - - if (maxSoFar < maxEndingHere) { - maxSoFar = maxEndingHere; - } - - if (maxEndingHere < 0) { - maxEndingHere = 0; - } - } - - return maxSoFar; -} - -function main(): void { - const args = process.argv.slice(2); - - if (args.length < 1) { - printUsage(); - process.exit(1); - } - - // Check if input is empty - if (args[0].length === 0) { - printUsage(); - process.exit(1); - } - - // Parse input string - const arr = args[0].split(',').map(s => parseInt(s.trim())); - - // If less than two integers were provided - if (arr.length === 1) { - console.log(arr[0]); - return; - } else if (arr.length < 1) { - printUsage(); - process.exit(1); - } - - // Calculate maximum subarray sum - const result = maxSubarraySum(arr); - - console.log(result); -} - -main(); - -``` - -{% endraw %} - -Maximum Subarray in [TypeScript](/languages/typescript) was written by: - -- Meet Thakur - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/maximum-subarray/visual-basic/index.md b/docs/projects/maximum-subarray/visual-basic/index.md deleted file mode 100644 index 6ef49a6527..0000000000 --- a/docs/projects/maximum-subarray/visual-basic/index.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: maximum-subarray-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- maximum-subarray -- visual-basic -title: Maximum Subarray in Visual Basic -title1: Maximum Subarray -title2: in Visual Basic ---- - - - -Welcome to the [Maximum Subarray](/projects/maximum-subarray) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module MaximumSubarray - - Private Sub ShowUsage() - Console.Error.WriteLine( - "Usage: Please provide a list of integers in the format: ""1, 2, 3, 4, 5""" - ) - Environment.Exit(1) - End Sub - - - Private Function ParseIntegerList(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - ShowUsage() - End If - - Dim result As New List(Of Integer) - - For Each part In input.Split(","c, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) - - Dim value As Integer - - If Not Integer.TryParse(part, value) Then - ShowUsage() - End If - - result.Add(value) - - Next - - If result.Count = 0 Then - ShowUsage() - End If - - Return result - - End Function - - - Private Function MaximumSubarraySum(numbers As List(Of Integer)) As Integer - - If numbers.Count = 0 Then - Return 0 - End If - - Dim currentSum As Integer = numbers(0) - Dim maxSum As Integer = numbers(0) - - For i As Integer = 1 To numbers.Count - 1 - - Dim value As Integer = numbers(i) - - currentSum = Math.Max(value, currentSum + value) - maxSum = Math.Max(maxSum, currentSum) - - Next - - Return maxSum - - End Function - - - Public Function Main(args As String()) As Integer - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim inputList = ParseIntegerList(args(0)) - - Console.WriteLine(MaximumSubarraySum(inputList)) - - Return 0 - - End Function - -End Module -``` - -{% endraw %} - -Maximum Subarray in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/algol60/index.md b/docs/projects/merge-sort/algol60/index.md deleted file mode 100644 index edd3383cc1..0000000000 --- a/docs/projects/merge-sort/algol60/index.md +++ /dev/null @@ -1,317 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-18 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- merge-sort -title: Merge Sort in ALGOL 60 -title1: Merge Sort -title2: in ALGOL 60 ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of at least two integers " - "to sort in the format \"1, 2, 3, 4, 5\"\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Output integer array; - procedure outIntegerArray(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i; - for i := 1 step 1 until arrLen do - begin - if i > 1 then outstring(1, ", "); - outIntegerNoSpace(arr[i]) - end; - - if arrLen > 0 then outstring(1, "\n") - end outIntegerArray; - - comment Source https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation; - procedure mergeSort(arrA, n); - value n; - integer array arrA; - integer n; - begin - integer i; - integer array arrB[1:n]; - - comment Copy array A into array B; - for i := 1 step 1 until n do arrB[i] := arrA[i]; - - comment Run merge sort recursively; - mergeSortRec(arrA, 1, n + 1, arrB) - end mergeSort; - - procedure mergeSortRec(arrA, lo, hi, arrB); - value lo, hi; - integer array arrA, arrB; - integer lo, hi; - begin - integer mid; - - comment If more than 1 point; - if hi - lo > 1 then - begin - comment Find the midpoint to split the array; - mid := (lo + hi) % 2; - - comment Recursively sort the left and right halves into array B; - mergeSortRec(arrB, lo, mid, arrA); - mergeSortRec(arrB, mid, hi, arrA); - - comment Merge sorted halves back into array A; - merge(arrB, lo, mid, hi, arrA) - end - end mergeSortRec; - - procedure merge(arrA, lo, mid, hi, arrB); - value lo, mid, hi; - integer array arrA, arrB; - integer lo, mid, hi; - begin - integer i, j, k; - boolean useLeft; - - i := lo; - j := mid; - - comment Merge the two sorted runs into array B; - for k := lo step 1 until hi - 1 do - begin - comment Determine whether to use left half; - useLeft := false; - if i < mid then - begin - if j >= hi then useLeft := true - else if arrA[i] <= arrA[j] then useLeft := true - end; - - comment Take element from appropriate half; - if useLeft then - begin - arrB[k] := arrA[i]; - i := i + 1 - end - else - begin - arrB[k] := arrA[j]; - j := j + 1 - end - end - end merge; - - integer argc, arrLen; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 2 then usage; - - comment Merge sort input and output result; - mergeSort(arr, arrLen); - outIntegerArray(arr, arrLen) -end - -``` - -{% endraw %} - -Merge Sort in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/algol68/index.md b/docs/projects/merge-sort/algol68/index.md deleted file mode 100644 index 40d8a78478..0000000000 --- a/docs/projects/merge-sort/algol68/index.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-29 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- merge-sort -title: Merge Sort in ALGOL 68 -title1: Merge Sort -title2: in ALGOL 68 ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a list of at least two integers to sort in the format ""1, 2, 3, 4, 5""")) -); - -COMMENT -Source: https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation -COMMENT -PROC merge sort = (REF []INT values) VOID: -( - # Create temporary work array and copy the values into it # - INT n = UPB values; - HEAP [n]INT working values := values; - - # Run the recursive merge sort # - merge sort rec(working values, 1, n + 1, values) -); - -PROC merge sort rec = (REF []INT working values, INT low, INT high, REF []INT values) VOID: -( - # Only sort if enough values # - IF (high - low) > 1 - THEN - # Get midpoint # - INT mid := (low + high) OVER 2; - - # Sort the left half (low to midpoint - 1) from values into working values # - merge sort rec(values, low, mid, working values); - - # Sort the right half (midpoint to high - 1) from values into working values # - merge sort rec(values, mid, high, working values); - - # Merge the two halves from working values into values # - merge(working values, low, mid, high, values) - FI -); - -PROC merge = (REF []INT src, INT low, INT mid, INT high, REF []INT dest) VOID: -( - # Copy the side that has the next largest value from the source to the destination # - # until a side is exhausted # - INT left index := low; - INT right index := mid; - INT combined index := low; - INT len; - WHILE left index < mid AND right index < high - DO - IF src[left index] <= src[right index] - THEN - dest[combined index] := src[left index]; - left index +:= 1 - ELSE - dest[combined index] := src[right index]; - right index +:= 1 - FI; - - combined index +:= 1 - OD; - - # Copy the leftovers from the left side from the source to the destination # - len := mid - left index; - IF len > 0 - THEN - dest[combined index:combined index + len - 1] := src[left index:mid - 1]; - combined index +:= len - FI; - - # Copy the leftovers from the right side from the source to the destination # - len := high - right index; - IF len > 0 - THEN - dest[combined index:combined index + len - 1] := src[right index:high - 1] - FI -); - -PROC show list values = (REF []INT values) VOID: -( - INT n = UPB values; - FOR k TO n - DO - IF k > 1 - THEN - print(", ") - FI; - - print(whole(values[k], 0)) - OD; - - IF n > 0 - THEN - print(newline) - FI -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result OR UPB values < 2 -THEN - usage; - stop -FI; - -# Do merge sort and show results # -merge sort(values); -show list values(values) - -``` - -{% endraw %} - -Merge Sort in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/awk/index.md b/docs/projects/merge-sort/awk/index.md deleted file mode 100644 index 596f2dd1a7..0000000000 --- a/docs/projects/merge-sort/awk/index.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-21 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2025-04-21 -layout: default -tags: -- awk -- merge-sort -title: Merge Sort in AWK -title1: Merge Sort -title2: in AWK ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -# Source: https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation -function merge_sort(arr_a, arr_a_len, idx, arr_b) { - # Create temporary work array and copy the values into it - for (idx in arr_a) { - arr_b[idx] = arr_a[idx] - } - - # Run the recursive merge sort - merge_sort_rec(arr_a, 1, arr_a_len + 1, arr_b) -} - -function merge_sort_rec(arr_b, lo, hi, arr_a, mid) { - # Only sort if enough values - if (hi - lo > 1) { - # Get midpoint - mid = rshift(lo + hi, 1) - - # Sort the left half (low to midpoint - 1) from A into B - merge_sort_rec(arr_a, lo, mid, arr_b) - - # Sort the right half (midpoint to high - 1) from A into B - merge_sort_rec(arr_a, mid, hi, arr_b) - - # Merge the two halves from B into A - merge(arr_b, lo, mid, hi, arr_a) - } -} - -function merge(arr_b, lo, mid, hi, arr_a, i, j, k) { - i = lo - j = mid - - # While there are elements in the left or right - for (k = lo; k < hi; k++) { - # Copy the side that has the next largest value (or next available value if - # out of values) from the A into B - if (i < mid && (j >= hi || arr_a[i] <= arr_a[j])) { - arr_b[k] = arr_a[i] - i++ - } else { - arr_b[k] = arr_a[j] - j++ - } - } -} - -function show_array(arr, idx, s) { - s = "" - for (idx in arr) { - if (s) { - s = s ", " - } - s = s arr[idx] - } - - print s -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], arr) - arr_len = length(arr) - if (!arr_len || arr_len < 2) { - usage() - } - - merge_sort(arr, arr_len) - show_array(arr) -} - -``` - -{% endraw %} - -Merge Sort in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/beef/index.md b/docs/projects/merge-sort/beef/index.md deleted file mode 100644 index 6086042853..0000000000 --- a/docs/projects/merge-sort/beef/index.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-04 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2024-02-04 -layout: default -tags: -- beef -- merge-sort -title: Merge Sort in Beef -title1: Merge Sort -title2: in Beef ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace MergeSort; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Source: https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation - public static void MergeSort(List arrA) - where int : operator T <=> T - { - List arrB = scope .(arrA); - MergeSortRec(arrA, 0, arrA.Count, arrB); - } - - public static void MergeSortRec(List arrB, int iBegin, int iEnd, List arrA) - where int : operator T <=> T - { - // Exit if not enough elements to sort - if ((iEnd - iBegin) <= 1) - { - return; - } - - // Split sort into two halves - int iMid = (iBegin + iEnd) / 2; - - // Recursively sort left half from A into B - MergeSortRec(arrA, iBegin, iMid, arrB); - - // Recursively sort right half from A into B - MergeSortRec(arrA, iMid, iEnd, arrB); - - // Merge left and right halves from B into A - Merge(arrB, iBegin, iMid, iEnd, arrA); - } - - public static void Merge( - List arrB, int iBegin, int iMid, int iEnd, List arrA - ) - where int : operator T <=> T - { - int i = iBegin; - int j = iMid; - for (int k in iBegin..< iEnd) - { - // If there are elements from the left side and there are still - // elements on the right sight side or the left side element - // is less or equal the right side element, merge in left element - if (i < iMid && (j >= iEnd || arrA[i] <= arrA[j])) - { - arrB[k] = arrA[i]; - i++; - } - // Else, merge in right element - else - { - arrB[k] = arrA[j]; - j++; - } - } - } - - public static void ShowList(List arr) - { - String line = scope .(); - for (T val in arr) - { - if (!line.IsEmpty) - { - line += ", "; - } - - line.AppendF("{}", val); - } - - Console.WriteLine(line); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - List arr = scope .(); - switch (ParseIntList(args[0], arr)) - { - case .Ok: - if (arr.Count < 2) - { - Usage(); - } - case .Err: - Usage(); - } - - MergeSort(arr); - ShowList(arr); - return 0; - } -} - -``` - -{% endraw %} - -Merge Sort in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/c-plus-plus/index.md b/docs/projects/merge-sort/c-plus-plus/index.md deleted file mode 100644 index d75fd5652b..0000000000 --- a/docs/projects/merge-sort/c-plus-plus/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Sailok Chinta -- Ștefan-Iulian Alecu -date: 2019-10-26 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- merge-sort -title: Merge Sort in C++ -title1: Merge Sort -title2: in C++ ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5")" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.size() < 2 ? std::nullopt : std::make_optional(out); -} - -template -void merge_sort(R&& r) { - auto first = ranges::begin(r); - auto last = ranges::end(r); - - const auto n = std::distance(first, last); - if (n <= 1) return; - - const auto mid = std::next(first, n / 2); - - merge_sort(ranges::subrange(first, mid)); - merge_sort(ranges::subrange(mid, last)); - - std::inplace_merge(first, mid, last); -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - auto vec = parse_vec(argv[1]); - if (!vec) usage(); - - merge_sort(*vec); - - for (const char* sep = ""; int val : *vec) { - std::cout << std::exchange(sep, ", ") << val; - } - std::cout << "\n"; -} - -``` - -{% endraw %} - -Merge Sort in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Sailok Chinta -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/c-sharp/index.md b/docs/projects/merge-sort/c-sharp/index.md deleted file mode 100644 index 6653a0c93b..0000000000 --- a/docs/projects/merge-sort/c-sharp/index.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-30 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- merge-sort -title: Merge Sort in C# -title1: Merge Sort -title2: in C# ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Buffers; - -if (args is not [var input] || !TryParseList(input.AsSpan(), out var numbers)) - return ExitWithUsage(); - -Span span = CollectionsMarshal.AsSpan(numbers); -MergeSort(span); - -Console.WriteLine(string.Join(", ", numbers)); -return 0; - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return numbers.Count > 1; -} - -// Bottom-up merge sort -static void MergeSort(Span span) -{ - int n = span.Length; - if (n <= 1) - return; - - int[] buffer = new int[n]; - - Span src = span; - Span dst = buffer; - - for (int width = 1; width < n; width *= 2) - { - for (int left = 0; left < n; left += width * 2) - { - int mid = Math.Min(left + width, n); - int right = Math.Min(left + width * 2, n); - - Merge( - src[left..mid], - src[mid..right], - dst[left..right] - ); - } - - Span temp = src; - src = dst; - dst = temp; - } - - // if final data ended up in buffer, copy back - if (!src.Overlaps(span)) - src.CopyTo(span); -} - -static void Merge( - ReadOnlySpan left, - ReadOnlySpan right, - Span target) -{ - int li = 0; - int ri = 0; - int ti = 0; - - while (li < left.Length && ri < right.Length) - { - target[ti++] = left[li] <= right[ri] - ? left[li++] - : right[ri++]; - } - - left[li..].CopyTo(target[ti..]); - right[ri..].CopyTo(target[ti..]); -} - -static int ExitWithUsage() -{ - Console.WriteLine( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - ); - return 1; -} - -``` - -{% endraw %} - -Merge Sort in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/c/index.md b/docs/projects/merge-sort/c/index.md deleted file mode 100644 index fe90880185..0000000000 --- a/docs/projects/merge-sort/c/index.md +++ /dev/null @@ -1,204 +0,0 @@ ---- -authors: -- panda311 -- Ștefan-Iulian Alecu -date: 2019-10-15 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- merge-sort -title: Merge Sort in C -title1: Merge -title2: Sort in C ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -// Merge Sort In C Language - -#include -#include -#include -#include - -void merge_sort(long *, int, int); // Recursive function used for sorting -void merge_array(long *, int, int, int, int); // Merges two halves of subarray - -size_t parse_list(const char *orig_list, - long **arr) // used for parsing the input in array arr -{ - char *list; - char *token; - size_t num_elements = 0; - int i; - int curr_index = 0; - long temp_num; - - /* figure out the length of the list first */ - for (i = 0; orig_list[i]; i++) - if (orig_list[i] == ',') - num_elements++; - - /* if there are no commas, it's an invalid list */ - if (num_elements == 0) - { - *arr = NULL; - return 0; - } - - /* since there's one more number than there are commas, add one */ - num_elements++; - - /* alloc our array */ - *arr = malloc(num_elements * sizeof(long)); - - /* find the numbers */ - list = strdup(orig_list); - token = strtok(list, ","); - while (token != NULL) - { - errno = 0; - temp_num = strtol(token, NULL, 10); - if (errno != 0) - { - *arr = NULL; - return 0; - } - - (*arr)[curr_index++] = temp_num; - - token = strtok(NULL, ","); - } - - free(list); - - return num_elements; -} - -/* printing array in desired form */ -void print_array(long *arr, size_t num_elems) -{ - int i; - - for (i = 0; i < num_elems - 1; i++) - printf("%ld, ", arr[i]); - - printf("%ld\n", arr[num_elems - 1]); -} - -/* Error message if input is not in desired format */ -void usage() -{ - fputs("Usage: please provide a list of at least two integers to sort in " - "the format \"1, 2, 3, 4, 5\"\n", - stderr); -} - -int main(int argc, char **argv) -{ - long *arr; - long num_elements; - - if (argc < 2) - { - usage(); - return 1; - } - - num_elements = parse_list(argv[1], &arr); - if (num_elements == 0) - { - usage(); - return 1; - } - - merge_sort(arr, 0, num_elements - 1); // call for complete array [0....n-1] - print_array(arr, num_elements); - - free(arr); -} - -void merge_sort(long *arr_sort, int l, int r) -{ - int m; - - if (l < r) - { - m = (l + r) / 2; // m is middle index - merge_sort( - arr_sort, l, - m); // recursive call for first half of subarray arr_sort[l...m] - merge_sort( - arr_sort, m + 1, - r); // recursive call for second half of subarray arr_sort[m+1....r] - - merge_array(arr_sort, l, m, m + 1, - r); // merging the two halves into arr_sort[l....r] - } -} - -void merge_array(long *arr_sort, int a, int b, int c, int d) -{ - long t[50]; // Temporary array t created for temporary storage of sorted - // subarray[l...r] of arr_sort - int i = a, j = c, k = 0; // i is starting index for first half [l...m] - // j is starting index for second half [m+1....r] - // k is starting index for temporary array t - - while (i <= b && j <= d) - if (arr_sort[i] < arr_sort[j]) - t[k++] = arr_sort[i++]; - else - t[k++] = arr_sort[j++]; // Comparing both indices of first half and - // second half and adding smaller one to - // temporary array - - // collect remaining elements if left in first half - while (i <= b) - t[k++] = arr_sort[i++]; - - // collect remaining elements if left in first half - while (j <= d) - t[k++] = arr_sort[j++]; - - for (i = a, j = 0; i <= d; i++, j++) - arr_sort[i] = t[j]; - -} // End of function merge() - -``` - -{% endraw %} - -Merge Sort in [C](/languages/c) was written by: - -- panda311 -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/cobol/index.md b/docs/projects/merge-sort/cobol/index.md deleted file mode 100644 index 3d23c6c808..0000000000 --- a/docs/projects/merge-sort/cobol/index.md +++ /dev/null @@ -1,227 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-21 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-04-21 -layout: default -tags: -- cobol -- merge-sort -title: Merge Sort in COBOL -title1: Merge Sort -title2: in COBOL ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. merge-sort. - -data division. -working-storage section. -01 max-entries constant as 1000. - -01 argument-string pic x(32768). -01 current-token pic x(128). -01 scan-ptr binary-long. - -01 table-a. - 05 list-size binary-long value 0. - 05 array-a pic s9(9) occurs max-entries. -01 table-b. - 05 array-b pic s9(9) occurs max-entries. - -01 sort-state. - 05 merge-size binary-long. - 05 left-idx binary-long. - 05 mid-idx binary-long. - 05 right-idx binary-long. - 05 pass-count binary-long. - 05 left-ptr binary-long. - 05 right-ptr binary-long. - 05 target-ptr binary-long. - 05 i binary-long. - -01 output-fmt. - 05 display-num pic -(10)9. - 05 comma-space pic xx value ", ". - -procedure division. - -main. - perform get-input - perform parse-input - perform execute-sort - perform display-results - goback. - -get-input. - accept argument-string from argument-value - if argument-string = spaces - perform show-usage - end-if. - -parse-input. - move 1 to scan-ptr - perform until scan-ptr > length of argument-string - move spaces to current-token - unstring argument-string delimited by "," - into current-token with pointer scan-ptr - - if current-token = spaces continue end-if - if function test-numval(function trim(current-token)) <> 0 - perform show-usage - end-if - - add 1 to list-size - if list-size > max-entries perform show-usage end-if - move function numval(current-token) to array-a(list-size) - end-perform - if list-size < 2 perform show-usage end-if. - -execute-sort. - move 1 to merge-size - move 0 to pass-count - - perform until merge-size >= list-size - move 1 to left-idx - perform until left-idx > list-size - compute mid-idx = left-idx + merge-size - 1 - compute right-idx = - function min(left-idx + 2 * merge-size - 1, list-size) - - if mid-idx < list-size - if function mod(pass-count, 2) = 0 - perform merge-a-to-b - else - perform merge-b-to-a - end-if - else - perform copy-leftover - end-if - - compute left-idx = left-idx + 2 * merge-size - end-perform - - compute merge-size = merge-size * 2 - add 1 to pass-count - end-perform. - -merge-a-to-b. - move left-idx to left-ptr - compute right-ptr = mid-idx + 1 - move left-idx to target-ptr - - perform until left-ptr > mid-idx or right-ptr > right-idx - if array-a(left-ptr) <= array-a(right-ptr) - move array-a(left-ptr) to array-b(target-ptr) - add 1 to left-ptr - else - move array-a(right-ptr) to array-b(target-ptr) - add 1 to right-ptr - end-if - add 1 to target-ptr - end-perform - - perform until left-ptr > mid-idx - move array-a(left-ptr) to array-b(target-ptr) - add 1 to left-ptr add 1 to target-ptr - end-perform - - perform until right-ptr > right-idx - move array-a(right-ptr) to array-b(target-ptr) - add 1 to right-ptr add 1 to target-ptr - end-perform. - -merge-b-to-a. - move left-idx to left-ptr - compute right-ptr = mid-idx + 1 - move left-idx to target-ptr - - perform until left-ptr > mid-idx or right-ptr > right-idx - if array-b(left-ptr) <= array-b(right-ptr) - move array-b(left-ptr) to array-a(target-ptr) - add 1 to left-ptr - else - move array-b(right-ptr) to array-a(target-ptr) - add 1 to right-ptr - end-if - - add 1 to target-ptr - end-perform - - perform until left-ptr > mid-idx - move array-b(left-ptr) to array-a(target-ptr) - add 1 to left-ptr add 1 to target-ptr - end-perform - - perform until right-ptr > right-idx - move array-b(right-ptr) to array-a(target-ptr) - add 1 to right-ptr add 1 to target-ptr - end-perform. - -copy-leftover. - perform varying i from left-idx by 1 until i > right-idx - if function mod(pass-count, 2) = 0 - move array-a(i) to array-b(i) - else - move array-b(i) to array-a(i) - end-if - end-perform. - -display-results. - perform varying i from 1 by 1 until i > list-size - if function mod(pass-count, 2) = 0 - move array-a(i) to display-num - else - move array-b(i) to display-num - end-if - - display function trim(display-num) with no advancing - if i < list-size - display ", " with no advancing - end-if - end-perform - - display space. - -show-usage. - display - 'Usage: please provide a list of at least two integers ' - 'to sort in the format "1, 2, 3, 4, 5"' - stop run. - -``` - -{% endraw %} - -Merge Sort in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/commodore-basic/index.md b/docs/projects/merge-sort/commodore-basic/index.md deleted file mode 100644 index a69d71a21b..0000000000 --- a/docs/projects/merge-sort/commodore-basic/index.md +++ /dev/null @@ -1,177 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-14 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2023-10-14 -layout: default -tags: -- commodore-basic -- merge-sort -title: Merge Sort in Commodore BASIC -title1: Merge Sort in -title2: Commodore BASIC ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -15 DIM B(99): REM Work array -20 GOSUB 2000: REM Get array -25 REM Error if invalid, not end of input/value, or less that 2 items -30 IF V = 0 OR C >= 0 OR NA < 2 THEN GOTO 200 -40 GOSUB 3000: REM Perform merge sort -50 GOSUB 3500: REM Show array -60 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide a list of at least two integers to sort "; -220 PRINT "in the format "; Q$; "1, 2, 3, 4, 5"; Q$ -230 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Merge sort -3001 REM Source: -3002 REM https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation -3003 REM Inputs: -3004 REM - A contains array to sort -3005 REM - NA contains size of array -3006 REM Output: A contains sorted array -3010 W = 1 -3020 IF W >= NA THEN RETURN -3030 FOR IL = 0 TO NA - 1 STEP W * 2 -3040 IR = IL + W -3050 IE = IR + W -3060 IF IR > NA THEN IR = NA -3070 IF IE > NA THEN IE = NA -3080 GOSUB 3200 -3090 NEXT IL -3100 FOR I = 0 TO NA - 1 -3110 A(I) = B(I) -3120 NEXT I -3130 W = W * 2 -3140 GOTO 3020 -3200 REM Merge array and work array -3201 REM Inputs: -3202 REM - A contains array to sort -3203 REM - NA contains size of array -3204 REM - IL contains left index -3205 REM - IR contains right index -3206 REM - IE contains end index -3207 REM Outputs: B contains sorted portion of work array -3210 II = IL -3220 JJ = IR -3230 FOR K = IL TO IE - 1 -3240 IF II < IR AND (JJ >= IE OR A(II) <= A(JJ)) THEN GOTO 3280 -3250 B(K) = A(JJ) -3260 JJ = JJ + 1 -3270 GOTO 3300 -3280 B(K) = A(II) -3290 II = II + 1 -3300 NEXT K -3310 RETURN -3500 REM Display array -3501 REM A contains array -3502 REM NA contains size of array -3510 IF NA < 1 THEN GOTO 3590 -3520 FOR I = 0 TO NA - 1 -3530 S$ = STR$(A(I)) -3540 IF A(I) >= 0 THEN S$ = MID$(S$, 2): REM strip leading space -3550 PRINT S$; -3560 IF I < (NA - 1)THEN PRINT ", "; -3570 NEXT I -3580 PRINT -3590 RETURN - -``` - -{% endraw %} - -Merge Sort in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/euphoria/index.md b/docs/projects/merge-sort/euphoria/index.md deleted file mode 100644 index ea0133ea3d..0000000000 --- a/docs/projects/merge-sort/euphoria/index.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2023-02-27 -layout: default -tags: -- euphoria -- merge-sort -title: Merge Sort in Euphoria -title1: Merge Sort -title2: in Euphoria ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/math.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"\n" - ) - abort(0) -end procedure - -procedure show_list_values(sequence values) - if length(values) > 0 - then - sequence format = repeat_pattern("%d, ", length(values)) - sequence s = sprintf(format[1..$-2], values) - printf(STDOUT, "%s\n", {s}) - end if -end procedure - -function merge_sort(sequence values) - -- Source: https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation - - -- Only sort if enough values - integer n = length(values) - if n <= 1 - then - return values - end if - - -- Get the midpoint - integer mid = intdiv(n, 2) - - -- Sort the left half (1 to midpoint) - sequence left = merge_sort(values[1..mid]) - - -- Sort the right side (midpoint + 1 to n) - sequence right = merge_sort(values[mid + 1..$]) - - -- Merge the two sides - return merge(left, right) -end function - -function merge(sequence left, sequence right) - -- Append the side that has the next largest value to the merged result - -- until a side is exhausted - integer left_index = 1 - integer left_len = length(left) - integer right_index = 1 - integer right_len = length(right) - sequence merged = {} - while left_index <= left_len and right_index <= right_len - do - if left[left_index] <= right[right_index] - then - merged &= left[left_index] - left_index += 1 - else - merged &= right[right_index] - right_index += 1 - end if - end while - - -- Append the remainders to the merged result - return merged & left[left_index..$] & right[right_index..$] -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int_list(argv[4]) -sequence values = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] or length(values) < 2 -then - usage() -end if - --- Do merge sort and show results -values = merge_sort(values) -show_list_values(values) - -``` - -{% endraw %} - -Merge Sort in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/f-sharp/index.md b/docs/projects/merge-sort/f-sharp/index.md deleted file mode 100644 index 60aff76be9..0000000000 --- a/docs/projects/merge-sort/f-sharp/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-09 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-04-09 -layout: default -tags: -- f-sharp -- merge-sort -title: Merge Sort in F# -title1: Merge Sort -title2: in F# ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module MergeSort = - let rec private merge left right = - let rec loop acc = function - | [], rs | rs, [] -> List.rev acc @ rs - | hL :: tL, hR :: tR -> - match hL <= hR with - | true -> loop (hL :: acc) (tL, hR :: tR) - | false -> loop (hR :: acc) (hL :: tL, tR) - loop [] (left, right) - - let rec sort = function - | [] | [ _ ] as trivial -> trivial - | lst -> - let mid = lst.Length / 2 - let left, right = List.splitAt mid lst - merge (sort left) (sort right) - -module Result = - let toOption = function - | Ok x -> Some x - | Error _ -> None - -module Helpers = - let private (|IntList|_|) (s: string) = - let parts = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) - |> Array.toList - |> List.map (fun p -> p.Trim()) - - let rec parseAll acc = function - | [] -> Some(List.rev acc) - | (h: string) :: t -> - match Int32.TryParse h with - | true, n -> parseAll (n :: acc) t - | false, _ -> None - - parseAll [] parts - |> function - | Some ns when ns.Length >= 2 -> Some ns - | _ -> None - - let parseArgs = function - | [| IntList numbers |] -> Ok numbers - | _ -> Error "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - - let handleResult = function - | Ok result -> - result |> List.map string |> String.concat ", " |> printfn "%s" - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.map MergeSort.sort |> Helpers.handleResult - -``` - -{% endraw %} - -Merge Sort in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/go/index.md b/docs/projects/merge-sort/go/index.md deleted file mode 100644 index 293689f977..0000000000 --- a/docs/projects/merge-sort/go/index.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-03-17 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2019-03-25 -layout: default -tags: -- go -- merge-sort -title: Merge Sort in Go -title1: Merge Sort -title2: in Go ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "encoding/json" - "fmt" - "os" - "regexp" - "strconv" - "strings" -) - -func mergeSort(list []int) []int { - var doMergeSort func(lst [][]int) [][]int - doMergeSort = func(lst [][]int) [][]int { - if len(lst) <= 0 { - return [][]int{} - } - if len(lst) == 1 { - return lst - } - return doMergeSort(append([][]int{merge(lst[0], lst[1])}, doMergeSort(lst[2:])...)) - } - return doMergeSort(split(list))[0] -} - -func split(list []int) (splitList [][]int) { - for _, i := range list { - splitList = append(splitList, []int{i}) - } - return -} - -func merge(list1 []int, list2 []int) []int { - if len(list1) <= 0 { - return list2 - } - if len(list2) <= 0 { - return list1 - } - if list1[0] < list2[0] { - return append(list1[:1], merge(list1[1:], list2)...) - } - return append(list2[:1], merge(list1, list2[1:])...) -} - -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - if len(list) < 2 { - exitWithError() - } - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} - -func sliceIntToString(list []int) (out string) { - bytes, _ := json.Marshal(list) - out = strings.Replace(string(bytes), ",", ", ", -1) - out = strings.Trim(out, "[]") - return -} - -func exitWithError() { - fmt.Println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - nums := strToSliceInt(os.Args[1]) - nums = mergeSort(nums) - fmt.Println(sliceIntToString(nums)) -} - -``` - -{% endraw %} - -Merge Sort in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/groovy/index.md b/docs/projects/merge-sort/groovy/index.md deleted file mode 100644 index ff9c8a5209..0000000000 --- a/docs/projects/merge-sort/groovy/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- Mykhaylo Samonov -- rzuckerm -date: 2019-10-20 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2023-07-25 -layout: default -tags: -- groovy -- merge-sort -title: Merge Sort in Groovy -title1: Merge Sort -title2: in Groovy ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -class MergeSort { - - static sort(int[] data) { sort(data, 0, data.length - 1) } - - /** - * Sorts the range data[start..end] in O(nlgn) time and O(n) space. - */ - static sort(int[] data, int start, int end) { - - if (end > start) { - - int middle = (int) ((start + end) / 2) - - // Sort the left and right sides separately. - sort(data, start, middle) - sort(data, middle + 1, end) - - // Intertwine the data into one sorted list. - mergeLists(data, start, middle, end) - } - - } - - /** - * Merges the two sorted sublists of data[start..middle] and data[middle+1..end]. - * O(n) time and memory. - */ - static mergeLists(int[] data, int start, int middle, int end) { - - // Copy the left and right arrays because we'll be overwriting them. - int[] left = Arrays.copyOfRange(data, start, middle+1) - int[] right = Arrays.copyOfRange(data, middle+1, end+1) - - // Now, merge the lists by repeatedly adding the biggest value, from whichever list has it. - int i = start, l = 0, r = 0 // l and r are indexes in left and right - while (l < left.length && r < right.length) - data[i++] = (left[l] <= right[r]) ? left[l++] : right[r++] - - // Add any leftovers on one side. - while (l < left.length) - data[i++] = left[l++] - while (r < right.length) - data[i++] = right[r++] - } - - static int[] convert_to_ints(def args) { - int[] argsint = [] - if (args?.size() >= 1) { - try { - argsint = args[0].split(",").collect { it.trim().toInteger() } - } - catch (NumberFormatException _) { - } - } - - argsint - } - - public static void main(def args) { - int[] argsint = convert_to_ints(args) - if (argsint.size() < 2) { - println 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - } else { - sort(argsint) - println argsint - } - } - -} -``` - -{% endraw %} - -Merge Sort in [Groovy](/languages/groovy) was written by: - -- Mykhaylo Samonov -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/haskell/index.md b/docs/projects/merge-sort/haskell/index.md deleted file mode 100644 index 26f8d524ad..0000000000 --- a/docs/projects/merge-sort/haskell/index.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-12-03 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2019-03-26 -layout: default -tags: -- haskell -- merge-sort -title: Merge Sort in Haskell -title1: Merge Sort -title2: in Haskell ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Text.Read -import System.Environment -import System.Exit (exitWith, ExitCode(ExitFailure)) -import Data.List (intercalate) - - -mergeSort :: Ord a => [a] -> [a] -mergeSort xs = head $ mergeSort' $ fmap (:[]) xs - where mergeSort' :: Ord a => [[a]] -> [[a]] - mergeSort' [] = [] - mergeSort' [x] = [x] - mergeSort' (x1:x2:xs) = mergeSort' $ merge x1 x2:mergeSort' xs - -merge :: Ord a => [a] -> [a] -> [a] -merge x [] = x -merge [] y = y -merge (x:xs) (y:ys) - | x < y = x:merge xs (y:ys) - | otherwise = y:merge (x:xs) ys - - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - --- Ensure that a list contains at least two elements -verifyListLength :: Ord a => [a] -> Maybe [a] -verifyListLength [] = Nothing -verifyListLength [x] = Nothing -verifyListLength (x:xs) = Just (x:xs) - -listToString :: [Int] -> String -listToString = intercalate ", " . map show - - -main :: IO () -main = do - args <- getArgs - let xs = headMaybe args >>= stringToListMaybe >>= verifyListLength - case xs of - Nothing -> do - putStrLn "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exitWith $ ExitFailure 1 - Just xs -> putStrLn $ listToString $ mergeSort xs - - -``` - -{% endraw %} - -Merge Sort in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/haxe/index.md b/docs/projects/merge-sort/haxe/index.md deleted file mode 100644 index 26e29b789a..0000000000 --- a/docs/projects/merge-sort/haxe/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- Fredrick Karau -date: 2025-10-31 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2025-10-31 -layout: default -tags: -- haxe -- merge-sort -title: Merge Sort in Haxe -title1: Merge Sort -title2: in Haxe ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Haxe](/languages/haxe) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haxe -package; -import Sys; -class MergeSort { - static function main() { - var args = Sys.args(); - - if(args.length != 1) { - usage(); - return; - } - - - var input = args[0]; - - var parts = input.split(","); - var numbers = []; - - - try { - for (p in parts) { - var trimmed = StringTools.trim(p); - if (trimmed == "") throw "Invalid"; - numbers.push(Std.parseInt(trimmed)); - } - } catch (e:Dynamic) { - usage(); - return; - } - if(numbers.length < 2) { - usage(); - return; - } - - var sorted = mergeSort(numbers); - trace(sorted.join(", ")); - } - static function mergeSort(arr:Array):Array { - if (arr.length <= 1) return arr; - - var mid = Std.int(arr.length / 2); - var left = mergeSort(arr.slice(0, mid)); - var right = mergeSort(arr.slice(mid, arr.length)); - - return merge(left, right); -} - - - static function merge(left:Array, right:Array):Array { - var result:Array = []; - var i = 0; - var j = 0; - - while (i < left.length && j < right.length) { - if (left[i] <= right[j]) { - result.push(left[i]); - i++; - } else { - result.push(right[j]); - j++; - } - } - - while (i < left.length) { - result.push(left[i]); - i++; - } - - while (j < right.length) { - result.push(right[j]); - j++; - } - - return result; - } - - static function usage() { - trace('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - } -} -``` - -{% endraw %} - -Merge Sort in [Haxe](/languages/haxe) was written by: - -- Fredrick Karau - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/index.md b/docs/projects/merge-sort/index.md deleted file mode 100644 index 4aba7a408d..0000000000 --- a/docs/projects/merge-sort/index.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -date: 2018-12-03 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-05-23 -layout: default -tags: -- merge-sort -title: Merge Sort -title1: Merge -title2: Sort ---- - - - -Welcome to the Merge Sort page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Merge sort is an algorithm that works by dividing a list into smaller lists. -It continues dividing until each list only has a single element in it -because lists of a single element are by definition already sorted. -It then merges each sublist in a sorted fashion until they all become a single sorted list. - -Step by step the process is: - -1. Divide the sorted list into lists of 1 element. -2. Continually merge the lists together until they become a single list. Do the merge as follows: - * Compare the smallest items in each of the two lists to be merged. - * Move the smaller of the two to the new merged list - * Repeat until there are no unmerged items - - -### Performance - -The performance of sorting algorithms is generally defined in "Big O notation". -If you are not familiar with such notations, please refer to the relevant -article by [Rob Bell][1] or the [Wikipedia][2] entry listed in further readings below. - -| Cases | Big O Notatation | -| ------------ | ---------------- | -| Best case | O(n log n) | -| Average case | O(n log n) | -| Worst case | O(n log n) | - -### Examples - -The examples below were taken from [Wikipedia's article about Merge sort][3]. - -![Merge sort example image](https://upload.wikimedia.org/wikipedia/commons/e/e6/Merge_sort_algorithm_diagram.svg) - -![Merge sort example gif](https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif) - -[1]: https://robbell.io/2009/06/a-beginners-guide-to-big-o-notation -[2]: https://en.wikipedia.org/wiki/Big_O_notation -[3]: https://en.wikipedia.org/wiki/Merge_sort - - -## Requirements - -Write a sample program that takes a list of numbers in the format "4, 5, 3, 1, 2". -It should then sort the numbers and output them: - -```console -$ ./merge-sort.lang "4, 5, 3, 1, 2" -1, 2, 3, 4, 5 -``` - -The solution should handle duplicate elements - -```console -$ ./merge-sort.lang "4, 5, 3, 1, 4, 2" -1, 2, 3, 4, 4, 5 -``` - -In addition, there should be some error handling for situations where the user -doesn't supply correct input. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Merge Sort. -In order to keep things simple, we split up the testing as follows: - -- Merge Sort Valid Tests -- Merge Sort Invalid Tests - -### Merge Sort Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input | "4, 5, 3, 1, 2" | "1, 2, 3, 4, 5" | -| Sample Input: With Duplicate | "4, 5, 3, 1, 4, 2" | "1, 2, 3, 4, 4, 5" | -| Sample Input: Already Sorted | "1, 2, 3, 4, 5" | "1, 2, 3, 4, 5" | -| Sample Input: Reverse Sorted | "9, 8, 7, 6, 5, 4, 3, 2, 1" | "1, 2, 3, 4, 5, 6, 7, 8, 9" | - -### Merge Sort Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A List | "1" | -| Invalid Input: Wrong Format | "4 5 3" | - -All of these tests should output the following: - -``` -Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -``` - - -## Articles - -There are 34 articles: - -- [Merge Sort in ALGOL 60](/projects/merge-sort/algol60) -- [Merge Sort in ALGOL 68](/projects/merge-sort/algol68) -- [Merge Sort in AWK](/projects/merge-sort/awk) -- [Merge Sort in Beef](/projects/merge-sort/beef) -- [Merge Sort in C](/projects/merge-sort/c) -- [Merge Sort in C#](/projects/merge-sort/c-sharp) -- [Merge Sort in C++](/projects/merge-sort/c-plus-plus) -- [Merge Sort in COBOL](/projects/merge-sort/cobol) -- [Merge Sort in Commodore BASIC](/projects/merge-sort/commodore-basic) -- [Merge Sort in Euphoria](/projects/merge-sort/euphoria) -- [Merge Sort in F#](/projects/merge-sort/f-sharp) -- [Merge Sort in Go](/projects/merge-sort/go) -- [Merge Sort in Groovy](/projects/merge-sort/groovy) -- [Merge Sort in Haskell](/projects/merge-sort/haskell) -- [Merge Sort in Haxe](/projects/merge-sort/haxe) -- [Merge Sort in Java](/projects/merge-sort/java) -- [Merge Sort in JavaScript](/projects/merge-sort/javascript) -- [Merge Sort in Kotlin](/projects/merge-sort/kotlin) -- [Merge Sort in Mathematica](/projects/merge-sort/mathematica) -- [Merge Sort in OCaml](/projects/merge-sort/ocaml) -- [Merge Sort in Objective-C](/projects/merge-sort/objective-c) -- [Merge Sort in Octave](/projects/merge-sort/octave) -- [Merge Sort in PHP](/projects/merge-sort/php) -- [Merge Sort in Pascal](/projects/merge-sort/pascal) -- [Merge Sort in Perl](/projects/merge-sort/perl) -- [Merge Sort in PowerShell](/projects/merge-sort/powershell) -- [Merge Sort in Python](/projects/merge-sort/python) -- [Merge Sort in Ruby](/projects/merge-sort/ruby) -- [Merge Sort in Rust](/projects/merge-sort/rust) -- [Merge Sort in Swift](/projects/merge-sort/swift) -- [Merge Sort in Tcl](/projects/merge-sort/tcl) -- [Merge Sort in TypeScript](/projects/merge-sort/typescript) -- [Merge Sort in Visual Basic](/projects/merge-sort/visual-basic) -- [Merge Sort in m4](/projects/merge-sort/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/merge-sort/java/index.md b/docs/projects/merge-sort/java/index.md deleted file mode 100644 index 37cd36c794..0000000000 --- a/docs/projects/merge-sort/java/index.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Shubham Raj -date: 2019-10-17 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- java -- merge-sort -title: Merge Sort in Java -title1: Merge Sort -title2: in Java ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.ArrayList; - -public class MergeSort { - - public static void main(String[] args) { - - ArrayList numList = new ArrayList<>(); // creating an arraylist(for dynamic size) to store the numbers - - if (args.length < 1) { // null input - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } - - else if (args[0].length() < 2) { // checking for empty input and single number input - - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - String[] stringList = args[0].split(","); // extract numbers from the passed string - - if (stringList.length < 2) { // wrong/invalid input format - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - - for (int i = 0; i < stringList.length; i++) { - numList.add(Integer.parseInt(stringList[i].trim())); // convert to Int type and store in numList for - // sorting - } - - if (numList.size() < 2) { // wrong/invalid input format - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - mergeSort(numList, 0, numList.size() - 1); - - // display the sorted list to the user - String str = ""; - for (int i = 0; i < numList.size() - 1; i++) { - str += String.valueOf(numList.get(i)); - str += ", "; - } - str += String.valueOf(numList.get(numList.size() - 1)); - System.out.println(str); - - } - } - - } - - } - - public static void mergeSort(ArrayList numList, int low, int high) { - - if (low < high) { - // calculating mid avoiding overflow - int mid = low + (high - low) / 2; - - // recursively divide the list into 2 parts and call mergeSort on each half - mergeSort(numList, low, mid); - mergeSort(numList, mid + 1, high); - - // finally merge the sorted halves to get the final sorted list - mergeList(numList, low, mid, high); - - } - - } - - public static void mergeList(ArrayList numList, int low, int mid, int high) { - - int i = low; - int j = mid + 1; - int k = low; - ArrayList copyList = new ArrayList(numList); - // find the smaller element using pointers,update the array and move the pointer - // forward - while (i <= mid && j <= high) { // till we don't reach the end of individual arrays - - if (copyList.get(i) <= copyList.get(j)) { - numList.set(k, copyList.get(i)); - i++; // incrementing pointer - } else { - numList.set(k, copyList.get(j)); - j++; // incrementing pointer - } - - k++; // incrementing arraylist index - } - - // dealing with cases where we reach end of one part; just copy the remaining - // part of second half - while (i <= mid) { - numList.set(k, copyList.get(i)); - i++; - k++; - } - - while (j <= high) { - numList.set(k, copyList.get(j)); - j++; - k++; - } - } - -} - -``` - -{% endraw %} - -Merge Sort in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Shubham Raj - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/javascript/index.md b/docs/projects/merge-sort/javascript/index.md deleted file mode 100644 index 87ccc5426d..0000000000 --- a/docs/projects/merge-sort/javascript/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- rzuckerm -- Sumathi Varadharajan -date: 2019-10-31 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- javascript -- merge-sort -title: Merge Sort in JavaScript -title1: Merge Sort in -title2: JavaScript ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -function mergeSort (unsortedArray) { - if (unsortedArray.length <= 1) { - return unsortedArray; - } - const middle = Math.floor(unsortedArray.length / 2); - const left = unsortedArray.slice(0, middle); - const right = unsortedArray.slice(middle); - return merge( - mergeSort(left), mergeSort(right) - ); -} - -function merge (left, right) { - let resultArray = [], leftIndex = 0, rightIndex = 0; - while (leftIndex < left.length && rightIndex < right.length) { - if (left[leftIndex] < right[rightIndex]) { - resultArray.push(left[leftIndex]); - leftIndex++; - } else { - resultArray.push(right[rightIndex]); - rightIndex++; - } - } - return resultArray - .concat(left.slice(leftIndex)) - .concat(right.slice(rightIndex)); -} - -const main = (input) => { - const inputValidation = /^"?(\d+,\s*){2,}\d+(,"?|"?)$/gm; - if (inputValidation.test(input) == true) { - let arr; - arr = input.replace(/(\s|"|'|`)/g, ''); - arr = arr.split(','); - arr = arr.map(function (n) { - return parseInt(n, 10); - }); - arr = arr.filter(n => n); - arr=mergeSort(arr); - console.log(arr.join(", ")); - } - else { - console.log(usage); - } -} - -const usage = `Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"`; - -if (process.argv.length > 2) { - const input = process.argv[2]; - main(input); -} -else { - console.log(usage); -} - -``` - -{% endraw %} - -Merge Sort in [JavaScript](/languages/javascript) was written by: - -- rzuckerm -- Sumathi Varadharajan - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/kotlin/index.md b/docs/projects/merge-sort/kotlin/index.md deleted file mode 100644 index cb9770d6f9..0000000000 --- a/docs/projects/merge-sort/kotlin/index.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -authors: -- Blake.Ke -- Jeremy Grifski -- mikenmo -date: 2020-10-02 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- kotlin -- merge-sort -title: Merge Sort in Kotlin -title1: Merge Sort -title2: in Kotlin ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) -{ - var arr: IntArray - try - { - arr = args[0].split(", ").map{ it.toInt() }.toIntArray() - if (arr.size < 2) { - throw Exception() - } - } - catch(e: Exception) - { - println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - return - } - - var ans:IntArray = mergeSort(arr) - for(i in 0 until ans.count()) - { - if (i==ans.count()-1) - { - println("${ans[i]}") - return - } - print("${ans[i]}, ") - } -} - -fun mergeSort(arr1: IntArray):IntArray -{ - var arr:IntArray = arr1 - if (arr.count() > 1) - { - var mid:Int = (arr.count() - 1) / 2 - var left = arr.sliceArray(0..mid) - var right = arr.sliceArray(mid + 1..arr.count() - 1) - - left = mergeSort(left) - right = mergeSort(right) - - arr = intArrayOf() - while (left.count() > 0 && right.count() > 0) - { - if (left[0] < right[0]) - { - arr = arr + left.sliceArray(0..0) - left = left.sliceArray(1..left.count() - 1) - } - else - { - arr = arr + right.sliceArray(0..0) - right = right.sliceArray(1..right.count() - 1) - } - } - arr = arr + left + right - } - return(arr) -} - -``` - -{% endraw %} - -Merge Sort in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- Jeremy Grifski -- mikenmo - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/m4/index.md b/docs/projects/merge-sort/m4/index.md deleted file mode 100644 index 19e9221a23..0000000000 --- a/docs/projects/merge-sort/m4/index.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-05 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2025-10-05 -layout: default -tags: -- m4 -- merge-sort -title: Merge Sort in m4 -title1: Merge Sort -title2: in m4 ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl show_int_list(varname): -dnl for i = 0 to n-1: -dnl if i > 0: -dnl Output ", " -dnl Output varname[i] -define(`show_int_list', `_show_int_list(`$1', 0)') -define(`_show_int_list', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`ifelse(eval($2 > 0), 1, `, ')dnl -array_get(`$1', $2)`'dnl -_show_int_list(`$1', incr($2))'`'dnl -)'dnl -) - -dnl Reference: https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation -dnl merge_sort(varnameA, varnameB): -dnl copy(varnameA, varnameB) -dnl merge_sort_rec(varnameA, 0, varnameA[length], varnameB) -define(`merge_sort', -`copy(`$1', `$2')dnl -merge_sort_rec(`$1', 0, array_get(`$1', `length'), `$2')'dnl -) - -dnl copy(varnameA, varnameB): -dnl n = varnameA[length] -dnl varnameB[length] = n -dnl for i = 0 to n-1: -dnl varnameB[i] = varnameA[i] -define(`copy', -`array_set(`$2', `length', array_get(`$1', `length'))dnl -_copy(`$1', `$2', 0)'dnl -) -define(`_copy', -`ifelse(eval($3 < array_get(`$1', `length')), 1, -`array_set(`$2', $3, array_get(`$1', $3))dnl -_copy(`$1', `$2', incr($3))'dnl -)'dnl -) - -dnl varnameB=$1, iBegin=$2, iEnd=$3, varnameA=$4 -dnl merge_sort_rec(varnameB, iBegin, iEnd, varnameA): -dnl if iEnd - iBegin > 1: -dnl iMid = (iBegin + iEnd) / 2 -dnl -dnl // Sort left side of varnameA into varnameB -dnl merge_sort_rec(varnameA, iBegin, iMid, varnameB) -dnl -dnl // Sort right side of varnameA into varnameB -dnl merge_sort_rec(varnameA, iMid, iEnd, varnameB) -dnl -dnl // Merge varnameB into varnameA -dnl merge(varnameB, iBegin, iMid, iEnd, varnameA) -define(`merge_sort_rec', -`ifelse(eval($3 - $2 > 1), 1, -`pushdef(`iMid', eval(($2 + $3) >> 1))dnl -merge_sort_rec(`$4', `$2', iMid, `$1')dnl -merge_sort_rec(`$4', iMid, `$3', `$1')dnl -merge(`$1', `$2', iMid, `$3', `$4')dnl -popdef(`iMid')'dnl -)'dnl -) - -dnl varnameB=$1, iBegin=$2, iMid=$3, iEnd=$4, varnameA=$5 -dnl merge(varnameB, iBegin, iMid, iEnd, varnameA): -dnl i = iBegin -dnl j = iMid -dnl for k = iBegin to iEnd-1: -dnl if i < iMid and j >= iEnd: -dnl varnameB[k] = varnameA[i] -dnl i = i + 1 -dnl else: -dnl // Cannot combine this with previous "if" due to how m4 expands macros -dnl if i < iMid and varnameA[i] <= varnameA[j]: -dnl varnameB[k] = varnameA[i] -dnl i = i + 1 -dnl else: -dnl varnameB[k] = varnameA[j] -dnl j = j + 1 -define(`merge', `_merge(`$1', `$2', `$3', `$4', `$5', `$2', `$3', `$2')') - -dnl varnameB=$1, iBegin=$2, iMid=$3, iEnd=$4, varnameA=$5, i=$6, j=$7, k=$8 -define(`_merge', -`ifelse(eval($8 < $4), 1, -`ifelse(eval($6 < $3 && $7 >= $4), 1, -`array_set(`$1', `$8', array_get(`$5', `$6'))dnl -_merge(`$1', `$2', `$3', `$4', `$5', incr($6), `$7', incr($8))', -`ifelse(eval($6 < $3 && array_get(`$5', `$6') <= array_get(`$5', `$7')), 1, -`array_set(`$1', `$8', array_get(`$5', `$6'))dnl -_merge(`$1', `$2', `$3', `$4', `$5', incr($6), `$7', incr($8))', -`array_set(`$1', `$8', array_get(`$5', `$7'))dnl -_merge(`$1', `$2', `$3', `$4', `$5', `$6', incr($7), incr($8))'dnl -)'dnl -)'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !parse_int_list(`arrA', ARGV1)), 1, `show_usage()')dnl -ifelse(eval(array_get(`arrA', `length') < 2), 1, `show_usage()')dnl -merge_sort(`arrA', `arrB')dnl -show_int_list(`arrA') - -``` - -{% endraw %} - -Merge Sort in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/mathematica/index.md b/docs/projects/merge-sort/mathematica/index.md deleted file mode 100644 index e6251f5992..0000000000 --- a/docs/projects/merge-sort/mathematica/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-19 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2023-01-19 -layout: default -tags: -- mathematica -- merge-sort -title: Merge Sort in Mathematica -title1: Merge Sort in -title2: Mathematica ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The function takes a Mathematica list of unsorted nonnegative integers: *) - -mergeSort = list \[Function] - (* merge two sorted components *) - Apply[Function[{l, r}, - First[ (* just the merged list *) - NestWhile[ - (* merge one element from either the left or right list into output *) - Apply[Function[{m, l, r}, - If[ (* use the first element of the left list if *) - (* the right list is empty, or the left list has elements and compares before the right *) - Length[r] == 0 \[Or] (Length[l] > 0 \[And] First[l] < First[r]), - {Append[m, First[l]], Rest[l], r}, - {Append[m, First[r]], l, Rest[r]}]]], - - (* begin with just the two components *) - {{} (* will be the merged list *), l, r}, - - (* while there are still elements in either the left or right list *) - Apply[Function[{m, l, r}, Length[l] > 0 \[Or] Length[r] > 0]]]]], - - (* for each partition component, sort recursively until it contains no more than one element *) - If[Length[#] <= 1, #, mergeSort[#]] & /@ ( - (* partition the list approximately halfway *) - #[list, Floor[Length[list]/2]] & /@ {Take, Drop})]; - -(* The outer function provides the 'user interface': *) - -mergeSortMain = l \[Function] - Module[{e = "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""}, - Catch[ - StringRiffle[ - mergeSort @ - (* list must have more than one element *) - If[Length[#] > 1, #, Throw[e]] & @ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments to merge sort: list of items *) - StringSplit[l, ", "], - {-1} (* at each leaf *)], - ", "]]]; - - -(* Valid Tests *) - -Print /@ mergeSortMain /@ { - "4, 5, 3, 1, 2", - "4, 5, 3, 1, 4, 2", - "1, 2, 3, 4, 5", - "9, 8, 7, 6, 5, 4, 3, 2, 1" - }; - - -(* Invalid Tests *) - -mergeSortMain[""] -mergeSortMain["1"] -mergeSortMain["4 5 3"] - -``` - -{% endraw %} - -Merge Sort in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/objective-c/index.md b/docs/projects/merge-sort/objective-c/index.md deleted file mode 100644 index 118f5b7987..0000000000 --- a/docs/projects/merge-sort/objective-c/index.md +++ /dev/null @@ -1,181 +0,0 @@ ---- -authors: -- Harshal Singh Raushan -- rzuckerm -- Ștefan-Iulian Alecu -date: 2020-10-03 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- merge-sort -- objective-c -title: Merge Sort in Objective-C -title1: Merge Sort in -title2: Objective-C ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -@interface NSString (Parsing) -- (nullable NSArray*)strictIntegerList; -@end - -@implementation NSString (Parsing) - -- (NSArray*)strictIntegerList { - NSArray* parts = [self componentsSeparatedByString:@","]; - NSMutableArray* results = - [NSMutableArray arrayWithCapacity:parts.count]; - NSCharacterSet* invertedDigits = - NSCharacterSet.decimalDigitCharacterSet.invertedSet; - - for (NSString* raw in parts) { - NSString* s = [raw stringByTrimmingCharactersInSet: - NSCharacterSet.whitespaceAndNewlineCharacterSet]; - if (s.length == 0) return nil; - - NSString* core = ([s hasPrefix:@"-"] || [s hasPrefix:@"+"]) - ? [s substringFromIndex:1] - : s; - if (core.length == 0 || - [core rangeOfCharacterFromSet:invertedDigits].location != - NSNotFound) - return nil; - - [results addObject:@(s.longLongValue)]; - } - return (results.count >= 2) ? results : nil; -} - -@end - -@interface NSArray (Sorting) -- (NSArray*)sortedArrayUsingMergeSort; -@end - -@interface NSArray (SortingInternal) -- (NSArray*)recursivelySortedArray; -- (NSArray*)mergedWithArray:(NSArray*)other; -@end - -@implementation NSArray (Sorting) - -- (NSArray*)sortedArrayUsingMergeSort { - if (self.count < 2) return self; - return [self recursivelySortedArray]; -} - -@end - -@implementation NSArray (SortingInternal) - -- (NSArray*)recursivelySortedArray { - if (self.count < 2) return self; - - NSUInteger mid = self.count / 2; - - NSArray* left = - [[self subarrayWithRange:NSMakeRange(0, mid)] recursivelySortedArray]; - - NSArray* right = - [[self subarrayWithRange:NSMakeRange(mid, self.count - mid)] - recursivelySortedArray]; - - return [left mergedWithArray:right]; -} - -- (NSArray*)mergedWithArray:(NSArray*)other { - NSMutableArray* result = - [NSMutableArray arrayWithCapacity:self.count + other.count]; - - NSUInteger i = 0, j = 0; - - while (i < self.count && j < other.count) { - if ([self[i] compare:other[j]] != NSOrderedDescending) { - [result addObject:self[i++]]; - } else { - [result addObject:other[j++]]; - } - } - - if (i < self.count) { - [result addObjectsFromArray:[self subarrayWithRange:NSMakeRange( - i, self.count - - i)]]; - } - - if (j < other.count) { - [result - addObjectsFromArray:[other - subarrayWithRange:NSMakeRange( - j, other.count - j)]]; - } - - return result; -} - -@end - -int main(int argc, const char* argv[]) { - @autoreleasepool { - const char* usage = - "Usage: please provide a list of at least two integers to sort in " - "the format \"1, 2, 3, 4, 5\""; - - if (argc < 2) { - puts(usage); - return 1; - } - - NSArray* numbers = @(argv[1]).strictIntegerList; - - if (!numbers) { - puts(usage); - return 1; - } - - NSString* output = [[numbers sortedArrayUsingMergeSort] - componentsJoinedByString:@", "]; - - puts(output.UTF8String); - } - return 0; -} -``` - -{% endraw %} - -Merge Sort in [Objective-C](/languages/objective-c) was written by: - -- Harshal Singh Raushan -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/ocaml/index.md b/docs/projects/merge-sort/ocaml/index.md deleted file mode 100644 index e1d0680fda..0000000000 --- a/docs/projects/merge-sort/ocaml/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-23 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-05-23 -layout: default -tags: -- merge-sort -- ocaml -title: Merge Sort in OCaml -title1: Merge Sort -title2: in OCaml ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -(* This implementation performs a bottom-up merge sort*) -let ( let* ) = Option.bind - -(* Given 2 sorted lists, merge them into a single sorted list *) -let merge a b = - let rec aux acc a b = - match (a, b) with - (* If only one list has elements, append all of the remaining elements from that list *) - | _, [] -> List.rev_append acc a - | [], _ -> List.rev_append acc b - (* If both lists have elements remaining, take the smaller of the two heads *) - | a_head :: a_rest, b_head :: b_rest -> - if a_head <= b_head then aux (a_head :: acc) a_rest b - else aux (b_head :: acc) a b_rest - in - aux [] a b - -(* Merge adjacent elements in a list using f - For example, when f is merge and the input is - [[1; 5]; [3; 8]; [4; 11]; [12; 15]] - the output would be - [[1; 3; 5; 8]; [4; 11; 12; 15]] *) -let pair_map f list = - let rec aux acc list = - match list with - (* If we have at least two elements to merge, merge them *) - | first :: second :: rest -> aux (f first second :: acc) rest - (* If we have an odd element out that cannot be paired, include it directly *) - | [ first ] -> aux (first :: acc) [] - | [] -> List.rev acc - in - aux [] list - -(* Recursively merge pairs until everything has been merged into a single list - For example, repeated merges could go as follows: - [[5]; [1]; [8]; [3]; [4]; [11]; [15]; [12]] - [[1; 5]; [3, 8]; [4, 11]; [12; 15]] - [[1; 3; 5; 8]; [4; 11; 12; 15]] - [[1; 3; 4; 5; 8; 11; 12; 15]] - [1; 3; 4; 5; 8; 11; 12; 15] - *) -let rec pair_collapse f list = - match list with - | [] -> [] - (* Once we have a single element, extract it from its nest *) - | [ single ] -> single - (* While we have at least two elements to merge, recursively merge them *) - | list -> pair_collapse f (pair_map f list) - -(* Convert input list into a list of singletons, then recursively merge sorted lists *) -let merge_sort list = pair_collapse merge (List.map List.singleton list) - -let parse_list list_str = - let rec aux acc l = - match l with - | [] -> Some (List.rev acc) - | head :: rest -> - let* num = head |> String.trim |> int_of_string_opt in - aux (num :: acc) rest - in - list_str |> String.split_on_char ',' |> aux [] - -let parse_args = function [| _; nums |] -> parse_list nums | _ -> None - -let validate_args args = - let* nums = parse_args args in - match nums with [ _ ] -> None | _ -> Some nums - -let print_list l = - l |> List.map string_of_int |> String.concat ", " |> print_endline - -let () = - match validate_args Sys.argv with - | Some nums -> print_list (merge_sort nums) - | None -> - print_endline - {|Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"|} - -``` - -{% endraw %} - -Merge Sort in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/octave/index.md b/docs/projects/merge-sort/octave/index.md deleted file mode 100644 index 5d66347c29..0000000000 --- a/docs/projects/merge-sort/octave/index.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- merge-sort -- octave -title: Merge Sort in Octave -title1: Merge Sort -title2: in Octave ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function merge_sort() - %input validation - usage = 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - arg_list = argv(); - nargin = length(arg_list); - if nargin == 0 - %if there was no input - disp(usage); - return; - end - - array_string = arg_list{1}; - array_size = sum(array_string == ',') + 1; - if array_size < 2 - disp(usage); - return; - end - - %build array - array = str2num(array_string); - if length(array) ~= array_size || any(mod(array, 1) ~= 0) - disp(usage); - return; - end - - %merge sort in ascending order - array = MyMergeSort(array); - - %convert to string - result_string = num2str(array); - - %replace space with ', ' - result_string = regexprep(result_string, '\s+', ', '); - disp(result_string); -end - -function [result] = MyMergeSort( x ) - % Sort vector 'x' using the merge sort algorithm - % result is a vector consisting of the sorted values of 'x' - % in ascended order - % Takes O( n log n ) time - % Requires extra memory for merging results - - n = length(x); - if n == 1 - % Stop the recursion, if we are down to one element in list - result = x; - else - m = floor(n/2); % Get the half way point - - r1 = MyMergeSort( x(1:m) ); % Sort first half recursively... - r2 = MyMergeSort( x(m+1:n) ); % Sort 2nd half recursively... - result = MyMerge( r1, r2 ); % Merge the two halves in sorted order - end -end - -function c = MyMerge( a, b ) - % Merges 2 vectors a,b into a result vector c - % assumes a, b are already sorted - % 'c' will also be in sorted order - - aLen = length(a); % get length of a - bLen = length(b); % get length of b - cLen = aLen+bLen; - c = zeros(1,cLen); % pre-allocate 'c' to correct size - - % Initialize starting indices - aIdx = 1; - bIdx = 1; - for cIdx = 1:cLen - % Should we grab from 'a' or 'b' ??? - if aIdx > aLen - % All done with 'a' vector, grab from 'b' vector. - c(cIdx) = b(bIdx); - bIdx = bIdx + 1; - elseif bIdx > bLen - % All done with 'b' vector, grab from 'a' vector - c(cIdx) = a(aIdx); - aIdx = aIdx + 1; - elseif a(aIdx) <= b(bIdx) - % a(i) <= b(i), grab from 'a' vector - c(cIdx) = a(aIdx); - aIdx = aIdx + 1; - else - % b(i) < a(i), grab from 'b' vector - c(cIdx) = b(bIdx); - bIdx = bIdx + 1; - end - end -end - -% BY - Nikhil Gupta -% GitHub - nikkkhil067 - -``` - -{% endraw %} - -Merge Sort in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/pascal/index.md b/docs/projects/merge-sort/pascal/index.md deleted file mode 100644 index f6bd285667..0000000000 --- a/docs/projects/merge-sort/pascal/index.md +++ /dev/null @@ -1,216 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- merge-sort -- pascal -title: Merge Sort in Pascal -title1: Merge Sort -title2: in Pascal ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program MergeSort; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - StrUtils, - SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) < 2 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function FormatIntegerList(const List: TIntegerList): string; -var - i: integer; - Builder: TStringBuilder; -begin - Builder := TStringBuilder.Create; - try - for i := 0 to List.Count - 1 do - begin - if i > 0 then - Builder.Append(', '); - Builder.Append(IntToStr(List[i])); - end; - Result := Builder.ToString; - finally - Builder.Free; - end; -end; - -procedure Merge(List: TIntegerList; Temp: TIntegerList; Left, Mid, Right: integer); -var - i, j: integer; -begin - Temp.Clear; - i := Left; - j := Mid + 1; - - // Merge two sorted halves [Left..Mid] and [Mid+1..Right] into Temp. - while (i <= Mid) and (j <= Right) do - if List[i] <= List[j] then - begin - Temp.Add(List[i]); - Inc(i); - end - else - begin - Temp.Add(List[j]); - Inc(j); - end; - - // Copy any remaining elements from left half. - while i <= Mid do - begin - Temp.Add(List[i]); - Inc(i); - end; - - // Copy any remaining elements from right half. - while j <= Right do - begin - Temp.Add(List[j]); - Inc(j); - end; - - // Copy merged result back into original list. - for i := 0 to Temp.Count - 1 do - List[Left + i] := Temp[i]; -end; - -procedure MergeSort(List: TIntegerList); -var - TempBuffer: TIntegerList; - Length, Width, i, Left, Mid, Right: integer; - - function Min(const A, B: integer): integer; inline; - begin - Result := B; - if A < B then - Result := A; - end; - -begin - Length := List.Count; - - // Nothing to sort if list has 0 or 1 elements. - if Length <= 1 then Exit; - - TempBuffer := TIntegerList.Create; - try - // Bottom-up merge sort: iteratively merge sorted subarrays of increasing size - Width := 1; - while Width < Length do - begin - i := 0; - while i < Length do - begin - Left := i; - Mid := i + Width - 1; - if Mid >= Length then break; // No right half to merge - - Right := Mid + Width; - if Right >= Length then - Right := Length - 1; - - // Merge two sorted halves [Left..Mid] and [Mid+1..Right] - Merge(List, TempBuffer, Left, Mid, Right); - - // Move to next pair of subarrays - Inc(i, 2 * Width); - end; - Width := Width * 2; - end; - finally - TempBuffer.Free; - end; -end; - -var - Numbers: TIntegerList; -begin - if ParamCount <> 1 then - ShowUsage; - - Numbers := ParseIntegerList(ParamStr(1)); - try - MergeSort(Numbers); - Writeln(FormatIntegerList(Numbers)); - finally - Numbers.Free; - end; -end. - -``` - -{% endraw %} - -Merge Sort in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/perl/index.md b/docs/projects/merge-sort/perl/index.md deleted file mode 100644 index 31a94401c2..0000000000 --- a/docs/projects/merge-sort/perl/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Mr Anand Somashekhara Rao Somavarapete -- Ștefan-Iulian Alecu -date: 2023-10-03 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- merge-sort -- perl -title: Merge Sort in Perl -title1: Merge Sort -title2: in Perl ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -use feature qw/keyword_any/; -no warnings 'experimental::keyword_any'; - -sub usage { - say 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - exit; -} - -sub parse_list ($s) { - return undef unless defined $s; - - my @vals = split /\s*,\s*/, $s; - - return undef if @vals < 2; - return undef if any { $_ !~ /\A-?\d+\z/ } @vals; - - return [ map 0 + $_, @vals ]; -} - -# Note: Perl's `sort` is implemented via merge sort as of v5.42, so one could use that instead. - -sub merge_sort ($a) { - return $a if @$a <= 1; - - my $mid = @$a >> 1; - - my $left = [ @{$a}[ 0 .. $mid - 1 ] ]; - my $right = [ @{$a}[ $mid .. $#$a ] ]; - - merge_sort($left); - merge_sort($right); - - @$a = _merge( $left, $right ); - return $a; -} - -sub _merge ( $left, $right ) { - my @out; - - while ( @$left && @$right ) { - push @out, $left->[0] <= $right->[0] - ? shift @$left - : shift @$right; - } - - push @out, @$left, @$right; - - return @out; -} - -my ($input) = @ARGV; -my $a = parse_list($input) or usage(); - -merge_sort($a); -say join ', ', @$a; - -``` - -{% endraw %} - -Merge Sort in [Perl](/languages/perl) was written by: - -- Mr Anand Somashekhara Rao Somavarapete -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/php/index.md b/docs/projects/merge-sort/php/index.md deleted file mode 100644 index 2cb8762ab4..0000000000 --- a/docs/projects/merge-sort/php/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- Ankit kumar -- Jeremy Grifski -- Parker Johansen -- rzuckerm -date: 2019-10-10 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- merge-sort -- php -title: Merge Sort in PHP -title1: Merge Sort -title2: in PHP ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - 0 && count($right) > 0) { - if ($left[0] > $right[0]) { - $res[] = $right[0]; - $right = array_slice($right, 1); - } else { - $res[] = $left[0]; - $left = array_slice($left, 1); - } - } - while (count($left) > 0) { - $res[] = $left[0]; - $left = array_slice($left, 1); - } - while (count($right) > 0) { - $res[] = $right[0]; - $right = array_slice($right, 1); - } - return $res; -} - -if (empty($argv[1])) { - exit('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); -} - -$test_array = array_map('intval', explode(',', $argv[1])); -$array_size = count($test_array); - -if ($array_size <= 1) { - exit('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); -} - -echo implode(', ', merge_sort($test_array)) . "\n"; - -``` - -{% endraw %} - -Merge Sort in [PHP](/languages/php) was written by: - -- Ankit kumar -- Jeremy Grifski -- Parker Johansen -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/powershell/index.md b/docs/projects/merge-sort/powershell/index.md deleted file mode 100644 index 828a6c59ce..0000000000 --- a/docs/projects/merge-sort/powershell/index.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-14 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2025-07-14 -layout: default -tags: -- merge-sort -- powershell -title: Merge Sort in PowerShell -title1: Merge Sort in -title2: PowerShell ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -# Source: https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation -function Invoke-MergeSort([array]$A) { - # Create temporary work array and copy the values into it - $B = @($A | ForEach-Object { $_ }) - - # Run the recursive merge sort - Invoke-MergeSortRec $A 0 $A.Length $B -} - -function Invoke-MergeSortRec([array]$B, [int]$Lo, [int]$Hi, [array]$A) { - # Only sort if enough values - if (($Hi - $Lo) -gt 1) { - # Get midpoint - $Mid = ($Hi + $Lo) -shr 1 - - # Sort the left half (low to midpoint - 1) from A into B - Invoke-MergeSortRec $A $Lo $Mid $B - - # Sort the right half (midpoint to high - 1) from A into B - Invoke-MergeSortRec $A $Mid $Hi $B - - # Merge the two halves from B into A - Invoke-Merge $B $Lo $Mid $Hi $A - } -} - -function Invoke-Merge([array]$B, [int]$Lo, [int]$Mid, [int]$Hi, [array]$A) { - $i = $Lo - $j = $Mid - - # While there are elements in the left or right - for ($k = $Lo; $k -lt $Hi; $k++) { - # Copy the side that has the next largest value (or next available value if - # out of values) from the A into B - if ($i -lt $Mid -and ($j -ge $Hi -or $A[$i] -le $A[$j])) { - $B[$k] = $A[$i] - $i++ - } else { - $B[$k] = $A[$j] - $j++ - } - } -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $values = Parse-IntList $args[0] - if ($values.Length -lt 2) { - Show-Usage - } -} catch { - Show-Usage -} - -Invoke-MergeSort $values -Write-Host ($values -join ', ') - -``` - -{% endraw %} - -Merge Sort in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/python/index.md b/docs/projects/merge-sort/python/index.md deleted file mode 100644 index e36e3dca9d..0000000000 --- a/docs/projects/merge-sort/python/index.md +++ /dev/null @@ -1,375 +0,0 @@ ---- -authors: -- Haseeb Majid -- Jeremy Grifski -- Parker Johansen -- rzuckerm -date: 2018-12-22 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- merge-sort -- python -title: Merge Sort in Python -title1: Merge Sort -title2: in Python ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def merge_sort(xs): - def sort(xs): - if len(xs) <= 0: - return [] - if len(xs) == 1: - return xs - return sort([merge(xs[0], xs[1])] + sort(xs[2:])) - split_xs = [[x] for x in xs] - return sort(split_xs)[0] - - -def merge(xs, ys): - if len(xs) <= 0: - return ys - if len(ys) <= 0: - return xs - if xs[0] < ys[0]: - return [xs[0]] + merge(xs[1:], ys) - return [ys[0]] + merge(xs, ys[1:]) - - -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] - - -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) - - -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(merge_sort(xs)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Merge Sort in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Parker Johansen - -This article was written by: - -- Haseeb Majid -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's dig into the code a bit. The following sections break -down the Merge Sort in Python functionality. - -### The Main Function - -Breaking down this solution bottom up, - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -This bit of code checks to see if this is the `main` module run. If it is it then calls the `main` -function and passes user input to it. In this case, the user input would be a string of numbers to sort, -like: `"2, 1, 10, 5, 3"`. - -```python -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(merge_sort(xs)) - except (IndexError, ValueError): - exit_with_error() -``` - -This is the `main` function of this file. It parses the input, then calls our merge sort -function (and prints the results). It also deals with any errors raised. - -### Transform Input Parameters - -```python -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] -``` - -This function takes a string like `"2, 1, 10, 5, 3"`, and turns into a list of numbers. -It does this using a list comprehension. First, we need to convert our string into a -list `list_str.split(',')` which is a list of strings split by comma (`,`). -As a result, our original input string becomes `["2", " 1", " 10", " 5", " 3"]`. Then, for each -element in the list `for x in ...` , we do something to it. - -In this example we convert it into a decimal integer, `int(x.strip(" "), 10)` -`x.strip(" ")`, removes any whitespace so `" 1"` becomes `"1"`, then `int("1", 10)` -converts the string `"1"` into a decimal number in this case `1`. This is done -for every item in the list so our original input of `"2, 1, 10, 5, 3"` -becomes `[2, 1, 10, 5, 3]`. - -### Throw Errors - -```python -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) -``` - -This function prints a message and then exits the script with an error, `sys.exit(1)`. -If any non-zero value is returned then the program didn't complete properly. This function is called -if the user input isn't correct. - -### Merge - -```python -def merge(xs, ys): - if len(xs) <= 0: - return ys - if len(ys) <= 0: - return xs - if xs[0] < ys[0]: - return [xs[0]] + merge(xs[1:], ys) - return [ys[0]] + merge(xs, ys[1:]) -``` - -This function is used to sort two list together (`xs` and `ys`). There are different conditions -we must account for. The first two conditions check if either of the lists are empty. There are -a few ways to check if a list if empty such as `not xs` but in this case we are checking -if the length of the list is less than or equal to 0 `len(xs) <= 0`. If either of the -lists `xs` or `ys`, then we return the non empty list. So if `xs` is empty, we will -return the list `ys`, and if `ys` is empty, we will returns the list `xs`. - -The next thing we check for is if the first element of `xs` is less than the `ys`, -We can get the first element of a list like so `xs[0]`, then we -`return [xs[0]] + merge(xs[1:], ys)`. This is an example of recursion where the function -calls itself within the function, in this case the `merge()` function calling the `merge()` -function again. - -Since `xs[0]` is less than `y[0]` we know `xs[0]` must be -the smallest item in either list, as both lists are already sorted. So we then take `xs[0]` out -of the first list, and we convert it into a list `[xs[0]]` because we want to concatenate it with a -sorted list. The `+` operator can be used to concatenate two lists together. - -We call `merge(xs[1:], ys)` to sort the remaining items in both lists. Where `xs[1:]` is the list -`xs` without the first element. This is called index splicing in Python, you can learn more about it -[here](https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/). -We don't include the first element of `xs` because we already know it's the smallest element in -both lists. The final line `return [ys[0]] + merge(xs, ys[1:])` is the same as line above except -in this case `ys[0]` is smaller than `xs[0]` hence we use `ys[0]` at the start of the list -concatenation instead of `xs[0]`. The reason this isn't surrounded by an `else` statement is -because of the `return` statement. Nothing will be executed after it. - -Let's take a look at an example, where `xs = [3, 4]` and `ys = [1, 10]` - -Merge 1: - -* `xs = [3, 4]` -* `ys = [1, 10]` -* `len(xs) = 2` and `2 > 0` -* `len(ys) = 2` and `2 > 0` -* `xs[0] = 3` and `ys[0] = 1` and `3 > 1` -* `[1] + merge([3, 4], [10])` - -Merge 2: - -* `xs = [3, 4]` -* `ys = [10]` -* `len(xs) = 2` and `2 > 0` -* `len(ys) = 1` and `1 > 0` -* `xs[0] = 3` and `ys[0] = 4` and `3 < 4` -* `[3] + merge([4], [10])` - -Merge 3: - -* `xs = [4]` -* `ys = [10]` -* `len(xs) = 1` and `1 > 0` -* `len(ys) = 1` and `1 > 0` -* `xs[0] = 4` and `ys[0] = 10` and `4 < 10` -* `[4] + merge([], [10])` - -Merge 4: - -* `xs = []` -* `ys = [10]` -* len(xs) = 0 and 0 <= 0 -* return `[10]` - -Going backwards: - -* `[4] + [10] = [4, 10]` (Merge 3) -* `[3] + [4, 10] = [3, 4, 10]` (Merge 2) -* `[1] + [3, 4, 10]` = `[1, 3, 4, 10]` (Merge 1) - -### Merge Sort - -```python -def merge_sort(xs): - def sort(xs): - if len(xs) <= 0: - return [] - if len(xs) == 1: - return xs - return sort([merge(xs[0], xs[1])] + sort(xs[2:])) - split_xs = [[x] for x in xs] - return sort(split_xs)[0] -``` - -This is the function that actually sorts our entire list. - -```python - def merge_sort(xs): - def sort(xs): -``` - -This is known as closure nested functions (a function within another function). -The nested function can access variables of the enclosing scope. They can read -variables but cannot edit them. In the example above, the `xs` variable is our -unsorted list. - -The `sort()` function only exists within the scope of `merge_sort()` but other than that -is works exactly the same as a normal function. - -```python -split_xs = [[x] for x in xs] -return sort(split_xs)[0] -``` - -In this example, we execute the above lines. First. you can ignore the `sort()` function until -it's called within `merge_sort()`. `split_xs = [[x] for x in xs]` splits our lists into separate lists. -It takes each element with in `xs` and turns it into a list `[x]`. So `split_xs` is now a list of lists. -If `xs = [3, 10, 5]` then `split_xs = [[3], [10], [5]]`. The final sorted result will look something -like this [[3, 5, 10]] another list of lists hence we want to return the first element -`sort(split_xs)[0]`. - -```python -def sort(xs): - if len(xs) <= 0: - return [] - if len(xs) == 1: - return xs - return sort([merge(xs[0], xs[1])] + sort(xs[2:])) -``` - -So what happens in the `sort()` function lets take a look. Using our example above the function -would be called by `sort([[3], [10], [5]])`. The first if statement checks if the `xs` list is -empty by checking that the length is less than or equal to 0 `len(xs) <= 0`. If so, we return an empty list `return []`. -The second statement checks if the list `xs` contains a single element `len(xs) == 1`. -If it does, we return the list `return xs`. Finally if the list `xs` has more than 1 element -`return sort([merge(xs[0], xs[1])] + sort(xs[2:]))`. - -Breaking this down this is another example of a recursive function, the `sort()` function is -calling itself. Breaking down the argument passed to the sort function, -`[merge(xs[0], xs[1])]` here we call our `merge()` function with the first two items of the `xs` -list, then we convert the returned element into a list, hence being surronded by `[]`. The second -part of the argument `sort(xs[2:])` calls the `sort()` function again but without the first two -elements of `xs`, again using list comprehension. - -We then combine these two lists together using -list concatenation using the plus `+` operator `[merge(xs[0], xs[1])] + sort(xs[2:]`. Taking a look -at an example where `xs = [[4], [10], [9], [5]]` the final sort function would look like -`sort([merge([4], [10]) + sort([[9], [5]]))`. - -Lets take a look at how we would sort the list `xs = [4, 3, 1, 10]`: - -* `merge_sort([4, 3, 1, 10])` -* `split_xs = [[4], [3], [1], [10]]` - -Sort 1: - -* `xs = [[4], [3], [1], [10]]` -* `len(xs) = 4` -* `sort([merge([4], [3])] + sort([[1], [10]]))` -* `[merge([4], [3])] = [[3, 4]]` -* `sort([[3, 4]] + sort([[1], [10]]))` - -Sort 2: - -* `xs = [[1], [10]]` -* `len(xs) = 2` -* `sort([merge([1], [10])] + sort([]))` -* `[merge([1], [10])] = [[1, 10]]` -* `sort([[1, 10]] + sort([]))` - -Sort 3: - -* `xs = []` -* `len(xs) = 0` -* `return []` - -Going Backwards (Sort 2): - -* `sort([[1, 10]] + [])` - -Sort: - -* `xs = [[1, 10]]` -* `len(xs) = 1` -* `return xs = return [1, 10]` - -Going Backwards (Sort 1): - -* `sort([merge([3, 4])], [1, 10]))` -* `sort([[1, 3, 4, 10]])` - -Sort: - -* `xs = [[1, 3, 4, 10]]` -* `len(xs) = 1` -* `return [1, 3, 4, 10]` - -So: - -* `return sort([[3, 4]] + sort([[1], [10]])) = [1, 3, 4, 10]` - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Selection Sort in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/merge_sort.py). -After that, we should make sure we have the [latest Python interpreter](https://www.python.org/downloads/). From there, we can run the -following command in the terminal: - -`python merge-sort.py "3, 2, 10, 6, 1, 7"` - -Alternatively, we can copy the solution into an [online Python interpreter](https://www.online-python.com/) and hit run. diff --git a/docs/projects/merge-sort/ruby/index.md b/docs/projects/merge-sort/ruby/index.md deleted file mode 100644 index eaedda17eb..0000000000 --- a/docs/projects/merge-sort/ruby/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- merge-sort -- ruby -title: Merge Sort in Ruby -title1: Merge Sort -title2: in Ruby ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -def usage! - abort %(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5") -end - -def parse_input - raw = ARGV.first - usage! if raw.nil? || raw.strip.empty? - - numbers = raw.split(",").map { Integer(it.strip) } - usage! if numbers.length < 2 - - numbers -rescue ArgumentError, NoMethodError - usage! -end - -def merge_sort(arr) - return arr if arr.length <= 1 - - mid = arr.length / 2 - left = merge_sort(arr[0...mid]) - right = merge_sort(arr[mid..]) - - merge(left, right) -end - -def merge(left, right) - i = 0 - j = 0 - result = [] - - while i < left.length && j < right.length - if left[i] <= right[j] - result << left[i] - i += 1 - else - result << right[j] - j += 1 - end - end - - result.concat(left[i..] || []) - result.concat(right[j..] || []) - result -end - -numbers = parse_input -puts merge_sort(numbers).join(", ") - -``` - -{% endraw %} - -Merge Sort in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/rust/index.md b/docs/projects/merge-sort/rust/index.md deleted file mode 100644 index 9ffab4d987..0000000000 --- a/docs/projects/merge-sort/rust/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- Andrew Johnson -- rzuckerm -date: 2020-10-03 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- merge-sort -- rust -title: Merge Sort in Rust -title1: Merge Sort -title2: in Rust ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -fn merge(lhs: &Vec, rhs: &Vec, merged_arr: &mut Vec) { - let mut lhs_idx = 0; - let mut rhs_idx = 0; - let mut merged_idx = 0; - - while lhs_idx < lhs.len() && rhs_idx < rhs.len() { - if lhs[lhs_idx] < rhs[rhs_idx] { - merged_arr[merged_idx] = lhs[lhs_idx]; - lhs_idx += 1; - } else { - merged_arr[merged_idx] = rhs[rhs_idx]; - rhs_idx += 1; - } - - merged_idx += 1; - } - - if lhs_idx < lhs.len() { - merged_arr[merged_idx..].copy_from_slice(&lhs[lhs_idx..]); - } - else if rhs_idx < rhs.len() { - merged_arr[merged_idx..].copy_from_slice(&rhs[rhs_idx..]); - } -} - -fn merge_sort(arr: &mut Vec) { - if arr.len() <= 1 { - return; - } - - let mid = arr.len() / 2; - let mut lhs = arr[..mid].to_vec(); - let mut rhs = arr[mid..].to_vec(); - - merge_sort(&mut lhs); - merge_sort(&mut rhs); - - merge(&lhs, &rhs, arr); -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let mut arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if list too small - if arr.len() < 2 { - usage(); - } - - merge_sort::(&mut arr); - println!("{arr:?}"); -} - -``` - -{% endraw %} - -Merge Sort in [Rust](/languages/rust) was written by: - -- Andrew Johnson -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/swift/index.md b/docs/projects/merge-sort/swift/index.md deleted file mode 100644 index 5212e4cb1f..0000000000 --- a/docs/projects/merge-sort/swift/index.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- merge-sort -- swift -title: Merge Sort in Swift -title1: Merge Sort -title2: in Swift ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseIntegers(from args: [String]) -> [Int]? { - guard args.count == 2 else { return nil } - - let parts = args[1].split(separator: ",", omittingEmptySubsequences: false) - let values = parts.compactMap { Int($0.trimmed) } - - guard values.count == parts.count, - values.count >= 2 - else { - return nil - } - - return values -} - -extension RangeReplaceableCollection -where Self: MutableCollection, Self: RandomAccessCollection, Element: Comparable { - mutating func mergeSort(by areInIncreasingOrder: (Element, Element) -> Bool) { - var buffer = Array(self) - var temp = buffer - - mergeSort(&buffer, &temp, start: 0, end: buffer.count, by: areInIncreasingOrder) - - self = Self(buffer) - } - - private func mergeSort( - _ buffer: inout [Element], - _ temp: inout [Element], - start: Int, - end: Int, - by areInIncreasingOrder: (Element, Element) -> Bool - ) { - guard end - start > 1 else { return } - - let mid = (start + end) / 2 - - mergeSort(&buffer, &temp, start: start, end: mid, by: areInIncreasingOrder) - mergeSort(&buffer, &temp, start: mid, end: end, by: areInIncreasingOrder) - - merge(&buffer, &temp, start: start, mid: mid, end: end, by: areInIncreasingOrder) - } - - private func merge( - _ buffer: inout [Element], - _ temp: inout [Element], - start: Int, - mid: Int, - end: Int, - by areInIncreasingOrder: (Element, Element) -> Bool - ) { - var i = start - var j = mid - var k = start - - while i < mid && j < end { - if areInIncreasingOrder(buffer[i], buffer[j]) { - temp[k] = buffer[i] - i += 1 - } else { - temp[k] = buffer[j] - j += 1 - } - k += 1 - } - - while i < mid { - temp[k] = buffer[i] - i += 1 - k += 1 - } - - while j < end { - temp[k] = buffer[j] - j += 1 - k += 1 - } - - for index in start.. - -Welcome to the [Merge Sort](/projects/merge-sort) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"} - exit 1 -} - -proc parseList {s} { - set tokens [split [string trim $s] ","] - if {[llength $tokens] < 2} { usage } - - set result {} - foreach token $tokens { - set t [string trim $token] - if {$t eq "" || [catch {expr {int($t)}} val]} usage - lappend result $val - } - return $result -} - -proc merge {lstVar tempVar left mid right} { - upvar 1 $lstVar lst - upvar 1 $tempVar temp - - set i $left - set j [expr {$mid + 1}] - set k $left - - while {$i <= $mid && $j <= $right} { - if {[lindex $lst $i] <= [lindex $lst $j]} { - lset temp $k [lindex $lst $i] - incr i - } else { - lset temp $k [lindex $lst $j] - incr j - } - incr k - } - - while {$i <= $mid} { - lset temp $k [lindex $lst $i] - incr i - incr k - } - - while {$j <= $right} { - lset temp $k [lindex $lst $j] - incr j - incr k - } - - for {set idx $left} {$idx <= $right} {incr idx} { - lset lst $idx [lindex $temp $idx] - } -} - -proc mergeSort {lstVar} { - upvar 1 $lstVar lst - set n [llength $lst] - if {$n <= 1} { return } - - set temp {} - set width 1 - while {$width < $n} { - set i 0 - while {$i < $n} { - set left $i - set mid [expr {$i + $width - 1}] - if {$mid >= $n} { break } - - set right [expr {$mid + $width}] - if {$right >= $n} { set right [expr {$n - 1}] } - - merge lst temp $left $mid $right - incr i [expr {2 * $width}] - } - set width [expr {$width * 2}] - } -} - -proc formatList {lst} { return [join $lst ", "] } - -if {$argc != 1} { usage } - -set numbers [parseList [lindex $argv 0]] -mergeSort numbers -puts [formatList $numbers] - - -``` - -{% endraw %} - -Merge Sort in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/typescript/index.md b/docs/projects/merge-sort/typescript/index.md deleted file mode 100644 index 6d1710b4d7..0000000000 --- a/docs/projects/merge-sort/typescript/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Aaron -date: 2024-10-06 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2024-10-06 -layout: default -tags: -- merge-sort -- typescript -title: Merge Sort in TypeScript -title1: Merge Sort in -title2: TypeScript ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript - -function DisplayErrorMessage() { - console.log( - `Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"`, - ); - process.exit(1); -} - -/** - * Processes user arguments from CLI, displays usages message and exits if arguments are incorrect - * @returns user input argument as a list to be merge sorted - */ -function VerifyUserInput(): number[] { - if (process.argv.length != 3) { - DisplayErrorMessage(); - } - // regex string to match requirements - const regexStr = /^([0-9]+)((, ?)([0-9]+))+$/; - const regex = new RegExp(regexStr); - const user_arg_pos = 2 - const numbers: string = process.argv[user_arg_pos]; - - if (numbers.length == 0 || !numbers.match(regex)) { - DisplayErrorMessage(); - } - // split numbers into array and parse values - return numbers.split(",").map((x) => parseInt(x)); -} - -/** - * Sorts and merges divided subsets of array. - * @param array the array to be sorted. Not that this will be updated. - * @param first the start of the unsorted array - * @param middle the middle of the unsorted array - * @param last the end of the unsorted array - */ -function Merge(array: number[], first: number, middle: number, last: number) { - // initial to "split" arrays - const fixed_middle = middle + 1 - const fixed_last = last + 1 - const left = array.slice(first, fixed_middle) - const right = array.slice(fixed_middle, fixed_last) - const sortedArray = [] - // sort values into sorted array - var index_left = 0 - var index_right = 0 - while (index_left < left.length) { - var leftVal = left[index_left] - if (index_right < right.length && right[index_right] < leftVal) { - sortedArray.push(right[index_right]) - index_right++ - } else { - sortedArray.push(leftVal) - index_left++ - } - } - // modify the original array to include the new sorted array - array.splice(first, sortedArray.length, ...sortedArray) -} - -/** - * Implements the Merge Sort algorithm by dividing the given array into smaller and smaller values - * then sorting and merging the list - * - * @param numbers the array to be sorted. Note that this will be updated - * @param first the starting index of the array - * @param last the ending index of the array - */ -function MergeSort(numbers: number[], first: number, last: number) { - if (first < last) { - var middle: number = Math.floor((first + last) / 2) - MergeSort(numbers, first, middle) - MergeSort(numbers, middle + 1, last) - Merge(numbers, first, middle, last) - } -} - -// start program - -const numbers: number[] = VerifyUserInput() -const first: number = 0 -const last: number = numbers.length - 1 -MergeSort(numbers, first, last) -console.log(numbers.join(", ")) - -``` - -{% endraw %} - -Merge Sort in [TypeScript](/languages/typescript) was written by: - -- Aaron - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/merge-sort/visual-basic/index.md b/docs/projects/merge-sort/visual-basic/index.md deleted file mode 100644 index aae6c3eae5..0000000000 --- a/docs/projects/merge-sort/visual-basic/index.md +++ /dev/null @@ -1,168 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: merge-sort-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- merge-sort -- visual-basic -title: Merge Sort in Visual Basic -title1: Merge Sort in -title2: Visual Basic ---- - - - -Welcome to the [Merge Sort](/projects/merge-sort) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module MergeSort - - Public Function Sort(Of T)(input As IEnumerable(Of T), - Optional compare As IComparer(Of T) = Nothing) As List(Of T) - - If compare Is Nothing Then - compare = Comparer(Of T).Default - End If - - Dim list As New List(Of T)(input) - If list.Count < 2 Then Return list - - Return MergeSortInternal(list, compare) - - End Function - - - Private Function MergeSortInternal(Of T)(list As List(Of T), - comparer As IComparer(Of T)) As List(Of T) - - If list.Count <= 1 Then - Return list - End If - - Dim mid As Integer = list.Count \ 2 - - Dim left = list.GetRange(0, mid) - Dim right = list.GetRange(mid, list.Count - mid) - - Dim sortedLeft = MergeSortInternal(left, comparer) - Dim sortedRight = MergeSortInternal(right, comparer) - - Return Merge(sortedLeft, sortedRight, comparer) - - End Function - - - Private Function Merge(Of T)(left As List(Of T), - right As List(Of T), - comparer As IComparer(Of T)) As List(Of T) - - Dim result As New List(Of T)(left.Count + right.Count) - - Dim i As Integer = 0 - Dim j As Integer = 0 - - While i < left.Count AndAlso j < right.Count - - If comparer.Compare(left(i), right(j)) <= 0 Then - result.Add(left(i)) - i += 1 - Else - result.Add(right(j)) - j += 1 - End If - - End While - - While i < left.Count - result.Add(left(i)) - i += 1 - End While - - While j < right.Count - result.Add(right(j)) - j += 1 - End While - - Return result - - End Function - - - Private Sub ShowUsage() - - Console.WriteLine( - "Usage: please provide a list of at least two integers to sort " & - "in the format ""1, 2, 3, 4, 5""" - ) - - Environment.Exit(1) - - End Sub - - - Public Sub Main(args As String()) - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim parts = args(0).Split(","c, StringSplitOptions.RemoveEmptyEntries) - - Dim numbers As New List(Of Integer) - - For Each p In parts - - Dim value As Integer - - If Not Integer.TryParse(p.Trim(), value) Then - ShowUsage() - End If - - numbers.Add(value) - - Next - - If numbers.Count < 2 Then - ShowUsage() - End If - - Dim sorted = Sort(numbers) - - Console.WriteLine(String.Join(", ", sorted)) - - End Sub - -End Module -``` - -{% endraw %} - -Merge Sort in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/algol60/index.md b/docs/projects/minimum-spanning-tree/algol60/index.md deleted file mode 100644 index 59460bcc6f..0000000000 --- a/docs/projects/minimum-spanning-tree/algol60/index.md +++ /dev/null @@ -1,384 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-22 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-04-22 -layout: default -tags: -- algol60 -- minimum-spanning-tree -title: Minimum Spanning Tree in ALGOL 60 -title1: Minimum Spanning -title2: Tree in ALGOL 60 ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a comma-separated list of integers\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - boolean procedure validateInputs(weights, numWeights, src, dest, numVertices); - value numWeights, src, dest, numVertices; - integer array weights; - integer numWeights, src, dest, numVertices; - begin - boolean valid, anyNonZero; - integer i; - - valid := true; - - comment Validate number of weights and source and destination node; - if (numWeights != numVertices * numVertices | - src < 0 | src >= numVertices | dest < 0 | dest >= numVertices) - then valid := false; - - comment Verify weights greater than equal to zero and any non-zero - weights; - anyNonZero := false; - i := 0; - weightLoop: - i := i + 1; - if valid & i <= numWeights then - begin - if weights[i] > 0 then anyNonZero := true - else if weights[i] < 0 then valid := false; - goto weightLoop - end; - - if !anyNonZero then valid := false; - - validateInputs := valid - end validateInputs; - - comment Create graph from weights. - The graph is in this form: - - column 1: Number of edges for each node - - column 2, 4, ..., 2*n: Index of each child node - - column 3, 5, ..., 2*n+1: Weight of each child node - - where n = number of vertices; - procedure createGraph(graph, weights, numVertices); - value numVertices; - integer array graph, weights; - integer numVertices; - begin - integer u, v, idx, numEdges; - - idx := 0; - for u := 1 step 1 until numVertices do - begin - comment Initialize number of edges for this node; - numEdges := 0; - - for v := 1 step 1 until numVertices do - begin - idx := idx + 1; - if weights[idx] > 0 then - begin - comment Update number of edges, store child index and - weight; - numEdges := numEdges + 1; - graph[u, 2 * numEdges] := v; - graph[u, 2 * numEdges + 1] := weights[idx] - end - end; - - comment Store number of edges for this node; - graph[u, 1] := numEdges - end - end createGraph; - - comment Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of - https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/. - Returns matrix in following format: - - Column 1: Parent node indices - - Column 2: Target node indices - - Column 3: Weights; - procedure primMst(graph, numVertices, mstResult); - value numVertices; - integer array graph, mstResult; - integer numVertices; - begin - comment Find vertex with minimum key values not already in MST; - integer procedure findMinKey(keys, mstSet); - integer array keys; - boolean array mstSet; - begin - integer minValue, minIndex, v; - - minValue := maxint; - minIndex := 0; - for v := 1 step 1 until numVertices do - begin - if !mstSet[v] & keys[v] < minValue then - begin - minValue := keys[v]; - minIndex := v - end - end; - - findMinKey := minIndex - end findMinKey; - - integer array parents[1:numVertices], keys[1:numVertices]; - boolean array mstSet[1:numVertices]; - integer i, j, u, v, w; - - comment Initialize key values to infinite and indicate nothing is in - MST yet; - for i := 1 step 1 until numVertices do - begin - keys[i] := maxint; - mstSet[i] := false - end; - - comment Include first vertex in MST, and root has no parent; - keys[1] := 0; - parents[1] := 0; - - for i := 1 step 1 until numVertices - 1 do - begin - comment Pick index of the minimum key value not already in MST; - u := findMinKey(keys, mstSet); - - comment Add picked vertex to MST set; - mstSet[u] := true; - - comment Update key values and parent indices of picked adjacent - vertices. Only consider vertices not yet in MST; - for j := 1 step 1 until graph[u, 1] do - begin - v := graph[u, j * 2]; - w := graph[u, j * 2 + 1]; - if !mstSet[v] & w < keys[v] then - begin - parents[v] := u; - keys[v] := w - end - end - end; - - comment Store MST results, skipping over root and adjusting vertex - numbers to account for 1-based indexing; - for i := 2 step 1 until numVertices do - begin - mstResult[i - 1, 1] := parents[i] - 1; - mstResult[i - 1, 2] := i - 1; - mstResult[i - 1, 3] := keys[i] - end - end primMst; - - integer procedure getTotalMstWeight(mstResult, numResults); - value numResults; - integer array mstResult; - integer numResults; - begin - integer total, i; - - total := 0; - for i := 1 step 1 until numResults do total := total + mstResult[i, 3]; - - getTotalMstWeight := total - end getTotalMstWeight; - - integer argc, ch, src, dest, numWeights, numVertices; - integer array weights[1:1024]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get weights from 1st argument. Exit if invalid; - numWeights := inIntegerArray(weights, 1024); - if numWeights < 1 then usage; - - comment Validate inputs. Exit if invalid; - numVertices := sqrt(numWeights); - if numWeights != numVertices * numVertices then usage; - - begin - comment Create graph based on weights; - integer array graph[1:numVertices, 1:2 * numVertices + 1]; - integer array mstResult[1:numVertices - 1, 1:3]; - integer total; - createGraph(graph, weights, numVertices); - - comment Get MST using Prim's algorithm; - primMst(graph, numVertices, mstResult); - - comment Get total weight and output result; - total := getTotalMstWeight(mstResult, numVertices - 1); - outinteger(1, total); - outstring(1, "\n") - end -end - -``` - -{% endraw %} - -Minimum Spanning Tree in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/algol68/index.md b/docs/projects/minimum-spanning-tree/algol68/index.md deleted file mode 100644 index 2c12143bcd..0000000000 --- a/docs/projects/minimum-spanning-tree/algol68/index.md +++ /dev/null @@ -1,276 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-06 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2023-02-06 -layout: default -tags: -- algol68 -- minimum-spanning-tree -title: Minimum Spanning Tree in ALGOL 68 -title1: Minimum Spanning -title2: Tree in ALGOL 68 ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: printf(($gl$, "Usage: please provide a comma-separated list of integers")); - -# Convert list of values to a matrix # -PROC convert to matrix = (REF []INT values, INT num rows, INT num cols) REF [, ]INT: -( - HEAP [num rows, num cols]INT matrix; - INT count := 0; - FOR i TO num rows - DO - FOR j TO num cols - DO - count +:= 1; - matrix[i, j] := values[count] - OD - OD; - - matrix -); - -COMMENT -Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of -https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ -COMMENT -MODE MST = STRUCT(INT vertex1, INT vertex2, INT weight); -PROC prim mst = (REF [, ]INT graph) REF []MST: -( - INT num vertices := UPB graph; - - # Array to store constructed MST # - [num vertices]INT parents; - - # Key values used to pick minimum weight edge # - [num vertices]INT keys; - - # Array used to indicate if vertex is in MST # - [num vertices]BOOL mst set; - - # Initialize key values to infinite and indicate nothing is in MST yet # - FOR k TO num vertices - DO - keys[k] := max int; - mst set[k] := FALSE - OD; - - # Include first vertex in MST # - keys[1] := 1; - parents[1] := 0; # Root has no parent # - - # The MST will include all vertices # - FOR k TO num vertices - 1 - DO - # Pick index of the minimum key value not already in MST # - INT u := find min key(keys, mst set); - - # Add picked vertex to MST set # - mst set[u] := TRUE; - - # Update key values and parent indices of picked adjacent # - # vertices. Only consider vertices not yet in MST # - FOR v TO num vertices - DO - INT graph value := graph[u, v]; - IF NOT mst set[v] AND graph value > 0 AND graph value < keys[v] - THEN - parents[v] := u; - keys[v] := graph value - FI - OD - OD; - - # Construct MST information to return # - HEAP [num vertices - 1]MST mst; - - # Skip over root and adjust vertex numbers to account for 1-based indexing # - FOR k FROM 2 TO num vertices - DO - mst[k - 1] := MST(parents[k] - 1, k - 1, graph[k, parents[k]]) - OD; - - mst -); - -# Find vertex with minimum key values not already in MST # -PROC find min key = (REF []INT keys, REF []BOOL mst set) INT: -( - INT min value := max int; - INT min index; - FOR v TO UPB keys - DO - IF keys[v] < min value AND NOT mst set[v] - THEN - min value := keys[v]; - min index := v - FI - OD; - - min index -); - -# Get total MST weight # -PROC get total mst weight = (REF []MST mst) INT: -( - INT total weight := 0; - FOR v TO UPB mst - DO - total weight +:= weight OF mst[v] - OD; - - total weight -); - -# Parse 1st command-line argument and make sure number of values is a square # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -INT num values := UPB values; -INT sqrt num values := ENTIER(sqrt(num values) + 0.5); -IF NOT valid OF list result OR num values /= sqrt num values * sqrt num values -THEN - usage; - stop -FI; - -# Convert values to matrix # -REF [, ]INT graph := convert to matrix(values, sqrt num values, sqrt num values); - -# Get MST using Prim's algorithm # -REF []MST mst := prim mst(graph); - -# Calculate total weight of MST and display # -INT total weight := get total mst weight(mst); -printf(($gl$, whole(total weight, 0))) - -``` - -{% endraw %} - -Minimum Spanning Tree in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/awk/index.md b/docs/projects/minimum-spanning-tree/awk/index.md deleted file mode 100644 index a8e68910f0..0000000000 --- a/docs/projects/minimum-spanning-tree/awk/index.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-29 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2025-04-29 -layout: default -tags: -- awk -- minimum-spanning-tree -title: Minimum Spanning Tree in AWK -title1: Minimum Spanning -title2: Tree in AWK ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a comma-separated list of integers" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -function create_graph(weights, num_vertices, graph, u, v, idx) { - idx = 0 - for (u = 0; u < num_vertices; u++) { - for (v = 0; v < num_vertices; v++) { - idx++ - if (weights[idx] > 0) { - graph[u][v] = weights[idx] - } - } - } -} - -# Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of -# https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ -function prim_mst(graph, num_vertices, mst, i, u, v, parents, keys, mst_set, graph_value) { - # Initialize key values to infinite - for (i = 0; i < num_vertices; i++) { - keys[i] = 1e999 # Awk doesn't have infinity, so use large integer - } - - # Include first vertex in MST - keys[0] = 0 - parents[0] = -1 # Root has no parent # - - # For each vertex - for (i = 1; i < num_vertices; i++) { - # Pick index of the minimum key value not already in MST - u = find_min_key(keys, mst_set) - - # Add picked vertex to MST set - mst_set[u] = 1 - - # Update key values and parent indices of picked adjacent - # vertices. Only consider vertices not yet in MST set - for (v in graph[u]) { - graph_value = graph[u][v] - if (!(v in mst_set) && graph_value < keys[v]) { - parents[v] = u - keys[v] = graph_value - } - } - } - - # Construct MST information to return, skipping over root - for (i = 1; i < num_vertices; i++) { - mst[i]["vertex1"] = parents[i] - mst[i]["vertex2"] = i - mst[i]["weight"] = graph[i][parents[i]] - } -} - -function find_min_key(keys, mst_set, min_key, min_index, v) { - min_key = 1e999 - min_index = -1 - for (v in keys) { - if (keys[v] < min_key && !(v in mst_set)) { - min_key = keys[v] - min_index = v - } - } - - return min_index -} - -function get_total_mst_weight(mst, i, total) { - total = 0 - for (i in mst) { - total += mst[i]["weight"] - } - - return total -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], weights) - num_weights = length(weights) - num_vertices = int(sqrt(num_weights) + 0.5) - if (!num_weights || weights[1] == "ERROR" || \ - num_vertices * num_vertices != num_weights) { - usage() - } - - create_graph(weights, num_vertices, graph) - prim_mst(graph, num_vertices, mst) - print get_total_mst_weight(mst) -} - -``` - -{% endraw %} - -Minimum Spanning Tree in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/beef/index.md b/docs/projects/minimum-spanning-tree/beef/index.md deleted file mode 100644 index 29f408afa8..0000000000 --- a/docs/projects/minimum-spanning-tree/beef/index.md +++ /dev/null @@ -1,279 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-26 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2024-02-26 -layout: default -tags: -- beef -- minimum-spanning-tree -title: Minimum Spanning Tree in Beef -title1: Minimum Spanning -title2: Tree in Beef ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace MinimumSpanningTree; - -struct NodeItem -{ - public int mIndex; - public T mWeight; - - public this(int index, T weight) - { - mIndex = index; - mWeight = weight; - } -} - -class Node -{ - public int mIndex; - public List> mChildren = new .() ~ delete _; - - public this(int index) - { - mIndex = index; - } - - public void AddChild(int index, T weight) - { - mChildren.Add(.(index, weight)); - } -} - -class Tree -where int : operator T <=> T -{ - public List> mVertices = new .() ~ DeleteContainerAndItems!(_); - - public this(List weights, int numVertices) - { - // Create nodes - for (int index < numVertices) - { - mVertices.Add(new .(index)); - } - - int index = 0; - for (int row < numVertices) - { - for (int col < numVertices) - { - if (weights[index] > default(T)) - { - mVertices[row].AddChild(col, weights[index]); - } - - index++; - } - } - } -} - -struct MstResult -{ - public int mSrcIndex; - public int mDestIndex; - public T mWeight; - - public this(int srcIndex, int destIndex, T weight) - { - mSrcIndex = srcIndex; - mDestIndex = destIndex; - mWeight = weight; - } -} - -class MstResults: List> -where T : operator T + T -{ - public T GetTotalMstWeight() - { - T total = default(T); - for (MstResult mstResult in this) - { - total += mstResult.mWeight; - } - - return total; - } -} - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a comma-separated list of integers"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of - // https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ - public static void PrimMst(Tree tree, MstResults mstResults) - where T : operator T + T, IMinMaxValue - where int : operator T <=> T - { - int numVertices = tree.mVertices.Count; - - // Indicate no parents yet, and initialize minimum weights to infinity - List parents = scope .(); - List keys = scope .(); - for (int i < numVertices) - { - parents.Add(0); - keys.Add(T.MaxValue); - } - - // Indicate nothing in MST - HashSet mstSet = scope .(); - - // Include first vertex in MST - keys[0] = default(T); - - // While all nodes not in MST - while (mstSet.Count < numVertices) - { - // Pick vertex of the minimum key value not already in MST - int u = -1; - T minWeight = T.MaxValue; - for (int index < numVertices) - { - if (!mstSet.Contains(index) && keys[index] < minWeight) - { - u = index; - minWeight = keys[index]; - } - } - - // Add selected vertex - mstSet.Add(u); - - // Update key values and parent indices of picked adjacent vertices, - // only considering vertices not in MST - for (NodeItem item in tree.mVertices[u].mChildren) - { - int v = item.mIndex; - T w = item.mWeight; - if (!mstSet.Contains(v) && w < keys[v]) - { - parents[v] = u; - keys[v] = w; - } - } - } - - // Construct MST results, skipping over root - mstResults.Clear(); - for (int v in 1.. weights = scope .(); - int numWeights = ?; - int numVertices = ?; - switch (ParseIntList(args[0], weights)) - { - case .Ok: - numWeights = weights.Count; - numVertices = (int)Math.Round(Math.Sqrt(numWeights)); - if (numWeights != numVertices * numVertices) - { - Usage(); - } - - case .Err: - Usage(); - } - - Tree tree = scope .(weights, numVertices); - MstResults mstResults = scope .(); - PrimMst(tree, mstResults); - Console.WriteLine(mstResults.GetTotalMstWeight()); - - return 0; - } -} - -``` - -{% endraw %} - -Minimum Spanning Tree in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/c-plus-plus/index.md b/docs/projects/minimum-spanning-tree/c-plus-plus/index.md deleted file mode 100644 index b41305c470..0000000000 --- a/docs/projects/minimum-spanning-tree/c-plus-plus/index.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -authors: -- SketchRudy -- Ștefan-Iulian Alecu -date: 2025-02-17 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- minimum-spanning-tree -title: Minimum Spanning Tree in C++ -title1: Minimum Spanning -title2: Tree in C++ ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -struct Edge { - int src; - int dest; - int weight; -}; - -[[noreturn]] void usage() { - std::cerr << "Usage: please provide a comma-separated list of integers\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - - return out.empty() ? std::nullopt : std::make_optional(out); -} - -struct DSU { - std::vector parent; - std::vector rank; - - explicit DSU(int n) : parent(n), rank(n, 0) { - std::iota(parent.begin(), parent.end(), 0); - } - - int find(int x) { - if (parent[x] != x) parent[x] = find(parent[x]); - return parent[x]; - } - - void unite(int a, int b) { - a = find(a); - b = find(b); - - if (a == b) return; - - if (rank[a] < rank[b]) - parent[a] = b; - else if (rank[a] > rank[b]) - parent[b] = a; - else { - parent[b] = a; - rank[a]++; - } - } -}; - -int kruskal_mst(std::vector& edges, int V) { - ranges::sort(edges, {}, &Edge::weight); - - DSU dsu(V); - - int cost = 0; - int used = 0; - - for (const auto& e : edges) { - if (dsu.find(e.src) != dsu.find(e.dest)) { - dsu.unite(e.src, e.dest); - cost += e.weight; - - if (++used == V - 1) break; - } - } - - return cost; -} - -int main(int argc, char* argv[]) { - if (argc < 2 || std::string_view(argv[1]).empty()) usage(); - - auto values = parse_vec(argv[1]); - if (!values) usage(); - - const int n = static_cast(values->size()); - const int V = static_cast(std::sqrt(n)); - - if (V * V != n) usage(); - - std::vector edges; - - for (int i = 0; i < V; ++i) { - for (int j = i + 1; j < V; ++j) { - int w = values->at(i * V + j); - if (w != 0) edges.push_back({i, j, w}); - } - } - - std::cout << kruskal_mst(edges, V) << '\n'; -} -``` - -{% endraw %} - -Minimum Spanning Tree in [C++](/languages/c-plus-plus) was written by: - -- SketchRudy -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/c-sharp/index.md b/docs/projects/minimum-spanning-tree/c-sharp/index.md deleted file mode 100644 index d71c3c1655..0000000000 --- a/docs/projects/minimum-spanning-tree/c-sharp/index.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-29 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- minimum-spanning-tree -title: Minimum Spanning Tree in C# -title1: Minimum Spanning -title2: Tree in C# ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var input] || !TryParseMatrix(input.AsSpan(), out var matrix, out int n)) - return ExitWithUsage(); - -int weight = MinimumSpanningTreeWeight(matrix, n); -if (weight < 0) - return ExitWithUsage(); - -Console.WriteLine(weight); -return 0; - -static int MinimumSpanningTreeWeight(List matrix, int n) -{ - var inMst = new bool[n]; - var minEdge = new int[n]; - - Array.Fill(minEdge, int.MaxValue); - - minEdge[0] = 0; - - int total = 0; - - for (int added = 0; added < n; added++) - { - int bestWeight = int.MaxValue; - int u = -1; - - for (int i = 0; i < n; i++) - { - if (!inMst[i] && minEdge[i] < bestWeight) - { - bestWeight = minEdge[i]; - u = i; - } - } - - if (u < 0) - return -1; - - inMst[u] = true; - total += bestWeight; - - int row = u * n; - - for (int v = 0; v < n; v++) - { - int w = matrix[row + v]; - - if (w != 0 && !inMst[v] && w < minEdge[v]) - minEdge[v] = w; - } - } - - return total; -} - -static bool TryParseMatrix(ReadOnlySpan view, out List numbers, out int dimension) -{ - numbers = null!; - dimension = 0; - - if (view.IsWhiteSpace()) - return false; - - int expected = view.Count(',') + 1; - if (expected < 4) return false; - - var list = new List(expected); - - while (!view.IsEmpty) - { - int i = view.IndexOf(','); - var token = i >= 0 ? view[..i] : view; - - view = i >= 0 ? view[(i + 1)..] : []; - - if (!int.TryParse(token, out int v)) - return false; - - list.Add(v); - } - - int d = (int)Math.Sqrt(list.Count); - if (d * d != list.Count) - return false; - - numbers = list; - dimension = d; - return true; -} - -static int ExitWithUsage() -{ - Console.Error.WriteLine("""Usage: please provide a comma-separated list of integers"""); - return 1; -} - -``` - -{% endraw %} - -Minimum Spanning Tree in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/c/index.md b/docs/projects/minimum-spanning-tree/c/index.md deleted file mode 100644 index 8b271d0aa4..0000000000 --- a/docs/projects/minimum-spanning-tree/c/index.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -authors: -- Jeremy Grifski -- LezendarySandwich -- Ștefan-Iulian Alecu -date: 2019-10-20 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- minimum-spanning-tree -title: Minimum Spanning Tree in C -title1: Minimum Spanning -title2: Tree in C ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -struct Edge -{ - int src, dest; - long long weight; -}; - -long long get_val(int tmp[], int len) -{ - long long value = 0, mult = 1; - for (int i = len - 1; i > -1; --i) - { - if (tmp[i] == ' ' - '0') - { - printf("Usage: please provide a list of at least two integers to " - "sort in the format \"1, 2, 3, 4, 5\"\n"); - exit(0); - } - value += tmp[i] * mult; - mult *= 10; - } - return value; -} - -struct Graph -{ - int V, E; - struct Edge *edge; -}; - -struct Graph *createGraph(int V, int E) -{ - struct Graph *graph = malloc(sizeof(struct Graph)); - graph->V = V; - graph->E = E; - graph->edge = malloc(sizeof(struct Edge) * E); - return graph; -} - -struct subset -{ - int parent; - int rank; -}; - -int find(struct subset subsets[], int i) -{ - if (subsets[i].parent != i) - subsets[i].parent = find(subsets, subsets[i].parent); - return subsets[i].parent; -} - -void Union(struct subset subsets[], int x, int y) -{ - int xroot = find(subsets, x); - int yroot = find(subsets, y); - if (subsets[xroot].rank < subsets[yroot].rank) - subsets[xroot].parent = yroot; - else if (subsets[xroot].rank > subsets[yroot].rank) - subsets[yroot].parent = xroot; - else - { - subsets[yroot].parent = xroot; - subsets[xroot].rank++; - } -} - -int myComp(const void *a, const void *b) -{ - struct Edge *a1 = (struct Edge *)a; - struct Edge *b1 = (struct Edge *)b; - return a1->weight > b1->weight; -} - -void KruskalMST(struct Graph *graph) -{ - int V = graph->V; - long long res = 0; - int e = 0; - int i = 0; - qsort(graph->edge, graph->E, sizeof(graph->edge[0]), myComp); - - struct subset *subsets = (struct subset *)malloc(V * sizeof(struct subset)); - for (int v = 0; v < V; ++v) - { - subsets[v].parent = v; - subsets[v].rank = 0; - } - while (e < V - 1 && i < graph->E) - { - struct Edge next_edge = graph->edge[i++]; - int x = find(subsets, next_edge.src); - int y = find(subsets, next_edge.dest); - if (x != y) - { - res = res + next_edge.weight; - Union(subsets, x, y); - } - } - printf("%lld", res); - return; -} - -int floorSqrt(int x) -{ - if (x == 0 || x == 1) - return x; - int i = 1, result = 1; - while (result <= x) - { - i++; - result = i * i; - } - return i - 1; -} - -int main(int argc, char **argv) -{ - if (argv[1] == NULL || strlen(argv[1]) == 0) - { - printf("Usage: please provide a comma-separated list of integers"); - return 0; - } - - int len = strlen(argv[1]); - int tmp[20]; - int ind = 0; - int pos = 0; - long long arr[100000]; - int E = 0; - for (int i = 0; i < len; ++i) - { - if (argv[1][i] == ',') - { - long long val = get_val(tmp, ind); - ind = 0; - i++; - arr[pos++] = val; - if (val != 0) - E++; - continue; - } - tmp[ind++] = argv[1][i] - '0'; - } - arr[pos++] = get_val(tmp, ind); - int sq = floorSqrt(pos); - if (pos != sq * sq) - { - printf("Usage: please provide a comma-separated list of integers"); - return 0; - } - int V = sq; - - struct Graph *graph = createGraph(V, E); - int index = 0; - for (int i = 0; i < pos; ++i) - { - if (arr[i] == 0) - continue; - graph->edge[index].src = i / V; - graph->edge[index].dest = i - (i / V) * V; - graph->edge[index++].weight = arr[i]; - } - KruskalMST(graph); -} - -``` - -{% endraw %} - -Minimum Spanning Tree in [C](/languages/c) was written by: - -- Jeremy Grifski -- LezendarySandwich -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/cobol/index.md b/docs/projects/minimum-spanning-tree/cobol/index.md deleted file mode 100644 index f8141d09ad..0000000000 --- a/docs/projects/minimum-spanning-tree/cobol/index.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- minimum-spanning-tree -title: Minimum Spanning Tree in COBOL -title1: Minimum Spanning -title2: Tree in COBOL ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. minimum-spanning-tree. - -data division. -working-storage section. -01 input-str pic x(4000). - -01 matrix-area. - 05 matrix-row occurs 25 times - indexed by row-idx. - 10 adj-val occurs 25 times - indexed by col-idx - pic 9(9) comp-5. - -01 state. - 05 node-count pic 9(4) comp-5. - 05 total-elements pic 9(4) comp-5. - 05 mst-weight pic 9(15) comp-5 value 0. - 05 infinity pic 9(9) comp-5 value 999999999. - 05 current-token pic x(15). - -01 work-tables. - 05 visited-flg occurs 25 times - indexed by v-idx - pic x value 'n'. - 88 is-visited value 'y'. - 88 is-not-visited value 'n'. - 05 min-dist occurs 25 times - indexed by d-idx - pic 9(9) comp-5. - -01 counters. - 05 u pic 9(4) comp-5. - 05 v pic 9(4) comp-5. - 05 ptr pic 9(4) comp-5. - 05 min-val pic 9(9) comp-5. - -01 display-area. - 05 result-out pic z(14)9. - -procedure division. -main. - accept input-str from argument-value - if input-str = spaces perform show-usage end-if - - perform parse-and-validate - perform find-mst - - move mst-weight to result-out - display function trim(result-out) - stop run. - -parse-and-validate. - move 0 to total-elements - inspect function trim(input-str) tallying total-elements for all "," - add 1 to total-elements - - compute node-count = function integer(function sqrt(total-elements)) - if (node-count * node-count not = total-elements) - or total-elements > 625 - perform show-usage - end-if - - move 1 to ptr - perform varying row-idx from 1 by 1 until row-idx > node-count - perform varying col-idx from 1 by 1 until col-idx > node-count - unstring input-str delimited by "," - into current-token - pointer ptr - compute adj-val(row-idx, col-idx) = function numval(current-token) - end-perform - end-perform. - -find-mst. - perform varying d-idx from 1 by 1 until d-idx > node-count - move infinity to min-dist(d-idx) - set is-not-visited(d-idx) to true - end-perform - - move 0 to min-dist(1) - - perform node-count times - move infinity to min-val - move 0 to u - - perform varying v-idx from 1 by 1 until v-idx > node-count - if is-not-visited(v-idx) and min-dist(v-idx) < min-val - move min-dist(v-idx) to min-val - set v to v-idx - move v to u - end-if - end-perform - - if u = 0 exit perform end-if - - set is-visited(u) to true - add min-dist(u) to mst-weight - - perform varying v from 1 by 1 until v > node-count - if is-not-visited(v) - and adj-val(u, v) > 0 - and adj-val(u, v) < min-dist(v) - move adj-val(u, v) to min-dist(v) - end-if - end-perform - end-perform. - -show-usage. - display "Usage: please provide a comma-separated list of integers" - stop run. - -``` - -{% endraw %} - -Minimum Spanning Tree in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/commodore-basic/index.md b/docs/projects/minimum-spanning-tree/commodore-basic/index.md deleted file mode 100644 index 49ac4ad744..0000000000 --- a/docs/projects/minimum-spanning-tree/commodore-basic/index.md +++ /dev/null @@ -1,222 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-23 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2023-10-23 -layout: default -tags: -- commodore-basic -- minimum-spanning-tree -title: Minimum Spanning Tree in Commodore BASIC -title1: Minimum Spanning Tree -title2: in Commodore BASIC ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -15 REM Graph: -16 REM - G%(i, j, 0) contains vertex index for child node j, vertex i or -17 REM negative to indicate no more child nodes -18 REM - G%(i, j, 1) contains weight between vertex i and child node j -20 DIM G%(9, 10, 1) -25 REM Minimum spanning tree working values -30 DIM MP%(9): REM Parents -40 DIM MK(9): REM Keys -50 DIM MS%(9): REM Set -55 REM Minimum spanning tree output -56 REM - MT(i, 0) contains source vertex index for node i -57 REM - MT(i, 1) contains destination vertex index for node i -58 REM - MT(i, 2) contains weight between source and destination for node i -60 DIM MT%(8, 2) -65 REM Get weights -70 GOSUB 2000 -80 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -85 REM Get number of vertices -90 NV = INT(SQR(NA) + 0.5) -100 IF NA <> (NV * NV) THEN GOTO 200: REM non-square input -105 REM Form graph -110 GOSUB 2500 -115 REM Perform minimum spanning tree, calculate total weight, and display -120 GOSUB 3000 -130 GOSUB 3500 -140 S$ = MID$(STR$(TW), 2) -150 PRINT S$ -160 END -200 PRINT "Usage: please provide a comma-separated list of integers" -210 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -2500 REM Form graph -2501 REM Inputs: -2502 REM - A contains weights -2504 REM - NV contains number of vertices -2505 REM Output: G% contains graph -2510 K = -1 -2520 FOR I = 0 TO NV - 1 -2530 N = -1 -2540 FOR J = 0 TO NV - 1 -2550 K = K + 1 -2560 IF A(K) <= 0 THEN GOTO 2600 -2570 N = N + 1 -2580 G%(I, N, 0) = J -2590 G%(I, N, 1) = A(K) -2600 NEXT J -2610 G%(I, N + 1, 0) = -1: REM End of child nodes -2620 G%(I, N + 1, 1) = 0 -2630 NEXT I -2640 RETURN -3000 REM Prim's Minimum Spanning Tree (MST) Algorithm based on C -3001 REM implementation of https://www.geeksforgeeks.org/ -3002 REM prims-minimum-spanning-tree-mst-greedy-algo-5/ -3003 REM Inputs: -3004 REM - G% contains graph -3005 REM - NV contains number of vertices -3006 REM Outputs: -3007 REM - MT contains minimum spanning tree -3008 REM - NM contains size of minimum spanning tree -3010 REM Initialize -3020 FOR I = 0 TO NV - 1 -3030 MP%(I) = -1: REM No parents yet -3040 MK(I) = 1.70141183E38: REM Minimum weight edge is infinty -3050 MS%(I) = 0: REM Nothing in MST yet -3060 NEXT I -3065 REM Include first vertex in MST -3070 MK(0) = 0 -3075 REM The MST will include all vertices -3080 FOR I = 1 TO NV - 1 -3085 REM Pick index of the minimum key value not already in MST -3090 MV = 1.70141183E38: REM Minimum value is infinity -3100 U = -1 -3110 FOR J = 0 TO NV - 1 -3120 IF MK(J) >= MV OR MS%(J) <> 0 THEN GOTO 3150 -3130 MV = MK(J) -3140 U = J -3150 NEXT J -3155 REM Add picked vertex to MST -3160 MS%(U) = 1 -3165 REM Update key values and parent indices of picked adjacent vertices. -3166 REM Only consider vertices not yet in MST -3170 J = -1 -3180 J = J + 1 -3190 V = G%(U, J, 0) -3200 W = G%(U, J, 1) -3210 IF V < 0 THEN GOTO 3260 -3220 IF MS%(V) <> 0 OR W >= MK(V) THEN GOTO 3180 -3230 MP%(V) = U -3240 MK(V) = W -3250 GOTO 3180 -3260 NEXT I -3265 REM Construct MST information to return, skipping over root -3270 NM = NV - 1 -3280 FOR I = 1 TO NM -3290 MT(I - 1, 0) = MP%(I) -3300 MT(I - 1, 1) = I -3310 MT(I - 1, 2) = MK(I) -3320 NEXT I -3330 RETURN -3500 REM Calculate total weight of MST -3501 REM Inputs: -3502 REM - MT contains minimum spanning tree -3503 REM - NM contains size of minimum spanning tree -3504 REM Output: TW contains total weight -3510 TW = 0 -3520 FOR I = 0 TO NM - 1 -3530 TW = TW + MT(I, 2) -3540 NEXT I -3550 RETURN - -``` - -{% endraw %} - -Minimum Spanning Tree in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/euphoria/index.md b/docs/projects/minimum-spanning-tree/euphoria/index.md deleted file mode 100644 index 51e056125b..0000000000 --- a/docs/projects/minimum-spanning-tree/euphoria/index.md +++ /dev/null @@ -1,251 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-27 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2023-02-27 -layout: default -tags: -- euphoria -- minimum-spanning-tree -title: Minimum Spanning Tree in Euphoria -title1: Minimum Spanning -title2: Tree in Euphoria ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e -include std/utils.e -include std/math.e -include std/mathcons.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts(STDOUT, "Usage: please provide a comma-separated list of integers\n") - abort(0) -end procedure - --- Indices for node values -enum NODE_INDEX, NODE_WEIGHT - --- Create graph from weights. --- The graph consists of a sequence of nodes. --- Each node consists of a weight and sequence of neighbor indices -function create_graph(sequence weights, integer num_vertices) - -- Initialize nodes - sequence nodes = repeat({}, num_vertices) - - -- Get neighbors for this node based on weights - integer num_weights = length(weights) - integer index = 0 - for row = 1 to num_vertices - do - -- Add neighbor node indices and weights to this node - for col = 1 to num_vertices - do - index += 1 - if weights[index] > 0 - then - nodes[row] &= {{col, weights[index]}} - end if - end for - end for - - return nodes -end function - --- Indices for Minimum Spanning Tree -enum MST_VERTEX1, MST_VERTEX2, MST_WEIGHT - --- Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of --- https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ -function prim_mst(sequence graph) - integer num_vertices = length(graph) - - -- Array to store constructed MST. Indicate no parents yet - sequence parents = repeat(0, num_vertices) - - -- Key values used to pick minimum weight edge. Initialize to infinity - sequence keys = repeat(PINF, num_vertices) - - -- Array used to indicate if vertex is in MST. Indicate nothing in MST yet - sequence mst_set = repeat(FALSE, num_vertices) - - -- Include first vertex in MST - keys[1] = 1 - - -- The MST will include all vertices - for i = 1 to num_vertices - 1 - do - -- Pick index of the minimum key value not already in MST - integer u = find_min_key(keys, mst_set) - - -- Add picked vertex to MST set - mst_set[u] = TRUE - - -- Update key values and parent indices of picked adjacent - -- vertices. Only consider vertices not yet in MST - for j = 1 to length(graph[u]) - do - integer v = graph[u][j][NODE_INDEX] - integer graph_value = graph[u][j][NODE_WEIGHT] - if not mst_set[v] and graph_value < keys[v] - then - parents[v] = u - keys[v] = graph_value - end if - end for - end for - - -- Construct MST information to return - sequence mst = {} - - -- Skip over root and adjust vertex numbers to account for 1-based indexing - for k = 2 to num_vertices - do - mst &= {{parents[k] - 1, k - 1, keys[k]}} - end for - - return mst -end function - --- Find vertex with minimum key values not already in MST -function find_min_key(sequence keys, sequence mst_set) - atom min_value = PINF - integer min_index - for v = 1 to length(keys) - do - if keys[v] < min_value and not mst_set[v] - then - min_value = keys[v] - min_index = v - end if - end for - - return min_index -end function - --- Get total MST weight -function get_total_mst_weight(sequence mst) - return sum(vslice(mst, MST_WEIGHT)) -end function - --- Check command-line arguments -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument and make sure number of values is a square -sequence list_result = parse_int_list(argv[4]) -sequence weights = list_result[PARSE_INT_LIST_VALUES] -integer num_weights = length(weights) -integer sqrt_num_weights = round(sqrt(num_weights)) -if ( - not list_result[PARSE_INT_LIST_VALID] - or num_weights != sqrt_num_weights * sqrt_num_weights -) -then - usage() -end if - --- Create graph from weights -sequence graph = create_graph(weights, sqrt_num_weights) - --- Get MST using Prim's algorithm -sequence mst = prim_mst(graph) - --- Calculate total weight of MST and display -integer total_weight = get_total_mst_weight(mst) -printf(STDOUT, "%d\n", total_weight) - -``` - -{% endraw %} - -Minimum Spanning Tree in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/f-sharp/index.md b/docs/projects/minimum-spanning-tree/f-sharp/index.md deleted file mode 100644 index dca32fc99d..0000000000 --- a/docs/projects/minimum-spanning-tree/f-sharp/index.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- minimum-spanning-tree -title: Minimum Spanning Tree in F# -title1: Minimum Spanning -title2: Tree in F# ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module DSU = - type t = { parent: int[]; rank: int[] } - - let create n = - { parent = Array.init n id - rank = Array.zeroCreate n } - - let find (dsu: t) x = - let mutable i = x - - while dsu.parent.[i] <> i do - dsu.parent.[i] <- dsu.parent.[dsu.parent.[i]] - i <- dsu.parent.[i] - - i - - let union (dsu: t) x y = - let rx = find dsu x - let ry = find dsu y - - if rx = ry then - false - else - match compare dsu.rank.[rx] dsu.rank.[ry] with - | -1 -> - dsu.parent.[rx] <- ry - true - | 1 -> - dsu.parent.[ry] <- rx - true - | _ -> - dsu.parent.[ry] <- rx - dsu.rank.[rx] <- dsu.rank.[rx] + 1 - true - - -module MST = - type t = { u: int; v: int; w: int } - - let edgesFromMatrix n (values: int[]) = - seq { - for i in 0 .. n - 1 do - let baseRow = i * n - - for j in i + 1 .. n - 1 do - let w = values.[baseRow + j] - - if w <> 0 then - { u = i; v = j; w = w } - } - - let kruskal (n: int) (edges: seq) = - let dsu = DSU.create n - - edges - |> Seq.sortBy (fun e -> e.w) - |> Seq.fold - (fun (cost, used) e -> - if used = n - 1 then cost, used - elif DSU.union dsu e.u e.v then cost + e.w, used + 1 - else cost, used) - (0, 0) - |> fst - - - let run (values: int[]) (n: int) = - values |> edgesFromMatrix n |> kruskal n - -module Helpers = - let usage = "Usage: please provide a comma-separated list of integers" - - let (|IntList|_|) (s: string) = - let parsed = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) - |> Array.choose (fun x -> - match Int32.TryParse(x.Trim()) with - | true, v -> Some v - | _ -> None) - - if parsed.Length = 0 then None else Some parsed - - let trySquare (values: int[]) = - let n = values.Length - let r = int (sqrt (float n)) - if r * r = n then Some(values, r) else None - - let parseArgs = - function - | [| IntList values |] -> - match trySquare values with - | Some v -> Ok v - | None -> Error usage - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%d" result - 0 - | Error msg -> - printfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map (fun (v, n) -> MST.run v n) - |> Helpers.handleResult - -``` - -{% endraw %} - -Minimum Spanning Tree in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/go/index.md b/docs/projects/minimum-spanning-tree/go/index.md deleted file mode 100644 index 4c458b5703..0000000000 --- a/docs/projects/minimum-spanning-tree/go/index.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- go -- minimum-spanning-tree -title: Minimum Spanning Tree in Go -title1: Minimum Spanning -title2: Tree in Go ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "math" - "os" - "strconv" - "strings" -) - -const usage = `Usage: please provide a comma-separated list of integers` - -func main() { - if len(os.Args) != 2 { - printUsage() - } - - matrix, errM := parseList(os.Args[1]) - - if errM != nil { - printUsage() - } - - nFloat := math.Sqrt(float64(len(matrix))) - n := int(nFloat) - if nFloat != float64(n) || n == 0 { - printUsage() - } - - cost, ok := primMST(matrix, n) - if !ok { - printUsage() - } - - fmt.Println(cost) -} - -func primMST(matrix []int, n int) (int, bool) { - if n == 0 { - return 0, true - } - - inMST := make([]bool, n) - minWeights := make([]int, n) - for i := range minWeights { - minWeights[i] = math.MaxInt32 - } - - minWeights[0] = 0 - totalWeight := 0 - nodesInTree := 0 - - for i := 0; i < n; i++ { - u := -1 - minVal := math.MaxInt32 - - for v := 0; v < n; v++ { - if !inMST[v] && minWeights[v] < minVal { - minVal = minWeights[v] - u = v - } - } - - if u == -1 { - break - } - - inMST[u] = true - totalWeight += minVal - nodesInTree++ - - for v := 0; v < n; v++ { - weight := matrix[u*n+v] - if weight > 0 && !inMST[v] && weight < minWeights[v] { - minWeights[v] = weight - } - } - } - - if nodesInTree != n { - return 0, false - } - - return totalWeight, true -} - -func parseList(input string) ([]int, error) { - if strings.TrimSpace(input) == "" { - return nil, fmt.Errorf("empty input") - } - - parts := strings.Split(input, ",") - nums := make([]int, 0, len(parts)) - for _, p := range parts { - val, err := strconv.Atoi(strings.TrimSpace(p)) - if err != nil { - return nil, err - } - nums = append(nums, val) - } - return nums, nil -} - -func printUsage() { - fmt.Println(usage) - os.Exit(1) -} -``` - -{% endraw %} - -Minimum Spanning Tree in [Go](/languages/go) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/haskell/index.md b/docs/projects/minimum-spanning-tree/haskell/index.md deleted file mode 100644 index 24a31a0487..0000000000 --- a/docs/projects/minimum-spanning-tree/haskell/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-18 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-18 -layout: default -tags: -- haskell -- minimum-spanning-tree -title: Minimum Spanning Tree in Haskell -title1: Minimum Spanning -title2: Tree in Haskell ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Data.Array (Array, (!)) -import qualified Data.Array as Array -import Text.Read (readMaybe) -import Control.Monad (guard) -import Data.IntSet (IntSet) -import qualified Data.IntSet as IS -import Data.Set (Set) -import qualified Data.Set as Set -import System.Environment - -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - -chunksOf :: Int -> [Int] -> [[Int]] -chunksOf _ [] = [] -chunksOf n l = let (row, xs) = splitAt n l in row : chunksOf n xs - -buildAdjacencyMatrix :: [Int] -> Array Int [Int] -buildAdjacencyMatrix l = Array.listArray (0, n-1) (chunksOf n l) - where - n = round (sqrt (fromIntegral (length l))) -- size of a row in a square matrix - -prim :: Array Int [Int] -> Int -prim adj = go IS.empty (Set.singleton (0, 0)) - where - go vis pq - | Set.null pq = 0 - | otherwise = - let ((weight, v), pq') = Set.deleteFindMin pq - in if IS.member v vis - then go vis pq' - else - let pq'' = foldr Set.insert pq' (unvisitedEdges v vis) - in weight + go (IS.insert v vis) pq'' - unvisitedEdges v vis = - [ (weight, u) - | (weight, u) <- zip (adj ! v) [0..] - , weight /= 0, u `IS.notMember` vis - ] - -parseArgs :: [String] -> Maybe [Int] -parseArgs [l] = do - l <- stringToListMaybe l - guard $ (not . null) l && isSquare (length l) - return l - where isSquare n = (round $ sqrt $ fromIntegral n) ^ 2 == n -parseArgs _ = Nothing - -main :: IO () -main = do - args <- getArgs - case parseArgs args of - Nothing -> putStrLn "Usage: please provide a comma-separated list of integers" - Just l -> print $ prim (buildAdjacencyMatrix l) - -``` - -{% endraw %} - -Minimum Spanning Tree in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/index.md b/docs/projects/minimum-spanning-tree/index.md deleted file mode 100644 index 6e99e1bc1b..0000000000 --- a/docs/projects/minimum-spanning-tree/index.md +++ /dev/null @@ -1,168 +0,0 @@ ---- -date: 2019-10-14 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-18 -layout: default -tags: -- minimum-spanning-tree -title: Minimum Spanning Tree -title1: Minimum -title2: Spanning Tree ---- - - - -Welcome to the Minimum Spanning Tree page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -## Description - -A minimum spanning tree is defined as the minimum set of edges needed to connect -every node in a graph without cycles. For our purposes, we're concerned with -weighted undirected graphs. In other words, we want to find the minimum cost -spanning tree. - -For example, let's say we have the following graph: - -![Initial Graph](https://www.simplilearn.com/ice9/free_resources_article_thumb/Prim%27s_Algorithm/Graph_G_for_Constructing_MST.png) - -Then, a possible minimum spanning tree would have the lowest total weight -while also connected all nodes without cycles. Such as: - -![Final Graph](https://www.simplilearn.com/ice9/free_resources_article_thumb/Prim%27s_Algorithm/Final_MST.png) - -Naturally, there are a few ways to solve this problem, but the two most famous -are Prim's algorithm and Kruskal's algorithm. Check those out before implementing -this solution. - - -## Requirements - -To implement this algorithm, your program should accept a square matrix of -strings in the following format: - -```console -./minimum-spanning-tree "0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0" -``` - -Here we've chosen to represent the matrix as a serialized list of integers. Since -the input string represents a square matrix, we should be able to take the -square root of the length to determine where the rows are in the string. In this -case, we have 25 values, so we must have 5 nodes. - -If we reformat the input string as a matrix, we'll notice that the values in the -matrix represent the edge weight between each node. For example, we -could reformat our example to look something like the following: - -| Mapping | 0 | 1 | 2 | 3 | 4 | -| ------- | --- | --- | --- | --- | --- | -| 0 | 0 | 2 | 0 | 6 | 0 | -| 1 | 2 | 0 | 3 | 8 | 5 | -| 2 | 0 | 3 | 0 | 0 | 7 | -| 3 | 6 | 8 | 0 | 0 | 9 | -| 4 | 0 | 5 | 7 | 9 | 0 | - -Here, we can see that there is no edge between node 0 and node 2. Meanwhile, -node 0 has an edge to node 3 with a weight of 6. - -If we continue to look at this table, we'll notice that all the edges are mirrored -across the top to bottom diagonal. In other words, the weight from node 0 to node -1 is the same as the weight from node 1 to node 0. We can use this property to -differentiate between directed and undirected graphs. - -For simplicity, the output sequence should print the minimum weight of the tree. -In other words, what is the cost of the minimum spanning tree? - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Minimum Spanning Tree. -In order to keep things simple, we split up the testing as follows: - -- Minimum Spanning Tree Valid Tests -- Minimum Spanning Tree Invalid Tests - -### Minimum Spanning Tree Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: Routine | "0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0" | "16" | - -### Minimum Spanning Tree Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Non-Square Input | "1, 0, 3, 0, 5, 1" | - -All of these tests should output the following: - -``` -Usage: please provide a comma-separated list of integers -``` - - -## Articles - -There are 27 articles: - -- [Minimum Spanning Tree in ALGOL 60](/projects/minimum-spanning-tree/algol60) -- [Minimum Spanning Tree in ALGOL 68](/projects/minimum-spanning-tree/algol68) -- [Minimum Spanning Tree in AWK](/projects/minimum-spanning-tree/awk) -- [Minimum Spanning Tree in Beef](/projects/minimum-spanning-tree/beef) -- [Minimum Spanning Tree in C](/projects/minimum-spanning-tree/c) -- [Minimum Spanning Tree in C#](/projects/minimum-spanning-tree/c-sharp) -- [Minimum Spanning Tree in C++](/projects/minimum-spanning-tree/c-plus-plus) -- [Minimum Spanning Tree in COBOL](/projects/minimum-spanning-tree/cobol) -- [Minimum Spanning Tree in Commodore BASIC](/projects/minimum-spanning-tree/commodore-basic) -- [Minimum Spanning Tree in Euphoria](/projects/minimum-spanning-tree/euphoria) -- [Minimum Spanning Tree in F#](/projects/minimum-spanning-tree/f-sharp) -- [Minimum Spanning Tree in Go](/projects/minimum-spanning-tree/go) -- [Minimum Spanning Tree in Haskell](/projects/minimum-spanning-tree/haskell) -- [Minimum Spanning Tree in Java](/projects/minimum-spanning-tree/java) -- [Minimum Spanning Tree in JavaScript](/projects/minimum-spanning-tree/javascript) -- [Minimum Spanning Tree in Mathematica](/projects/minimum-spanning-tree/mathematica) -- [Minimum Spanning Tree in PHP](/projects/minimum-spanning-tree/php) -- [Minimum Spanning Tree in Pascal](/projects/minimum-spanning-tree/pascal) -- [Minimum Spanning Tree in PowerShell](/projects/minimum-spanning-tree/powershell) -- [Minimum Spanning Tree in Python](/projects/minimum-spanning-tree/python) -- [Minimum Spanning Tree in Ruby](/projects/minimum-spanning-tree/ruby) -- [Minimum Spanning Tree in Rust](/projects/minimum-spanning-tree/rust) -- [Minimum Spanning Tree in Swift](/projects/minimum-spanning-tree/swift) -- [Minimum Spanning Tree in Tcl](/projects/minimum-spanning-tree/tcl) -- [Minimum Spanning Tree in TypeScript](/projects/minimum-spanning-tree/typescript) -- [Minimum Spanning Tree in Visual Basic](/projects/minimum-spanning-tree/visual-basic) -- [Minimum Spanning Tree in m4](/projects/minimum-spanning-tree/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/java/index.md b/docs/projects/minimum-spanning-tree/java/index.md deleted file mode 100644 index b1ed5a87be..0000000000 --- a/docs/projects/minimum-spanning-tree/java/index.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- java -- minimum-spanning-tree -title: Minimum Spanning Tree in Java -title1: Minimum Spanning -title2: Tree in Java ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.Arrays; - -public class MinimumSpanningTree { - - public static void main(String[] args) { - int[] matrix = parse(args); - - int size = (int) Math.sqrt(matrix.length); - long result = minimumSpanningTree(matrix, size); - - System.out.println(result); - } - - private static void usage() { - System.err.println("Usage: please provide a comma-separated list of integers"); - System.exit(1); - } - - private static int[] parse(String[] args) { - if (args.length != 1 || args[0] == null || args[0].isBlank()) { - usage(); - } - - String[] tokens = args[0].split(","); - int[] values = new int[tokens.length]; - - for (int i = 0; i < tokens.length; i++) { - String token = tokens[i].trim(); - if (token.isEmpty()) { - usage(); - } - - try { - values[i] = Integer.parseInt(token); - } catch (NumberFormatException e) { - usage(); - } - } - - int n = (int) Math.sqrt(values.length); - if (n * n != values.length) { - usage(); - } - - return values; - } - - private static long minimumSpanningTree(int[] graph, int size) { - boolean[] inMst = new boolean[size]; - long[] minEdgeWeight = new long[size]; - - Arrays.fill(minEdgeWeight, Long.MAX_VALUE); - minEdgeWeight[0] = 0; - - long totalWeight = 0; - - for (int i = 0; i < size; i++) { - int selectedNode = -1; - long bestWeight = Long.MAX_VALUE; - - for (int v = 0; v < size; v++) { - if (inMst[v] || minEdgeWeight[v] >= bestWeight) { - continue; - } - - bestWeight = minEdgeWeight[v]; - selectedNode = v; - } - - if (selectedNode == -1 || bestWeight == Long.MAX_VALUE) { - usage(); - } - - inMst[selectedNode] = true; - totalWeight += bestWeight; - - int rowStart = selectedNode * size; - - for (int v = 0; v < size; v++) { - int edgeWeight = graph[rowStart + v]; - - if (inMst[v] || edgeWeight <= 0 || edgeWeight >= minEdgeWeight[v]) { - continue; - } - - minEdgeWeight[v] = edgeWeight; - } - } - - return totalWeight; - } -} - -``` - -{% endraw %} - -Minimum Spanning Tree in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/javascript/index.md b/docs/projects/minimum-spanning-tree/javascript/index.md deleted file mode 100644 index d1eac33d5b..0000000000 --- a/docs/projects/minimum-spanning-tree/javascript/index.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- javascript -- minimum-spanning-tree -title: Minimum Spanning Tree in JavaScript -title1: Minimum Spanning -title2: Tree in JavaScript ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -"use strict"; - -const USAGE = "Usage: please provide a comma-separated list of integers"; - -const solveMST = (flat, size) => { - const keys = new Array(size).fill(Infinity); - const inMST = new Uint8Array(size); - - keys[0] = 0; - - for (let count = 0; count < size; count++) { - let u = -1; - - for (let v = 0; v < size; v++) { - if (!inMST[v] && (u === -1 || keys[v] < keys[u])) { - u = v; - } - } - - if (u === -1 || keys[u] === Infinity) break; - - inMST[u] = 1; - - const rowOffset = u * size; - for (let v = 0; v < size; v++) { - const weight = flat[rowOffset + v]; - if (weight > 0 && !inMST[v] && weight < keys[v]) { - keys[v] = weight; - } - } - } - - return keys.reduce((sum, w) => (w === Infinity ? sum : sum + w), 0); -}; - -const run = () => { - const [, , input] = process.argv; - - if (!input) { - console.error(USAGE); - process.exit(1); - } - - try { - const flat = input - .split(",") - .filter((x) => x.trim() !== "") - .map((x) => { - const val = Number(x); - if (!Number.isInteger(val)) throw new Error(); - return val; - }); - - const size = Math.sqrt(flat.length); - - if (flat.length === 0 || !Number.isInteger(size)) { - throw new Error(); - } - - const result = solveMST(flat, size); - console.log(result); - } catch { - console.error(USAGE); - process.exit(1); - } -}; - -run(); - -``` - -{% endraw %} - -Minimum Spanning Tree in [JavaScript](/languages/javascript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/m4/index.md b/docs/projects/minimum-spanning-tree/m4/index.md deleted file mode 100644 index dfb43a16a5..0000000000 --- a/docs/projects/minimum-spanning-tree/m4/index.md +++ /dev/null @@ -1,317 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-11-14 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2025-11-14 -layout: default -tags: -- m4 -- minimum-spanning-tree -title: Minimum Spanning Tree in m4 -title1: Minimum Spanning -title2: Tree in m4 ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a comma-separated list of integers -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(varname, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(varname, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl 2D versions of "array_get" and "array_set" -dnl array2_get(varname, idx1, idx2) -define(`array2_get', `defn(format(``%s[%s][%s]'', `$1', `$2', `$3'))') - -dnl array2_set(varname, idx1, idx2, value) -define(`array2_set', `define(format(``%s[%s][%s]'', `$1', `$2', `$3'), `$4')') - -dnl 3D versions of "array_get" and "array_set" -dnl array3_get(varname, idx1, idx2, idx3) -define(`array3_get', `defn(format(``%s[%s][%s][%s]'', `$1', `$2', `$3', `$4'))') - -dnl array3_set(varname, idx1, idx2, idx3, value) -define(`array3_set', `define(format(``%s[%s][%s][%s]'', `$1', `$2', `$3', `$4'), `$5')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname["length"] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname["length"]] = arg -dnl varname["length"] = varname["length"] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl Reference: https://en.wikipedia.org/wiki/Integer_square_root#Algorithm_using_Newton's_method -dnl isqrt(n): -dnl if n < 2: -dnl return n -dnl prev2 = -1 -dnl prev1 = 1 -dnl while 1: -dnl x1 = (prev1 + n // prev1) // 2 -dnl -dnl // Case 1: converged (steady value) -dnl if x1 == prev1: -dnl return x1 -dnl -dnl // Case 2: oscillation (2-cycle) -dnl if x1 == prev2 and x1 != prev1: -dnl return min(prev1, x1) -dnl -dnl // Set up next values -dnl prev2, prev1 = prev1, x1 -define(`isqrt', `ifelse(eval($1 < 2), 1, $1, -`pushdef(`x1', 0)dnl -_isqrt($1, -1, 1)dnl -popdef(`x1')dnl -'dnl -)'dnl -) - -dnl n=$1, prev2=$2, prev1=$3 -define(`_isqrt', -`define(`x1', eval(($3 + $1 / $3) >> 1))dnl -ifelse(eval(x1 == $3), 1, x1, -`ifelse(eval(x1 == $2 && x1 != $3), 1, `min(`$3', x1)', `_isqrt(`$1', `$3', x1)')'dnl -)'dnl -) - -dnl min(a, b) -define(`min', `ifelse(eval($1 < $2), 1, $1, $2)') - -dnl create_graph(weights_varname, num_vertices, graph_varname): -dnl // Create nodes -dnl graph_varname["length"] = num_vertices -dnl for i = 0 to num_vertices - 1: -dnl graph_varname[i]["length"] = 0 -dnl -dnl // Connect children to nodes -dnl idx = 0 -dnl for i = 0 to num_vertices - 1: -dnl for j = 0 to num_vertices - 1: -dnl if weight_mtx_varname[idx] > 0: -dnl graph_varname[i]["edge"][graph_varname[i]["length"]] = j -dnl graph_varname[i]["weight"][graph_varname[i]["length"]] = weights_varname[idx] -dnl graph_varname[i]["length"] = graph_varname[i]["length"] + 1 -dnl -dnl idx = idx + 1 -define(`create_graph', -`array_set(`$3', `length', `$2')dnl -_create_nodes(`$3', `$2', 0)dnl -_connect_children(`$1', `$2', `$3', 0, 0)dnl -'dnl -) - -dnl graph_varname=$1, num_vertices=$2, i=$3 -define(`_create_nodes', -`ifelse(eval($3 < $2), 1, -`array2_set(`$1', `$3', `length', 0)dnl -_create_nodes(`$1', `$2', incr($3))'dnl -)'dnl -) - -dnl weights_varname=$1, num_vertices=$2, graph_varname=$3, i=$4, idx=$5 -define(`_connect_children', -`ifelse(eval($4 < $2), 1, -`_connect_children_inner(`$1', `$2', `$3', `$4', `$5', 0)dnl -_connect_children(`$1', `$2', `$3', incr($4), eval($5 + $2))'dnl -)'dnl -) - -dnl weights_varname=$1, num_vertices=$2, graph_varname=$3, i=$4, idx=$5, j=$6 -define(`_connect_children_inner', -`ifelse(eval($6 < $2), 1, -`ifelse(eval(array_get(`$1', `$5') > 0), 1, -`array3_set(`$3', `$4', `edge', array2_get(`$3', `$4', `length'), `$6')dnl -array3_set(`$3', `$4', `weight', array2_get(`$3', `$4', `length'), array_get(`$1', $5))dnl -array2_set(`$3', `$4', `length', incr(array2_get(`$3', `$4', `length')))'dnl -)dnl -_connect_children_inner(`$1', `$2', `$3', `$4', incr($5), incr($6))'dnl -)'dnl -) - -dnl M4 does not have infinity so choose largest integer value as infinity -define(`INF', 2147483647) - -dnl Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of -dnl https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ -dnl prim_mst(graph_varname, mst_varname): -dnl // Note: mst_set is a string that looks like this: "||||..." -dnl // Since M4 does not have anything like a set, this is the easiest way to -dnl // represent it, and the "index" function can be used to see if a node is -dnl // in the MST (non-negative if so) -dnl -dnl // Indicate nothing in MST, and initialize key values to infinite -dnl mst_set = "" -dnl mst_varname["length"] = graph_varname["length"] -dnl for i = 0 to mst_varname["length"] - 1: -dnl mst_varname[i]["key"] = INF -dnl -dnl // Include first vertex in MST -dnl mst_varname[0]["key"] = 0 -dnl mst_varname[0]["parent"] = -1 // Root has no parent -dnl -dnl // For each vertex -dnl for i = 1 to mst_varname["length"] - 1 -dnl // Pick index of the minimum key value not already in MST -dnl u = find_min_key(mst_varname) -dnl -dnl // Add picked vertex to MST set -dnl mst_set = mst_set + "|" + u + "|" -dnl -dnl // Update key values and parent indices of picked adjacent -dnl // vertices. Only consider vertices not yet in MST set -dnl for j = 0 to graph[u]["length"] - 1: -dnl v = graph[u]["edge"][j] -dnl w = graph[u]["weight"][j] -dnl if ("|" + v + "|") not in mst_set and w < mst_varname[v]["key"]: -dnl mst_varname[v]["parent"] = u -dnl mst_varname[v]["key"] = w -define(`prim_mst', -`pushdef(`u', `')dnl -pushdef(`v', `')dnl -pushdef(`w', `')dnl -pushdef(`mst_set', `')dnl -array_set(`$2', `length', array_get(`$1', `length'))dnl -_init_mst(`$2', 0)dnl -array2_set(`$2', 0, `key', 0)dnl -array2_set(`$2', 0, `parent', -1)dnl -_prim_mst_outer(`$1', `$2', 1)dnl -popdef(`mst_set')dnl -popdef(`w')dnl -popdef(`v')dnl -popdef(`u')dnl -'dnl -) - -dnl mst_varname=$1, i=$2 -define(`_init_mst', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`array2_set(`$1', `$2', `key', INF)dnl -_init_mst(`$1', incr($2))'dnl -)'dnl -) - -dnl graph_varname=$1, mst_varname=$2, i=$3 -define(`_prim_mst_outer', -`ifelse(eval($3 < array_get(`$2', `length')), 1, -`define(`u', find_min_key(`$2'))dnl -define(`mst_set', mst_set`|'u`|')dnl -_prim_mst_inner(`$1', `$2', 0)dnl -_prim_mst_outer(`$1', `$2', incr($3))dnl -'dnl -)'dnl -) - -dnl graph_varname=$1, mst_varname=$2, j=$3 -define(`_prim_mst_inner', -`ifelse(eval($3 < array2_get(`$1', u, `length')), 1, -`define(`v', array3_get(`$1', u, `edge', `$3'))dnl -define(`w', array3_get(`$1', u, `weight', `$3'))dnl -ifelse(eval(index(mst_set, `|'v`|') < 0 && w < array2_get(`$2', v, `key')), 1, -`array2_set(`$2', v, `parent', u)dnl -array2_set(`$2', v, `key', w)dnl -')dnl -_prim_mst_inner(`$1', `$2', incr($3))dnl -'dnl -)'dnl -) - -dnl find_min_key(mst_varname): -dnl min_key = INF -dnl min_index = -1 -dnl for i = 0 to mst_varname["length"] - 1: -dnl if ("|" + i + "|") not in mst_set and mst_varname[i]["key"] < min_dist: -dnl min_key = mst_varname[i]["key"] -dnl min_index = i -dnl return min_index -define(`find_min_key', `_find_min_key(`$1', INF, -1, 0)') - -dnl mst_varname=$1, min_key=$2, min_index=$3, i=$4 -define(`_find_min_key', -`ifelse(eval($4 >= array_get(`$1', `length')), 1, `$3', -`ifelse(eval(index(mst_set, `|$4|') < 0 && array2_get(`$1', `$4', `key') < $2), 1, -`_find_min_key(`$1', array2_get(`$1', `$4', `key'), `$4', incr($4))', -`_find_min_key(`$1', `$2', `$3', incr($4))'dnl -)'dnl -)'dnl -) - -dnl get_total_mst_weight(mst_varname): -dnl total = 0 -dnl for i = 1 to mst_varname["length"] - 1: -dnl total = total + mst_varname[i]["key"] -dnl return total -define(`get_total_mst_weight', `_get_total_mst_weight(`$1', 0, 1)') - -dnl mst_varname=$1, total=$2, i=$3 -define(`_get_total_mst_weight', -`ifelse(eval($3 >= array_get(`$1', `length')), 1, `$2', -`_get_total_mst_weight(`$1', eval($2 + array2_get(`$1', `$3', `key')), incr($3))'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 1 || !parse_int_list(`weights', ARGV1)), 1, `show_usage()')dnl -define(`num_vertices', isqrt(array_get(`weights', `length')))dnl -ifelse(eval(array_get(`weights', `length') != num_vertices * num_vertices), 1, `show_usage()')dnl -create_graph(`weights', num_vertices, `graph')dnl -prim_mst(`graph', `mst')dnl -get_total_mst_weight(`mst') - -``` - -{% endraw %} - -Minimum Spanning Tree in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/mathematica/index.md b/docs/projects/minimum-spanning-tree/mathematica/index.md deleted file mode 100644 index 895e66f0c8..0000000000 --- a/docs/projects/minimum-spanning-tree/mathematica/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-18 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2023-01-18 -layout: default -tags: -- mathematica -- minimum-spanning-tree -title: Minimum Spanning Tree in Mathematica -title1: Minimum Spanning -title2: Tree in Mathematica ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* This is easy to do using Mathematica graph operations: *) - -minimumSpanningTreeWeight = am \[Function] Module[ - {g = WeightedAdjacencyGraph[am /. 0 -> \[Infinity] (* needed to indicate no edge *)]}, - Total[PropertyValue[ - {g, EdgeList[FindSpanningTree[g, Method -> "Prim"]]}, - EdgeWeight]]]; - -(* The outer function provides the 'user interface': *) - -minimumSpanningTreeWeightMain = l \[Function] - Module[{e = "Usage: please provide a comma-separated list of integers"}, - Catch[ - minimumSpanningTreeWeight@ - (* convert to square matrix *) - Partition[#, - (* compute square dimension *) - Module[{l = Sqrt[Length[#]]}, - If[IntegerQ[l], l, Throw[e]]]] & @ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments to spanning tree: - weighted adjacency matrix *) - StringSplit[If[StringLength[l] > 0, l, Throw[e]], ", "], - {-1} (* at each leaf *)]]]; - - -(* Valid Tests *) - -minimumSpanningTreeWeightMain["0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0"] - - -(* Invalid Tests *) - -minimumSpanningTreeWeightMain[""] -minimumSpanningTreeWeightMain["1, 0, 3, 0, 5, 1"] - -``` - -{% endraw %} - -Minimum Spanning Tree in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/pascal/index.md b/docs/projects/minimum-spanning-tree/pascal/index.md deleted file mode 100644 index 1a46984cc9..0000000000 --- a/docs/projects/minimum-spanning-tree/pascal/index.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- minimum-spanning-tree -- pascal -title: Minimum Spanning Tree in Pascal -title1: Minimum Spanning -title2: Tree in Pascal ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program MinimumSpanningTree; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - Math, - StrUtils, - SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a comma-separated list of integers'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value, Len, Dim: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - Len := Length(Tokens); - // Minimum size should be a 2x2 matrix - if Len < 4 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; - - Dim := Trunc(Sqrt(Result.Count)); - if Dim * Dim <> Result.Count then - begin - Result.Free; - ShowUsage; - end; -end; - -function CalculateMSTWeight(const AdjacencyMatrix: TIntegerList; - Dimension: integer): integer; -var - IncludedInMST: array of boolean; - MinEdgeWeight: array of integer; - i, NodeCount, CurrentNode, AdjacentNode, CurrentMinWeight: integer; - TotalWeight, EdgeWeight: integer; -begin - SetLength(IncludedInMST, Dimension); - SetLength(MinEdgeWeight, Dimension); - - for i := 0 to Dimension - 1 do - begin - MinEdgeWeight[i] := High(integer); - IncludedInMST[i] := False; - end; - - MinEdgeWeight[0] := 0; - TotalWeight := 0; - - for NodeCount := 0 to Pred(Dimension) do - begin - CurrentMinWeight := High(integer); - CurrentNode := -1; - - // Find vertex with minimum key not yet included in MST - for i := 0 to Dimension - 1 do - if (not IncludedInMST[i]) and (MinEdgeWeight[i] < CurrentMinWeight) then - begin - CurrentMinWeight := MinEdgeWeight[i]; - CurrentNode := i; - end; - - if CurrentNode = -1 then - begin - Writeln('Graph is not connected!'); - Exit(-1); - end; - - IncludedInMST[CurrentNode] := True; - Inc(TotalWeight, CurrentMinWeight); - - // Update edge weights for adjacent vertices - for AdjacentNode := 0 to Dimension - 1 do - if (not IncludedInMST[AdjacentNode]) then - begin - EdgeWeight := AdjacencyMatrix[CurrentNode * Dimension + AdjacentNode]; - if (EdgeWeight <> 0) and - (EdgeWeight < MinEdgeWeight[AdjacentNode]) then - MinEdgeWeight[AdjacentNode] := EdgeWeight; - end; - end; - - Result := TotalWeight; -end; - -var - Numbers: TIntegerList; - MatrixDimension: integer; -begin - if ParamCount <> 1 then - ShowUsage; - - Numbers := ParseIntegerList(ParamStr(1)); - try - MatrixDimension := Trunc(Sqrt(Numbers.Count)); - Writeln(CalculateMSTWeight(Numbers, MatrixDimension)); - finally - Numbers.Free; - end; -end. - -``` - -{% endraw %} - -Minimum Spanning Tree in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/php/index.md b/docs/projects/minimum-spanning-tree/php/index.md deleted file mode 100644 index 130f0eeb8d..0000000000 --- a/docs/projects/minimum-spanning-tree/php/index.md +++ /dev/null @@ -1,283 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- minimum-spanning-tree -- php -title: Minimum Spanning Tree in PHP -title1: Minimum Spanning -title2: Tree in PHP ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -function create_graph($weights, $num_vertices) -{ - // Initialize nodes - $nodes = array_map( - function ($id) { return new Node($id); }, - range(0, $num_vertices - 1) - ); - - // Get neighbors for this node based on weights - $index = 0; - for ($row = 0; $row < $num_vertices; $row++) - { - for ($col = 0; $col < $num_vertices; $col++, $index++) - { - if ($weights[$index] > 0) - { - $nodes[$row]->add_child($col, $weights[$index]); - } - } - } - - return $nodes; -} - -class Node -{ - public $index; - public $children; - - public function __construct($index) - { - $this->index = $index; - $this->children = array(); - } - - public function add_child($index, $weight) - { - array_push($this->children, new NodeItem($index, $weight)); - } -} - -class NodeItem -{ - public $index; - public $weight; - - public function __construct($index, $weight) - { - $this->index = $index; - $this->weight = $weight; - } -} - -// Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of -// https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ -function prim_mst(&$graph) -{ - $num_vertices = count($graph); - - // Array to store constructed MST. Indicate no parents yet - $parents = array_fill(0, $num_vertices, -1); - - // Key values used to pick minimum weight edge. Initialize to infinity - $keys = array_fill(0, $num_vertices, PHP_INT_MAX); - - // Indicate nothing in MST yet - $mst_set = array_fill(0, $num_vertices, FALSE); - - // Include first vertex in MST - $keys[0] = 0; - - // The MST will include all vertices - for ($i = 1; $i < $num_vertices; $i++) - { - // Pick index of the minimum key value not already in MST - $u = find_min_key($keys, $mst_set); - - // Add picked vertex to MST - $mst_set[$u] = TRUE; - - // Update key values and parent indices of picked adjacent - // vertices. Only consider vertices not yet in MST - foreach ($graph[$u]->children as $child) - { - $v = $child->index; - $graph_value = $child->weight; - if (!$mst_set[$v] && $graph_value < $keys[$v]) - { - $parents[$v] = $u; - $keys[$v] = $graph_value; - } - } - } - - // Construct MST information to return, skipping over root - $mst = array(); - for ($i = 1; $i < $num_vertices; $i++) - { - array_push($mst, new MSTItem($parents[$i], $i, $keys[$i])); - } - - return $mst; -} - -class MSTItem -{ - public $src_index; - public $dest_index; - public $weight; - - function __construct($src_index, $dest_index, $weight) - { - $this->src_index = $src_index; - $this->dest_index = $dest_index; - $this->weight = $weight; - } -} - -// Find vertex with minimum key values not already in MST -function find_min_key($keys, $mst_set) -{ - $min_value = PHP_INT_MAX; - $min_index = -1; - foreach ($keys as $v => $key_value) - { - if ($key_value < $min_value && !$mst_set[$v]) - { - $min_value = $key_value; - $min_index = $v; - } - } - - return $min_index; -} - -// Get total MST weight -function get_total_mst_weight($mst) -{ - return array_sum( - array_map( - function ($mst_item) { return $mst_item->weight; }, - $mst - ) - ); -} - -// Exit if too few arguments -if (count($argv) < 2) -{ - usage(); -} - -// Parse 1st argument. Exit if invalid -$weights = parse_int_array($argv[1]); -if ($weights === FALSE) -{ - usage(); -} - -// Exit if number of weight is not a square -$num_weights = count($weights); -$num_vertices = round(sqrt($num_weights)); -if ($num_weights != $num_vertices * $num_vertices) -{ - usage(); -} - -// Create graph from weights -$graph = create_graph($weights, $num_vertices); - -// Get MST using Prim's algorithm -$mst = prim_mst($graph); - -// Calculate total weight of MST and display -$total_weight = get_total_mst_weight($mst); -echo "$total_weight\n"; - -``` - -{% endraw %} - -Minimum Spanning Tree in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/powershell/index.md b/docs/projects/minimum-spanning-tree/powershell/index.md deleted file mode 100644 index 70c1d92dbc..0000000000 --- a/docs/projects/minimum-spanning-tree/powershell/index.md +++ /dev/null @@ -1,195 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-28 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2025-07-28 -layout: default -tags: -- minimum-spanning-tree -- powershell -title: Minimum Spanning Tree in PowerShell -title1: Minimum Spanning -title2: Tree in PowerShell ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide a comma-separated list of integers" - Exit(1) -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -class NodeItem { - [int]$Index - [int]$Weight - - NodeItem([int]$index, [int]$weight) { - $this.Index = $index - $this.Weight = $weight - } -} - -class Node { - [int]$Index - [NodeItem[]]$Children - - Node([int]$index) { - $this.Index = $index - $this.Children = @() - } - - [void] AddChild([int]$index, [int]$weight) { - $this.Children += [NodeItem]::new($index, $weight) - } -} - -function Create-Graph([array]$Weights, [int]$NumVertices) { - # Initialize nodes - $nodes = 0..($NumVertices - 1) | ForEach-Object { [Node]::new($_) } - - # Get neighbors for this node based on weights - $index = 0 - for ($row = 0; $row -lt $NumVertices; $row++) { - for ($col = 0; $col -lt $NumVertices; ($col++), ($index++)) { - if ($Weights[$index] -gt 0) { - $nodes[$row].AddChild($col, $Weights[$index]) - } - } - } - - $nodes -} - -class MstItem { - [int]$SrcIndex - [int]$DestIndex - [int]$Weight - - MstItem([int]$srcIndex, [int]$destIndex, [int]$weight) { - $this.SrcIndex = $srcIndex - $this.DestIndex = $destIndex - $this.Weight = $weight - } -} - -# Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of -# https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ -function Invoke-PrimMst([Node[]]$Graph) { - $numVertices = $Graph.Length - - # Array to store constructed MST. Indicate no parents yet - $parents = @(-1) * $numVertices - - # Key values used to pick minimum weight edge. Initialize to infinity - $keys = @([int]::MaxValue) * $numVertices - - # Indicate nothing in MST yet - $mstSet = @($false) * $numVertices - - # Include first vertex in MST - $keys[0] = 0 - - # The MST will include all vertices - for ($i = 1; $i -lt $numVertices; $i++) { - # Pick index of the minimum key value not already in MST - $u = Find-MinKey $keys $mstSet - - # Add picked vertex to MST - $mstSet[$u] = $true - - # Update key values and parent indices of picked adjacent - # vertices. Only consider vertices not yet in MST - foreach ($child in $Graph[$u].Children) { - $v = $child.Index - $w = $child.Weight - if (-not $mstSet[$v] -and $w -lt $keys[$v]) { - $parents[$v] = $u - $keys[$v] = $w - } - } - } - - # Construct MST information to return, skipping over root - @(1..($numVertices - 1) | ForEach-Object { [MstItem]::new($parents[$_], $_, $keys[$_]) }) -} - -function Find-MinKey([int[]]$Keys, [bool[]]$MstSet) { - $minValue = [int]::MaxValue - $minIndex = -1 - for ($v = 0; $v -lt $Keys.Length; $v++) { - if ($Keys[$v] -lt $minValue -and -not $MstSet[$v]) { - $minValue = $Keys[$v] - $minIndex = $v - } - } - - $minIndex -} - -function Invoke-MstTotalWeight([MstItem[]]$mst) { - ($mst.Weight | Measure-Object -Sum).Sum -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -try { - $weights = Parse-IntList $args[0] -} catch { - Show-Usage -} - -$numVertices = [int][Math]::Floor([Math]::Sqrt($weights.Length)) -if ($weights.Length -ne $numVertices * $numVertices) { - Show-Usage -} - -# Create graph from weights -$graph = Create-Graph $weights $numVertices - -# Get MST using Prim's algorithm -$mst = Invoke-PrimMst $graph - -# Calculate total weight of MST -$totalWeight = Invoke-MstTotalWeight $mst -Write-Output $totalWeight - -``` - -{% endraw %} - -Minimum Spanning Tree in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/python/index.md b/docs/projects/minimum-spanning-tree/python/index.md deleted file mode 100644 index 4b90f80aed..0000000000 --- a/docs/projects/minimum-spanning-tree/python/index.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Yuchuan Liu -date: 2019-10-14 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- minimum-spanning-tree -- python -title: Minimum Spanning Tree in Python -title1: Minimum Spanning -title2: Tree in Python ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - -USAGE = 'Usage: please provide a comma-separated list of integers' - - -def prims_algorithm(weights): - num_verticies = len(weights) - map_c, map_e = {ind: max([elem for row in weights for elem in row]) + - 1 for ind in range(num_verticies)}, {ind: None for ind in range(num_verticies)} - set_f, set_q = set(), set(range(num_verticies)) - while len(set_q) > 0: - v = [i for i in set_q if map_c[i] == min( - [map_c[item] for item in set_q])][0] - set_q.remove(v) - set_f.add(v) - set_f.add(map_e[v]) if map_e[v] is not None else None - for w in range(num_verticies): - if v == w: - continue - if w in set_q and 0 < weights[w][v] <= map_c[w]: - map_c[w] = weights[w][v] - map_e[w] = v - return sum([weights[v][w] for v, w in map_e.items() if v is not None and w is not None]) - - -def _validate_arguments(): - arguments = sys.argv[1:] - if len(arguments) != 1: - log(USAGE) - sys.exit() - try: - weights = [int(weight.strip()) for weight in arguments[0].split(',')] - except Exception: - log(USAGE) - sys.exit() - num_verticies = len(weights) ** 0.5 - if num_verticies != int(num_verticies): - log(USAGE) - sys.exit() - num_verticies = int(num_verticies) - weights = [[weights[num_verticies * row + col] - for col in range(num_verticies)] for row in range(num_verticies)] - for row in range(num_verticies): - for col in range(row, num_verticies): - if weights[row][col] != weights[col][row]: - log('The matrix you provided doesn\'t represent an undirected graph.') - sys.exit() - return weights - - -def log(msg): - sys.stdout.write('{}\n'.format(msg)) - - -def main(): - weights = _validate_arguments() - ret = prims_algorithm(weights) - log(ret) - - -def test(): - _test_case_1() - _test_case_2() - _test_case_3() - _test_case_4() - _test_case_5() - - -def _test_case_1(): - log('Test case 1') - sys.argv = sys.argv[:1] - try: - main() - except SystemExit: - pass - - -def _test_case_2(): - log('Test case 2') - sys.argv = sys.argv[:1] + [""] - try: - main() - except SystemExit: - pass - - -def _test_case_3(): - log('Test case 3') - sys.argv = sys.argv[:1] + ["1, 0, 3, 0, 5, 1"] - try: - main() - except SystemExit: - pass - - -def _test_case_4(): - log('Test case 4') - sys.argv = sys.argv[:1] + \ - ["0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 0, 0"] - try: - main() - except SystemExit: - pass - - -def _test_case_5(): - log('Test case 5') - sys.argv = sys.argv[:1] + \ - ["0, 2, 0, 6, 0, 2, 0, 3, 8, 5, 0, 3, 0, 0, 7, 6, 8, 0, 0, 9, 0, 5, 7, 9, 0"] - try: - main() - except SystemExit: - pass - - -if __name__ == '__main__': - # test() - main() - -``` - -{% endraw %} - -Minimum Spanning Tree in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Yuchuan Liu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/ruby/index.md b/docs/projects/minimum-spanning-tree/ruby/index.md deleted file mode 100644 index 68e95acead..0000000000 --- a/docs/projects/minimum-spanning-tree/ruby/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- minimum-spanning-tree -- ruby -title: Minimum Spanning Tree in Ruby -title1: Minimum Spanning -title2: Tree in Ruby ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = "Usage: please provide a comma-separated list of integers" - -def usage! - warn USAGE - exit 1 -end - -def parse_input - raw = ARGV.first - usage! if raw.nil? || raw.strip.empty? - - nums = raw.split(",").map { Integer(it.strip) } - n = Integer(Math.sqrt(nums.length)) - usage! unless n * n == nums.length - - Array.new(n) { |i| nums[i * n, n] } -rescue ArgumentError, NoMethodError - usage! -end - -def find(parent, x) - (parent[x] == x) ? x : (parent[x] = find(parent, parent[x])) -end - -def union(parent, rank, a, b) - a = find(parent, a) - b = find(parent, b) - return if a == b - - if rank[a] < rank[b] - parent[a] = b - elsif rank[a] > rank[b] - parent[b] = a - else - parent[b] = a - rank[a] += 1 - end -end - -def mst_weight(matrix) - n = matrix.size - - edges = - (0...n).flat_map do |i| - (i + 1...n).map do |j| - w = matrix[i][j] - w.positive? ? [w, i, j] : nil - end - end.compact - - edges.sort_by!(&:first) - - parent = (0...n).to_a - rank = Array.new(n, 0) - - edges.reduce(0) do |total, (w, u, v)| - next total if find(parent, u) == find(parent, v) - - union(parent, rank, u, v) - total + w - end -end - -matrix = parse_input -puts mst_weight(matrix) - -``` - -{% endraw %} - -Minimum Spanning Tree in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/rust/index.md b/docs/projects/minimum-spanning-tree/rust/index.md deleted file mode 100644 index 629ce1e3d6..0000000000 --- a/docs/projects/minimum-spanning-tree/rust/index.md +++ /dev/null @@ -1,201 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-20 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- minimum-spanning-tree -- rust -title: Minimum Spanning Tree in Rust -title1: Minimum Spanning -title2: Tree in Rust ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::collections::{HashMap, HashSet}; - -fn usage() -> ! { - println!("Usage: please provide a comma-separated list of integers"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -#[derive(Debug, Clone)] -struct Node { - index: usize, - children: HashMap, -} - -impl Node { - fn new(index: usize) -> Node { - Node {index: index, children: HashMap::::new()} - } - - fn add_child(&mut self, index: usize, weight: i32) { - self.children.insert(index, weight); - } -} - -type Tree = Vec; - -fn create_tree(weights: &Vec, num_vertices: usize) -> Tree { - // Create nodes - let mut nodes: Vec = (0..num_vertices) - .map(|index| Node::new(index)) - .collect(); - - // Add child nodes to each node based on non-zero values of adjacency matrix - let mut index = 0; - for row in 0..num_vertices { - for col in 0..num_vertices { - let weight = weights[index]; - index += 1; - if weight > 0 { - nodes[row].add_child(col, weight); - } - } - } - - nodes -} - -#[derive(Debug)] -struct MstResult { - src_index: usize, - dest_index: usize, - weight: i32, -} - -impl MstResult { - fn new(src_index: usize, dest_index: usize, weight: i32) -> MstResult { - MstResult {src_index: src_index, dest_index: dest_index, weight: weight} - } -} - -// Prim's Minimum Spanning Tree (MST) Algorithm based on C implementation of -// https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/ -fn prim_mst(tree: &Tree) -> Vec { - let num_vertices = tree.len(); - - // Array to store constructed MST. Indicate no parents yet - let mut parents = vec![0; num_vertices]; - - // Key values used to pick minimum weight edge. Initialize to infinity - let mut keys = vec![i32::MAX; num_vertices]; - - // Indicate nothing in MST yet - let mut mst_set = HashSet::::new(); - - // Include first vertex in MST - keys[0] = 0; - - // The MST will include all vertices - while mst_set.len() < num_vertices { - // Pick index of the minimum key value not already in MST - let u: usize = (0..num_vertices) - .filter(|index| !mst_set.contains(index)) - .map(|index| (keys[index], index)) - .min() - .unwrap() - .1; - - // Add picked vertex to MST - mst_set.insert(u); - - // Update key values and parent indices of picked adjacent - // vertices. Only consider vertices not yet in MST - for (v, weight) in tree[u].children.iter() { - if !mst_set.contains(v) && *weight < keys[*v] { - parents[*v] = u; - keys[*v] = *weight; - } - } - } - - // Construct MST information to return, skipping over root - (1..num_vertices) - .map(|v| MstResult::new(parents[v], v, keys[v])) - .collect() -} - -fn get_total_mst_weight(mst: &Vec) -> i32 { - mst.iter() - .map(|mst_item| mst_item.weight) - .sum() -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let weights: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if number of weights is not a square - let num_weights = weights.len(); - let num_vertices = (num_weights as f32).sqrt().round() as usize; - if num_weights != num_vertices * num_vertices - { - usage(); - } - - // Create tree - let tree = create_tree(&weights, num_vertices); - - // Get MST using Prim's algorithm - let mst = prim_mst(&tree); - - // Calculate total weight of MST and display - println!("{}", get_total_mst_weight(&mst)); -} - -``` - -{% endraw %} - -Minimum Spanning Tree in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/swift/index.md b/docs/projects/minimum-spanning-tree/swift/index.md deleted file mode 100644 index 44928645e7..0000000000 --- a/docs/projects/minimum-spanning-tree/swift/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- minimum-spanning-tree -- swift -title: Minimum Spanning Tree in Swift -title1: Minimum Spanning -title2: Tree in Swift ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = "Usage: please provide a comma-separated list of integers" - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseMatrix(_ input: String?) -> [[Int]]? { - guard - let input = input, - !input.isEmpty - else { return nil } - - let values = - input - .split(separator: ",") - .map { Int($0.trimmed) } - - guard values.allSatisfy({ $0 != nil }) else { return nil } - let flat = values.compactMap { $0 } - - let n = Int(Double(flat.count).squareRoot()) - guard n * n == flat.count else { return nil } - - return stride(from: 0, to: flat.count, by: n) - .map { Array(flat[$0..<$0 + n]) } -} - -func minimumSpanningTreeCost(_ matrix: [[Int]]) -> Int { - let n = matrix.count - guard n > 0 else { return 0 } - - var visited = Array(repeating: false, count: n) - var minEdge = Array(repeating: Int.max, count: n) - minEdge[0] = 0 - - var total = 0 - - for _ in 0.. 0 && !visited[v] && weight < minEdge[v] { - minEdge[v] = weight - } - } - - return total -} - -guard - let matrix = parseMatrix(CommandLine.arguments.dropFirst().first) -else { - print(usage) - exit(1) -} - -print(minimumSpanningTreeCost(matrix)) - -``` - -{% endraw %} - -Minimum Spanning Tree in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/tcl/index.md b/docs/projects/minimum-spanning-tree/tcl/index.md deleted file mode 100644 index 38552ad520..0000000000 --- a/docs/projects/minimum-spanning-tree/tcl/index.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- minimum-spanning-tree -- tcl -title: Minimum Spanning Tree in Tcl -title1: Minimum Spanning -title2: Tree in Tcl ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 -package require struct::graph -package require struct::graph::op - -proc usage {} { - puts stderr {Usage: please provide a comma-separated list of integers} - exit 1 -} - -proc isInteger {x} { return [string is integer -strict $x] } - -proc parseList {s} { - set s [string trim $s] - if {$s eq ""} { usage } - - set result {} - foreach t [split $s ,] { - set t [string trim $t] - if {![isInteger $t] || $t < 0} { usage } - lappend result $t - } - return $result -} - -proc range {start end} { - set result {} - for {set i $start} {$i <= $end} {incr i} { lappend result $i } - return $result -} - -proc createGraph {matrix} { - set n [expr {int(sqrt([llength $matrix]))}] - if {$n * $n != [llength $matrix]} { usage } - - set g [::struct::graph] - $g node insert {*}[range 0 [expr {$n-1}]] - - set idx 0 - for {set i 0} {$i < $n} {incr i} { - for {set j 0} {$j < $n} {incr j} { - set w [lindex $matrix $idx] - incr idx - if {$w > 0} { - $g arc setweight [$g arc insert $i $j] $w - } - } - } - return $g -} - -if {[llength $argv] != 1} { usage } -set matrixStr [lindex $argv 0] - -set matrix [parseList $matrixStr] -set g [createGraph $matrix] - -try { - set mst [::struct::graph::op::prim $g] - set arcWeights [$g arc weights] - - set totalWeight 0 - foreach a $mst { - incr totalWeight [dict get $arcWeights $a] - } - - puts $totalWeight -} on error {err opts} { - usage -} finally { - $g destroy -} - - -``` - -{% endraw %} - -Minimum Spanning Tree in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/typescript/index.md b/docs/projects/minimum-spanning-tree/typescript/index.md deleted file mode 100644 index 8db88ec5a1..0000000000 --- a/docs/projects/minimum-spanning-tree/typescript/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- minimum-spanning-tree -- typescript -title: Minimum Spanning Tree in TypeScript -title1: Minimum Spanning -title2: Tree in TypeScript ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function printUsage(): void { - console.error("Usage: please provide a comma-separated list of integers"); - process.exit(1); -} - -function solveMST(flat: number[], size: number): number { - const keys: number[] = new Array(size).fill(Infinity); - const inMST: Uint8Array = new Uint8Array(size); - - keys[0] = 0; - - for (let count = 0; count < size; count++) { - let u = -1; - - for (let v = 0; v < size; v++) { - if (!inMST[v] && (u === -1 || keys[v] < keys[u])) { - u = v; - } - } - - if (u === -1 || keys[u] === Infinity) break; - - inMST[u] = 1; - - const rowOffset = u * size; - - for (let v = 0; v < size; v++) { - const weight = flat[rowOffset + v]; - - if (weight > 0 && !inMST[v] && weight < keys[v]) { - keys[v] = weight; - } - } - } - - return keys.reduce((sum, w) => (w === Infinity ? sum : sum + w), 0); -} - -function parseInput(input: string): number[] { - return input - .split(",") - .map((s) => s.trim()) - .filter((s) => s.length > 0) - .map((s) => { - const val = Number(s); - if (!Number.isInteger(val)) throw new Error("invalid"); - return val; - }); -} - -function main(): void { - const input = process.argv[2]; - - if (!input) { - printUsage(); - } - - try { - const flat = parseInput(input); - const size = Math.sqrt(flat.length); - - if (flat.length === 0 || !Number.isInteger(size)) { - throw new Error("invalid size"); - } - - const result = solveMST(flat, size); - console.log(result); - } catch { - printUsage(); - } -} - -main(); - -``` - -{% endraw %} - -Minimum Spanning Tree in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/minimum-spanning-tree/visual-basic/index.md b/docs/projects/minimum-spanning-tree/visual-basic/index.md deleted file mode 100644 index 37ffba10a4..0000000000 --- a/docs/projects/minimum-spanning-tree/visual-basic/index.md +++ /dev/null @@ -1,160 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: minimum-spanning-tree-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- minimum-spanning-tree -- visual-basic -title: Minimum Spanning Tree in Visual Basic -title1: Minimum Spanning -title2: Tree in Visual Basic ---- - - - -Welcome to the [Minimum Spanning Tree](/projects/minimum-spanning-tree) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module MinimumSpanningTree - - Private Sub ShowUsage() - Console.Error.WriteLine( - "Usage: please provide a comma-separated list of integers" - ) - Environment.Exit(1) - End Sub - - - Private Function ParseMatrix(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - ShowUsage() - End If - - Dim result As New List(Of Integer) - - For Each token In input.Split(","c, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) - - Dim value As Integer - If Not Integer.TryParse(token, value) Then - ShowUsage() - End If - - result.Add(value) - - Next - - If result.Count < 4 Then - ShowUsage() - End If - - Dim dimension As Integer = CInt(Math.Sqrt(result.Count)) - - If dimension * dimension <> result.Count Then - ShowUsage() - End If - - Return result - - End Function - - - Private Function MinimumSpanningTreeWeight(matrix As List(Of Integer), dimension As Integer) As Integer - - Dim inMST(dimension - 1) As Boolean - Dim minEdge(dimension - 1) As Integer - - For i As Integer = 0 To dimension - 1 - minEdge(i) = Integer.MaxValue - Next - - minEdge(0) = 0 - Dim totalWeight As Integer = 0 - - For i As Integer = 0 To dimension - 1 - - Dim minValue As Integer = Integer.MaxValue - Dim node As Integer = -1 - - For j As Integer = 0 To dimension - 1 - If Not inMST(j) AndAlso minEdge(j) < minValue Then - minValue = minEdge(j) - node = j - End If - Next - - If node = -1 Then - ShowUsage() - End If - - inMST(node) = True - totalWeight += minValue - - For adj As Integer = 0 To dimension - 1 - - Dim weight As Integer = matrix(node * dimension + adj) - - If weight <> 0 AndAlso Not inMST(adj) AndAlso weight < minEdge(adj) Then - minEdge(adj) = weight - End If - - Next - - Next - - Return totalWeight - - End Function - - - Public Function Main(args As String()) As Integer - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim matrix = ParseMatrix(args(0)) - Dim dimension As Integer = CInt(Math.Sqrt(matrix.Count)) - - Dim result = MinimumSpanningTreeWeight(matrix, dimension) - - Console.WriteLine(result) - - Return 0 - - End Function - -End Module -``` - -{% endraw %} - -Minimum Spanning Tree in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/algol60/index.md b/docs/projects/palindromic-number/algol60/index.md deleted file mode 100644 index 857efd0d30..0000000000 --- a/docs/projects/palindromic-number/algol60/index.md +++ /dev/null @@ -1,177 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-20 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- algol60 -- palindromic-number -title: Palindromic Number in ALGOL 60 -title1: Palindromic Number -title2: in ALGOL 60 ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please input a non-negative integer\n"); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - null byte maps to 17 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch); - integer result, ch; - begin - boolean valid; - integer s; - - result := 0; - valid := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment Ignore characters until end of argument. Indicate invalid - if not whitespace; - ignoreloop: - if ch != -1 then - begin - if ch != 12 then valid := false; - ch := indigit; - goto ignoreloop - end; - - inValidInteger := valid - end inValidInteger; - - integer procedure mod(x, n); - value x, n; - integer x, n; - begin - mod := x - n * (x % n) - end mod; - - boolean procedure isPalindromicNumber(x); - value x; - integer x; - begin - integer xrev, temp; - - comment Reverse the passed in value; - xrev := 0; - for temp := x, temp % 10 while temp > 0 do - xrev := xrev * 10 + mod(temp, 10); - - isPalindromicNumber := x = xrev - end isPalindromicNumber; - - integer argc, result, ch; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get integer value from 1st argument. Exit if invalid or - negative; - if !inValidInteger(result, ch) | result < 0 then usage; - - comment Output "true" if number is palindromic number, "false" otherwise; - if isPalindromicNumber(result) then outstring(1, "true\n") - else outstring(1, "false\n") -end - -``` - -{% endraw %} - -Palindromic Number in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/algol68/index.md b/docs/projects/palindromic-number/algol68/index.md deleted file mode 100644 index 72160f9e57..0000000000 --- a/docs/projects/palindromic-number/algol68/index.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-24 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- palindromic-number -title: Palindromic Number in ALGOL 68 -title1: Palindromic Number -title2: in ALGOL 68 ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC usage = VOID: printf(($gl$, "Usage: please input a non-negative integer")); - -PROC is palindromic number = (INT n) BOOL: -( - # Convert number to string # - STRING s := whole(n, 0); - - # Check if palindrome # - INT len := UPB s; - BOOL is palindrome := TRUE; - FOR k TO len - WHILE is palindrome - DO - is palindrome := (s[k] = s[len + 1 - k]) - OD; - - is palindrome -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINT_RESULT result := parse int(s); - -# If invalid, extra characters, or negative, exit # -INT n := value OF result; -IF NOT (valid OF result) OR (leftover OF result) /= "" OR n < 0 -THEN - usage; - stop -FI; - -# Check if number is a palindrome and display results # -BOOL is palindrome := is palindromic number(n); -printf(($gl$, (is palindrome | "true" | "false"))) - -``` - -{% endraw %} - -Palindromic Number in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/awk/index.md b/docs/projects/palindromic-number/awk/index.md deleted file mode 100644 index 5a2db45bb0..0000000000 --- a/docs/projects/palindromic-number/awk/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-07 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-04-20 -layout: default -tags: -- awk -- palindromic-number -title: Palindromic Number in AWK -title1: Palindromic -title2: Number in AWK ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please input a non-negative integer" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function is_palindromic_number(n, s, left, right, result) { - result = 1 - s = sprintf("%s", n) - left = 1 - right = length(s) - while (result && left < right) { - result = (substr(s, left++, 1) == substr(s, right--, 1)) - } - - return result -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - result = str_to_number(ARGV[1]) - if (result == "ERROR" || result < 0) { - usage() - } - - print is_palindromic_number(result) ? "true" : "false" -} - -``` - -{% endraw %} - -Palindromic Number in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/beef/index.md b/docs/projects/palindromic-number/beef/index.md deleted file mode 100644 index b2b6f4c8bc..0000000000 --- a/docs/projects/palindromic-number/beef/index.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-22 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- palindromic-number -title: Palindromic Number in Beef -title1: Palindromic -title2: Number in Beef ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace PalindromicNumber; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please input a non-negative integer"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static bool PalindromicNumber(T val) - where T: IInteger - { - String str = scope String(); - val.ToString(str); - bool isPalindromic = true; - for (int left = 0, right = str.Length - 1; left < right; left++, right--) - { - if (str[left] != str[right]) - { - isPalindromic = false; - break; - } - } - - return isPalindromic; - } - - public static int Main(String[] args) - { - if (args.Count < 1 || args[0].Length < 1) - { - Usage(); - } - - int32 val = 0; - switch (ParseInt(args[0])) - { - case .Ok(out val): - if (val < 0) - { - Usage(); - } - case .Err: - Usage(); - } - - bool result = PalindromicNumber(val); - Console.WriteLine(result ? "true" : "false"); - return 0; - } -} - -``` - -{% endraw %} - -Palindromic Number in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/c-plus-plus/index.md b/docs/projects/palindromic-number/c-plus-plus/index.md deleted file mode 100644 index 4645e78444..0000000000 --- a/docs/projects/palindromic-number/c-plus-plus/index.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -authors: -- Jeremy Grifski -- smjalageri -- Ștefan-Iulian Alecu -date: 2021-11-01 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- palindromic-number -title: Palindromic Number in C++ -title1: Palindromic -title2: Number in C++ ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please input a non-negative integer\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_nonnegative_int(std::string_view s) { - s = trim(s); - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size() && value >= 0) - ? std::make_optional(value) - : std::nullopt; -} - -constexpr bool is_palindrome(int n) { - int original = n; - int reversed = 0; - - while (n > 0) { - reversed = reversed * 10 + (n % 10); - n /= 10; - } - - return reversed == original; -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - if (auto n = to_nonnegative_int(argv[1]); n) { - int original = *n; - int reversed = 0; - - while (original > 0) { - reversed = reversed * 10 + (original % 10); - original /= 10; - } - - std::cout << std::format("{}\n", reversed == *n); - } else { - usage(); - } -} -``` - -{% endraw %} - -Palindromic Number in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- smjalageri -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/c-sharp/index.md b/docs/projects/palindromic-number/c-sharp/index.md deleted file mode 100644 index f9fa75b4e0..0000000000 --- a/docs/projects/palindromic-number/c-sharp/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- maple-johnson -- Ștefan-Iulian Alecu -date: 2025-02-18 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- palindromic-number -title: Palindromic Number in C# -title1: Palindromic -title2: Number in C# ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var raw] || !ulong.TryParse(raw.AsSpan(), out ulong number)) - return ExitWithUsage(); - -Console.WriteLine(IsPalindrome(number) ? "true" : "false"); -return 0; - -static bool IsPalindrome(ulong value) -{ - if (value < 10) - return true; - - if (value % 10 == 0) - return false; - - ulong reversedHalf = 0; - - while (value > reversedHalf) - { - reversedHalf = reversedHalf * 10 + value % 10; - value /= 10; - } - - return value == reversedHalf || - value == reversedHalf / 10; -} - -static int ExitWithUsage() -{ - Console.WriteLine("Usage: please input a non-negative integer"); - return 1; -} -``` - -{% endraw %} - -Palindromic Number in [C#](/languages/c-sharp) was written by: - -- maple-johnson -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/c/index.md b/docs/projects/palindromic-number/c/index.md deleted file mode 100644 index 4344e40414..0000000000 --- a/docs/projects/palindromic-number/c/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- smjalageri -- Ștefan-Iulian Alecu -date: 2021-11-01 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- palindromic-number -title: Palindromic Number in C -title1: Palindromic -title2: Number in C ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include - -void palindromic_number(int number) -{ - int temp = number, reversed_number = 0; - - while (temp > 0) - { - reversed_number = (reversed_number * 10) + (temp % 10); - temp = (int)(temp / 10); - } - - if (number < 0) - { - printf("Usage: please input a non-negative integer"); - exit(1); - } - else - { - if (reversed_number == number) - printf("true"); - else - printf("false"); - } -} - -int is_int(char **argv) -{ - int j = 0; - while (isdigit(argv[1][j])) - ++j; - - if (strlen(argv[1]) != j || j == 0) - return 1; - else - return 0; -} - -int main(int argc, char **argv) -{ - - if (argc != 2 || is_int(argv)) - { - printf("Usage: please input a non-negative integer"); - return 1; - } - palindromic_number(atoi(argv[1])); - return 0; -} - -``` - -{% endraw %} - -Palindromic Number in [C](/languages/c) was written by: - -- Jeremy Grifski -- rzuckerm -- smjalageri -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/cobol/index.md b/docs/projects/palindromic-number/cobol/index.md deleted file mode 100644 index 3049841cbf..0000000000 --- a/docs/projects/palindromic-number/cobol/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- palindromic-number -title: Palindromic Number in COBOL -title1: Palindromic -title2: Number in COBOL ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. palindromic-number. - -data division. -working-storage section. -01 cmdargs pic x(38). - -01 buffer-num-area. - 05 buffer-num pic 9(15). - -01 num pic s9(15) comp. -01 temp pic s9(15) comp. -01 rev pic s9(15) comp value 0. -01 digit pic 9. -01 original pic s9(15) comp. - -procedure division. -main. - accept cmdargs from command-line - - if cmdargs = spaces or function trim(cmdargs) is not numeric - perform show-usage - end-if - - move function trim(cmdargs) to buffer-num - move buffer-num to num - - if num < 0 - perform show-usage - end-if - - move num to original - move num to temp - - perform until temp = 0 - divide temp by 10 giving temp remainder digit - compute rev = (rev * 10) + digit - end-perform - - if rev = original - display "true" - else - display "false" - end-if - - stop run. - -show-usage. - display "Usage: please input a non-negative integer" - stop run. -``` - -{% endraw %} - -Palindromic Number in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/commodore-basic/index.md b/docs/projects/palindromic-number/commodore-basic/index.md deleted file mode 100644 index 877a2264ce..0000000000 --- a/docs/projects/palindromic-number/commodore-basic/index.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-17 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2023-09-17 -layout: default -tags: -- commodore-basic -- palindromic-number -title: Palindromic Number in Commodore BASIC -title1: Palindromic Number -title2: in Commodore BASIC ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input N -10 GOSUB 1000 -20 IF V = 0 OR C >=0 OR NR < 0 THEN GOTO 170: REM invalid or not end character -30 N = NR -40 S$ = MID$(STR$(N), 2) -50 L = 1: REM left position -60 R = LEN(S$): REM right position -70 P = 1 -80 IF L >= R THEN GOTO 130 -90 IF MID$(S$, L, 1) <> MID$(S$, R, 1) THEN P = 0: GOTO 130: REM left != right -100 L = L + 1 -110 R = R - 1 -120 GOTO 80 -130 R$ = "false" -140 IF P <> 0 THEN R$ = "true" -150 PRINT R$ -160 END -170 PRINT "Usage: please input a non-negative integer" -180 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN - -``` - -{% endraw %} - -Palindromic Number in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/dart/index.md b/docs/projects/palindromic-number/dart/index.md deleted file mode 100644 index 8711c84acd..0000000000 --- a/docs/projects/palindromic-number/dart/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- gangaasoonu -date: 2025-10-04 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-10-04 -layout: default -tags: -- dart -- palindromic-number -title: Palindromic Number in Dart -title1: Palindromic -title2: Number in Dart ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -//Issue 4971 -void main(List args){ - const String error_message= "Usage: please input a non-negative integer"; - if (args.isEmpty){ - print(error_message); - return; - } - - try{ - bool is_palindrome = true; - int num_needed = int.parse(args[0]); - - if (num_needed.isNegative){ - print(error_message); - return; - } - - String original_string = num_needed.toString(); - String reverse_string = original_string.split('').reversed.join('') ; - is_palindrome = (original_string == reverse_string); - - print(is_palindrome); - } - catch(e){ - print(error_message); - } -} - -``` - -{% endraw %} - -Palindromic Number in [Dart](/languages/dart) was written by: - -- gangaasoonu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/elvish/index.md b/docs/projects/palindromic-number/elvish/index.md deleted file mode 100644 index 7e7516c3a1..0000000000 --- a/docs/projects/palindromic-number/elvish/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-16 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-01-16 -layout: default -tags: -- elvish -- palindromic-number -title: Palindromic Number in Elvish -title1: Palindromic -title2: Number in Elvish ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -use str - -fn die { - echo 'Usage: please input a non-negative integer' - exit 1 -} - -if (> 1 (count $args)) { - die -} - -var n = $args[0] - -# Check if the number contains a decimal point -if (str:contains $n .) { - die -} - -try { - var q = (+ $n 1) -} catch _ { - die -} - -if (> 0 $n) { - die -} - -if (eq $n (echo $n|rev)) { - echo true -} else { - echo false -} - -``` - -{% endraw %} - -Palindromic Number in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/euphoria/index.md b/docs/projects/palindromic-number/euphoria/index.md deleted file mode 100644 index cdb9ae0409..0000000000 --- a/docs/projects/palindromic-number/euphoria/index.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- palindromic-number -title: Palindromic Number in Euphoria -title1: Palindromic Number -title2: in Euphoria ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/math.e -include std/utils.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - -procedure usage() - puts(STDOUT, "Usage: please input a non-negative integer\n") - abort(0) -end procedure - -function is_palindromic_number(integer value) - -- Convert number to string - sequence s = sprintf("%d", value) - - -- Check if palindrome - integer len = length(s) - for n = 1 to intdiv(len, 2) - do - if s[n] != s[len + 1 - n] - then - return FALSE - end if - end for - - return TRUE -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int(argv[4]) -integer value = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] or value < 0 -then - usage() -end if - --- Indicate whether palindromic number or not -puts(STDOUT, iif(is_palindromic_number(value), "true\n", "false\n")) - -``` - -{% endraw %} - -Palindromic Number in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/f-sharp/index.md b/docs/projects/palindromic-number/f-sharp/index.md deleted file mode 100644 index 5e0d268f9f..0000000000 --- a/docs/projects/palindromic-number/f-sharp/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- palindromic-number -title: Palindromic Number in F# -title1: Palindromic -title2: Number in F# ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Palindrome = - let isPalindrome (n: int) = - if n < 0 then - false - elif n % 10 = 0 && n <> 0 then - false - else - let rec loop x rev = - if x <= rev then - x = rev || x = rev / 10 - else - loop (x / 10) (rev * 10 + x % 10) - - loop n 0 - -module Helpers = - let parseArgs = - function - | [| input: string |] -> - match Int32.TryParse input with - | true, n when n >= 0 -> Ok n - | _ -> Error "Usage: please input a non-negative integer" - | _ -> Error "Usage: please input a non-negative integer" - - let handleResult = - function - | Ok result -> - printfn "%b" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map Palindrome.isPalindrome - |> Helpers.handleResult - -``` - -{% endraw %} - -Palindromic Number in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/go/index.md b/docs/projects/palindromic-number/go/index.md deleted file mode 100644 index fb553ca769..0000000000 --- a/docs/projects/palindromic-number/go/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2024-10-08 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2024-10-08 -layout: default -tags: -- go -- palindromic-number -title: Palindromic Number in Go -title1: Palindromic -title2: Number in Go ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" -) - -func palindromicNumber(x int) { - if x >= 0 { - reversedNumber := 0 - noOfDigits := 0 - temp := x - - for temp > 0 { - noOfDigits++ - reversedNumber = (reversedNumber * 10) + (temp % 10) - temp /= 10 - } - - if x == reversedNumber { - fmt.Println("true") - } else { - fmt.Println("false") - } - } else { - fmt.Println("Usage: please input a non-negative integer") - } -} - -func main() { - if len(os.Args) < 2 { - fmt.Println("Usage: please input a non-negative integer") - os.Exit(1) - } - - x, err := strconv.Atoi(os.Args[1]) - if err != nil { - fmt.Println("Usage: please input a non-negative integer") - os.Exit(1) - } - - palindromicNumber(x) -} - -``` - -{% endraw %} - -Palindromic Number in [Go](/languages/go) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/haskell/index.md b/docs/projects/palindromic-number/haskell/index.md deleted file mode 100644 index 9088c87fd4..0000000000 --- a/docs/projects/palindromic-number/haskell/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-11 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- haskell -- palindromic-number -title: Palindromic Number in Haskell -title1: Palindromic -title2: Number in Haskell ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Text.Read (readMaybe) -import Data.Maybe (listToMaybe) -import System.Environment - -reverseInt :: Int -> Int -reverseInt n = go n 0 - where go 0 acc = acc - go n acc = go (n `div` 10) (acc * 10 + n `mod` 10) - -main :: IO () -main = do - args <- getArgs - case listToMaybe args >>= readMaybe of - Just n -> - if n >= 0 - then putStrLn (if reverseInt n == n then "true" else "false") - else putStrLn "Usage: please input a non-negative integer" - Nothing -> putStrLn "Usage: please input a non-negative integer" - -``` - -{% endraw %} - -Palindromic Number in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/index.md b/docs/projects/palindromic-number/index.md deleted file mode 100644 index 4fca52f99d..0000000000 --- a/docs/projects/palindromic-number/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -date: 2020-10-07 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- palindromic-number -title: Palindromic Number -title1: Palindromic -title2: Number ---- - - - -Welcome to the Palindromic Number page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -A palindromic number is a number that reads the same backward and forward. -Example: 343, 121, 909, 222 - - -## Requirements - -To implement this algorithm, your program should accept a positive integer -from the command line as follows: - -```console -./palindromic-number.lang 56765 -``` - -And report whether or not that number is a palindrome using the values -"true" and "false." See testing below for examples. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Palindromic Number. -In order to keep things simple, we split up the testing as follows: - -- Palindromic Number Valid Tests -- Palindromic Number Invalid Tests - -### Palindromic Number Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input: One Digit | "7" | "true" | -| Sample Input: Even Digits | "2442" | "true" | -| Sample Input: Odd Digits | "232" | "true" | -| Sample Input: Even Digits Not Palindrome | "5215" | "false" | -| Sample Input: Odd Digits Not Palindrome | "521" | "false" | - -### Palindromic Number Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A Number | "a" | -| Invalid Input: Negative Integer | "-7" | -| Invalid Input: Float | "5.41" | - -All of these tests should output the following: - -``` -Usage: please input a non-negative integer -``` - - -## Articles - -There are 36 articles: - -- [Palindromic Number in ALGOL 60](/projects/palindromic-number/algol60) -- [Palindromic Number in ALGOL 68](/projects/palindromic-number/algol68) -- [Palindromic Number in AWK](/projects/palindromic-number/awk) -- [Palindromic Number in Beef](/projects/palindromic-number/beef) -- [Palindromic Number in C](/projects/palindromic-number/c) -- [Palindromic Number in C#](/projects/palindromic-number/c-sharp) -- [Palindromic Number in C++](/projects/palindromic-number/c-plus-plus) -- [Palindromic Number in COBOL](/projects/palindromic-number/cobol) -- [Palindromic Number in Commodore BASIC](/projects/palindromic-number/commodore-basic) -- [Palindromic Number in Dart](/projects/palindromic-number/dart) -- [Palindromic Number in Elvish](/projects/palindromic-number/elvish) -- [Palindromic Number in Euphoria](/projects/palindromic-number/euphoria) -- [Palindromic Number in F#](/projects/palindromic-number/f-sharp) -- [Palindromic Number in Go](/projects/palindromic-number/go) -- [Palindromic Number in Haskell](/projects/palindromic-number/haskell) -- [Palindromic Number in Java](/projects/palindromic-number/java) -- [Palindromic Number in JavaScript](/projects/palindromic-number/javascript) -- [Palindromic Number in Julia](/projects/palindromic-number/julia) -- [Palindromic Number in Kotlin](/projects/palindromic-number/kotlin) -- [Palindromic Number in Mathematica](/projects/palindromic-number/mathematica) -- [Palindromic Number in OCaml](/projects/palindromic-number/ocaml) -- [Palindromic Number in PHP](/projects/palindromic-number/php) -- [Palindromic Number in Pascal](/projects/palindromic-number/pascal) -- [Palindromic Number in Perl](/projects/palindromic-number/perl) -- [Palindromic Number in PowerShell](/projects/palindromic-number/powershell) -- [Palindromic Number in Python](/projects/palindromic-number/python) -- [Palindromic Number in R](/projects/palindromic-number/r) -- [Palindromic Number in Ruby](/projects/palindromic-number/ruby) -- [Palindromic Number in Rust](/projects/palindromic-number/rust) -- [Palindromic Number in Swift](/projects/palindromic-number/swift) -- [Palindromic Number in TI-BASIC](/projects/palindromic-number/ti-basic) -- [Palindromic Number in Tcl](/projects/palindromic-number/tcl) -- [Palindromic Number in TypeScript](/projects/palindromic-number/typescript) -- [Palindromic Number in Visual Basic](/projects/palindromic-number/visual-basic) -- [Palindromic Number in Wren](/projects/palindromic-number/wren) -- [Palindromic Number in m4](/projects/palindromic-number/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/palindromic-number/java/index.md b/docs/projects/palindromic-number/java/index.md deleted file mode 100644 index 1bd685edfb..0000000000 --- a/docs/projects/palindromic-number/java/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Jeremy Grifski -- smallblack9 -date: 2020-10-11 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2022-10-11 -layout: default -tags: -- java -- palindromic-number -title: Palindromic Number in Java -title1: Palindromic -title2: Number in Java ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class PalindromicNumber { - - public static void main(String[] args) { - Long num; - try { - num = Long.parseLong(args[0]); - } catch (Exception ignored) { - num = null; - } - - if (num == null || num < 0) { - System.out.println("Usage: please input a non-negative integer"); - } else { - System.out.println(isPalindromic(num)); - } - } - - public static boolean isPalindromic(Long num) { - char[] numChars = String.valueOf(num).toCharArray(); - for (int i = 0; i < numChars.length / 2; i++) { - if (numChars[i] != numChars[numChars.length - 1 - i]) - return false; - } - return true; - } -} - -``` - -{% endraw %} - -Palindromic Number in [Java](/languages/java) was written by: - -- Jeremy Grifski -- smallblack9 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/javascript/index.md b/docs/projects/palindromic-number/javascript/index.md deleted file mode 100644 index babfd80be2..0000000000 --- a/docs/projects/palindromic-number/javascript/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Jeremy Grifski -- smjalageri -date: 2021-11-01 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2022-10-11 -layout: default -tags: -- javascript -- palindromic-number -title: Palindromic Number in JavaScript -title1: Palindromic Number -title2: in JavaScript ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const isPalindromic = (number) => { - if (number <= 1) { - console.log("Usage: please input a non-negative integer"); - process.exit(1); - } - - let reverse_number = 0, temp = number; - while (temp > 0) { - reverse_number = (reverse_number * 10) + (temp % 10); - temp = Math.floor(temp / 10); - } - - if (reverse_number == number) - return true; - else - return false; - -}; - -const input = process.argv[2]; -let number = Number(input) - -if (input !== '' && Number.isInteger(number) && number >= 0) { - isPalindromic(input) ? console.log("true") : console.log("false"); -} else { - console.log("Usage: please input a non-negative integer") -} - -``` - -{% endraw %} - -Palindromic Number in [JavaScript](/languages/javascript) was written by: - -- Jeremy Grifski -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/julia/index.md b/docs/projects/palindromic-number/julia/index.md deleted file mode 100644 index 00d0714cd2..0000000000 --- a/docs/projects/palindromic-number/julia/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- smjalageri -date: 2022-10-11 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2022-10-11 -layout: default -tags: -- julia -- palindromic-number -title: Palindromic Number in Julia -title1: Palindromic -title2: Number in Julia ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -function err() - println("Usage: please input a non-negative integer") -end - -function palindrome_check(n) - new_num = 0 - original = n - while (n > 0) - digit = n % 10 - new_num = new_num * 10 + digit - n ÷= 10 - end - - if(new_num == original) - return "true" - else - return "false" - end -end - -try - n = parse(Int, ARGS[1]) - if (n >= 0) - println(palindrome_check(n)) - else - err() - end -catch e - err() -end - -``` - -{% endraw %} - -Palindromic Number in [Julia](/languages/julia) was written by: - -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/kotlin/index.md b/docs/projects/palindromic-number/kotlin/index.md deleted file mode 100644 index 97ea58ec21..0000000000 --- a/docs/projects/palindromic-number/kotlin/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- Blake.Ke -- Isaac Anohene -- Jeremy Grifski -- rzuckerm -date: 2020-10-07 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- kotlin -- palindromic-number -title: Palindromic Number in Kotlin -title1: Palindromic -title2: Number in Kotlin ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) { - var n: Int - var num: Int - var digit: Int - var rev: Int = 0 - - try { - num = args[0].toInt() - - if (num >= 0){ - n = num - - do { - digit = num % 10 - rev = (rev * 10) + digit - num = num / 10 - }while (num != 0) - - if (n == rev){ - println(true) - }else{ - println(false) - } - }else{ - println("Usage: please input a non-negative integer") - } - - - }catch(e: Exception){ - println("Usage: please input a non-negative integer") - } -} - -``` - -{% endraw %} - -Palindromic Number in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- Isaac Anohene -- Jeremy Grifski - -This article was written by: - -- Isaac Anohene -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -We first create some variables we will use in the algorithm in the `main` function as shown here: - -```kotlin -fun main(args: Array) { - var n: Int - var num: Int - var digit: Int - var rev: Int = 0 - ``` - - Then we will convert the input argument from a string to an integer: - - ```kotlin -try { - num = args[0].toInt() - - if (num >= 0){ - ... - }else{ - println("Usage: please input a non-negative integer") - } - - -}catch(e: Exception){ - println("Usage: please input a non-negative integer") -} -``` - -If there is an error or the number is negative, we display the usage statement. - -```kotlin - Then we use a `do` while loop to reverse the number that was typed in: - - ```kotlin -do { - digit = num % 10 - rev = (rev * 10) + digit - num = num / 10 -}while (num != 0) -``` - -Finally, we check if the number and its reverse are the same or not. If they are the same, we tell the user that it's true, otherwise we tell the user that it's false, as shown here: - -```kotlin -if (n == rev){ - println(true) -}else{ - println(false) -} -``` - - -## How to Run the Solution - -At this point, we probably want to actually run the Palindromic Number in -Kotlin code snippet. Perhaps the easiest way to do so is to leverage -the online Kotlin editor. - -Alternatively, we can use the latest [standalone compiler][1]. Of course, -we'll want to get a copy of [Hello World in Kotlin][2] while we're at it. -With both in hand, all we need to do is navigate to the folder containing -our files and run the following: - -```shell -kotlinc hello-world.kt -include-runtime -d hello-world.jar -java -jar hello-world.jar -``` - -The standalone Kotlin compiler compiles Kotlin down to a -runnable Java Archive (`jar`) which we can then execute using the Java Runtime -Environment. - -[1]: https://kotlinlang.org/docs/command-line.html#manual-install -[2]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/k/kotlin/PalindromicNumber.kt diff --git a/docs/projects/palindromic-number/m4/index.md b/docs/projects/palindromic-number/m4/index.md deleted file mode 100644 index 178828f385..0000000000 --- a/docs/projects/palindromic-number/m4/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-15 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-08-31 -layout: default -tags: -- m4 -- palindromic-number -title: Palindromic Number in m4 -title1: Palindromic -title2: Number in m4 ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please input a non-negative integer -m4exit(`1')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl is_palindrome(str) -define(`is_palindrome', `_is_palindrome(`$1', 0, decr(len(`$1')))') - -dnl _is_palidrome(str, left, right) -dnl while left < right: -dnl if str[left] != str[right]: -dnl Return 0 -dnl left = left + 1 -dnl right = right - 1 -dnl Return 1 -define(`_is_palindrome', -`ifelse( - eval($2 >= $3), 1, `1', - substr(`$1', $2, 1), substr(`$1', $3, 1), `_is_palindrome(`$1', incr($2), decr($3))', `0'dnl -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !is_valid(ARGV1)), 1, `show_usage()')dnl -ifelse(eval(ARGV1 < 0), 1, `show_usage()',)dnl -ifelse(is_palindrome(ARGV1), 1, `true', `false') - -``` - -{% endraw %} - -Palindromic Number in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/mathematica/index.md b/docs/projects/palindromic-number/mathematica/index.md deleted file mode 100644 index e80e4d3522..0000000000 --- a/docs/projects/palindromic-number/mathematica/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-18 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2023-01-18 -layout: default -tags: -- mathematica -- palindromic-number -title: Palindromic Number in Mathematica -title1: Palindromic Number -title2: in Mathematica ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* This is provided by a Mathematica built-in PalindromeQ. Only a function to provide the 'user interface' is needed: *) - -palindromicNumberMain = s \[Function] Module[ - {e = "Usage: please input a non-negative integer"}, - Catch[ - Replace[ - PalindromeQ@ - (* convert string to integer, or throw *) - If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - {False -> "false", True -> "true"}]]]; - - -(* Valid Tests *) - -Print /@ palindromicNumberMain /@ { - "7", - "2442", - "232", - "5215", - "521" - }; - - -(* Invalid Tests *) - -palindromicNumberMain[""] -palindromicNumberMain["a"] -palindromicNumberMain["-5"] -palindromicNumberMain["5.41"] - -``` - -{% endraw %} - -Palindromic Number in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/ocaml/index.md b/docs/projects/palindromic-number/ocaml/index.md deleted file mode 100644 index c337851661..0000000000 --- a/docs/projects/palindromic-number/ocaml/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-17 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-17 -layout: default -tags: -- ocaml -- palindromic-number -title: Palindromic Number in OCaml -title1: Palindromic -title2: Number in OCaml ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let ( let* ) = Option.bind - -let palindrome str = - let rec aux lo hi = - lo >= hi || (str.[lo] = str.[hi] && (aux [@tailcall]) (lo + 1) (hi - 1)) - in - aux 0 (String.length str - 1) - -let validate_arg = function - | [| _; n |] -> - let* num = int_of_string_opt n in - if num >= 0 then - (* Converting back and forth normalizes the number - - allows for checking things like "+323" based on the actual numerical value *) - (* Problem statement is underspecified, so going to follow Postel's law and be permissive :) *) - Some (string_of_int num) - else None - | _ -> None - -let () = - match validate_arg Sys.argv with - | Some n -> Printf.printf "%b\n" (palindrome n) - | None -> print_endline "Usage: please input a non-negative integer" - -``` - -{% endraw %} - -Palindromic Number in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/pascal/index.md b/docs/projects/palindromic-number/pascal/index.md deleted file mode 100644 index 9831d568e7..0000000000 --- a/docs/projects/palindromic-number/pascal/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Jeremy Grifski -- manasmithamn -date: 2021-10-29 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2022-10-11 -layout: default -tags: -- palindromic-number -- pascal -title: Palindromic Number in Pascal -title1: Palindromic -title2: Number in Pascal ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -(* -Description Input Output -no input None Usage: please input a number -empty input ”” Usage: please input a number -invalid input: not a number a Usage: please input a number -sample input: palindrome 232 true -sample input: not palindrome 521 false - -Count the no. of digits -compare the left most with rightmost no & keep moving nearer to midpoint -If any one comparison fails, type false -If all comparison succeeds, type true -*) - -program Palindromic_number_check(input, output, stdErr); -(*Read count of fibonnacnoofdigits numbers into a string - -*) -var - buf: String; - noofdigits : integer; - check, number, reversed_number : Cardinal; - -begin - (*Variable initialisation must be inside begin-end block*) - (*Accept Number, check no. of digits in it, ...*) - buf:= paramStr(1); - Val(buf, number, check); - (*If input is valid integer, check will be 0, else will be 1*) - if (check <> 0) - then - begin - writeln('Usage: please input a non-negative integer'); - end - else - begin - // writeln('number = ', number); - check := number; - reversed_number := 0; - repeat - begin - (*quotient := check mod 10 ;*) - reversed_number := (reversed_number * 10) + (check mod 10); - check := trunc(check div 10); - end; - until check = 0; - - if number >= 0 then - if (reversed_number = number) then - writeln('true') - else - - writeln('false') - - else - writeln('Usage: please input a non-negative integer') - end; (* Begin Reading NUmber*) -end. (* Begin Program Block*) - -``` - -{% endraw %} - -Palindromic Number in [Pascal](/languages/pascal) was written by: - -- Jeremy Grifski -- manasmithamn - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/perl/index.md b/docs/projects/palindromic-number/perl/index.md deleted file mode 100644 index 8820a2562e..0000000000 --- a/docs/projects/palindromic-number/perl/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- manasmithamn -- Ștefan-Iulian Alecu -date: 2021-10-29 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- palindromic-number -- perl -title: Palindromic Number in Perl -title1: Palindromic -title2: Number in Perl ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -sub usage { - say "Usage: please input a non-negative integer"; - exit; -} - -my ($n) = @ARGV; -usage() unless defined $n && $n =~ /\A\d+\z/; -say $n eq reverse($n) ? "true" : "false"; - -``` - -{% endraw %} - -Palindromic Number in [Perl](/languages/perl) was written by: - -- manasmithamn -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/php/index.md b/docs/projects/palindromic-number/php/index.md deleted file mode 100644 index 343cfcb77f..0000000000 --- a/docs/projects/palindromic-number/php/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- palindromic-number -- php -title: Palindromic Number in PHP -title1: Palindromic -title2: Number in PHP ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function is_palindromic_number($value) -{ - // Convert number to string - $str = (string)$value; - - // Check if palindrome - $len = strlen($str); - $is_palindrome = TRUE; - for ($left = 0, $right = $len - 1; $left < $right && $is_palindrome; $left++, $right--) - { - $is_palindrome = ($str[$left] == $str[$right]); - } - - return $is_palindrome; - -} - -// Exit if too few arguments -if (count($argv) < 2) -{ - usage(); -} - -// Parse 1st command-line argument and exit if invalid or negative -$value = parse_int($argv[1]); -if ($value === FALSE || $value < 0) -{ - usage(); -} - -// Check if number is a palindrome and display results -$is_palindrome = is_palindromic_number($value); -printf("%s\n", $is_palindrome ? "true" : "false"); - -``` - -{% endraw %} - -Palindromic Number in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/powershell/index.md b/docs/projects/palindromic-number/powershell/index.md deleted file mode 100644 index b23e7f3380..0000000000 --- a/docs/projects/palindromic-number/powershell/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-05-24 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-05-24 -layout: default -tags: -- palindromic-number -- powershell -title: Palindromic Number in PowerShell -title1: Palindromic Number -title2: in PowerShell ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please input a non-negative integer" - Exit 1 -} - -function Test-IsPalindromicNumber([int]$Value) { - $Str = [string]$Value - $Str -eq -join $Str[$Str.Length..0] -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $Value = [int]::Parse($args[0]) -} catch { - Show-Usage -} - -if ($Value -lt 0) { - Show-Usage -} - -Write-Host ((Test-IsPalindromicNumber $Value) ? "true" : "false") - -``` - -{% endraw %} - -Palindromic Number in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/python/index.md b/docs/projects/palindromic-number/python/index.md deleted file mode 100644 index 5907ffed4a..0000000000 --- a/docs/projects/palindromic-number/python/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Jeremy Grifski -- manasmithamn -date: 2021-10-27 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2022-10-11 -layout: default -tags: -- palindromic-number -- python -title: Palindromic Number in Python -title1: Palindromic -title2: Number in Python ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def palindromic_number(x): - if x >= 0: - reversed_number = 0 - - noofdigits = 0 - temp = x - while (temp > 0): - noofdigits += 1 - reversed_number = (reversed_number * 10) + (temp % 10) - temp = int(temp/10) - - if x == reversed_number: - print("true") - else: - print("false") - else: - print("Usage: please input a non-negative integer") - - -def main(): - try: - palindromic_number(int(sys.argv[1])) - except (IndexError, ValueError): - print("Usage: please input a non-negative integer") - sys.exit(1) - - -if __name__ == "__main__": - main() - -``` - -{% endraw %} - -Palindromic Number in [Python](/languages/python) was written by: - -- Jeremy Grifski -- manasmithamn - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/r/index.md b/docs/projects/palindromic-number/r/index.md deleted file mode 100644 index 623b8041b1..0000000000 --- a/docs/projects/palindromic-number/r/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- palindromic-number -- r -title: Palindromic Number in R -title1: Palindromic -title2: Number in R ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -args <- commandArgs(trailingOnly = TRUE) - -USAGE <- "Usage: please input a non-negative integer" - -if (length(args) != 1 || !nzchar(x <- args[[1]]) || !grepl("^[0-9]+$", x)) { - cat(USAGE, "\n") - quit(status = 1) -} - -n <- as.numeric(x) -orig <- n -rev_num <- 0 - -while (n > 0) { - rev_num <- rev_num * 10 + (n %% 10) - n <- n %/% 10 -} - -cat(tolower(orig == rev_num), "\n") -``` - -{% endraw %} - -Palindromic Number in [R](/languages/r) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/ruby/index.md b/docs/projects/palindromic-number/ruby/index.md deleted file mode 100644 index 9cfef0693b..0000000000 --- a/docs/projects/palindromic-number/ruby/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- MSJ -- Ștefan-Iulian Alecu -date: 2024-10-02 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- palindromic-number -- ruby -title: Palindromic Number in Ruby -title1: Palindromic -title2: Number in Ruby ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def usage! - abort("Usage: please input a non-negative integer") -end - -number = Integer(ARGV.first, exception: false) - -usage! if number.nil? || number.negative? - -puts number.digits == number.digits.reverse - -``` - -{% endraw %} - -Palindromic Number in [Ruby](/languages/ruby) was written by: - -- MSJ -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/rust/index.md b/docs/projects/palindromic-number/rust/index.md deleted file mode 100644 index 2c46365f06..0000000000 --- a/docs/projects/palindromic-number/rust/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-09 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- palindromic-number -- rust -title: Palindromic Number in Rust -title1: Palindromic -title2: Number in Rust ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; -use std::fmt::Display; - -fn usage() -> ! { - println!("Usage: please input a non-negative integer"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn is_palindromic_number(n: T) -> bool { - // Source: https://stackoverflow.com/questions/24542115/how-to-index-a-string-in-rust - - // Convert number to string - let s: String = n.to_string(); - - // Check if palindrome by comparing left half of string with reversed right half of string - let half_s_len: usize = s.len() / 2; - s.chars().take(half_s_len).eq(s.chars().rev().take(half_s_len)) -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to integer - let n: u32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Determine if palindromic number and display result - println!("{}", is_palindromic_number::(n)); -} - -``` - -{% endraw %} - -Palindromic Number in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/swift/index.md b/docs/projects/palindromic-number/swift/index.md deleted file mode 100644 index 854995c18a..0000000000 --- a/docs/projects/palindromic-number/swift/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Kaalid -date: 2024-11-12 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2024-11-12 -layout: default -tags: -- palindromic-number -- swift -title: Palindromic Number in Swift -title1: Palindromic -title2: Number in Swift ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -func isPalindrome(_ input: String) -> Bool { - return input == String(input.reversed()) -} - -func main() { - let arguments = CommandLine.arguments - - guard arguments.count == 2 else { - print("Usage: please input a non-negative integer") - return - } - - let input = arguments[1] - - if let number = Int(input), number >= 0 { - - - // Check if the input is a palindrome - if isPalindrome(input) { - print("true") - } else { - print("false") - } - } else { - // If the input is not a valid positive integer - print("Usage: please input a non-negative integer") - } -} - -main() - -``` - -{% endraw %} - -Palindromic Number in [Swift](/languages/swift) was written by: - -- Kaalid - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/tcl/index.md b/docs/projects/palindromic-number/tcl/index.md deleted file mode 100644 index 703f0f73b0..0000000000 --- a/docs/projects/palindromic-number/tcl/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- palindromic-number -- tcl -title: Palindromic Number in Tcl -title1: Palindromic -title2: Number in Tcl ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 - -proc usage {} { - puts stderr "Usage: please input a non-negative integer" - exit 1 -} - -proc isNonNegativeInteger {s} { return [regexp {^[0-9]+$} $s] } - - -proc isPalindrome {s} { - set n [string length $s] - set i 0 - set j [expr {$n - 1}] - while {$i < $j} { - if {[string range $s $i $i] ne [string range $s $j $j]} { - return 0 - } - incr i - incr j -1 - } - return 1 -} - -if {$argc != 1} { usage } - -set input [string trim [lindex $argv 0]] -if {![isNonNegativeInteger $input]} { usage } - -puts [expr {[isPalindrome $input] ? "true" : "false"}] - -``` - -{% endraw %} - -Palindromic Number in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/ti-basic/index.md b/docs/projects/palindromic-number/ti-basic/index.md deleted file mode 100644 index 6381371292..0000000000 --- a/docs/projects/palindromic-number/ti-basic/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-02 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-02-02 -layout: default -tags: -- palindromic-number -- ti-basic -title: Palindromic Number in TI-BASIC -title1: Palindromic Number -title2: in TI-BASIC ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -"0123456789"->Str2 -length(Str1)->L -L<1->E -0->D -0->V -1->N -1->S -While E=0 and N<=L - sub(Str1,N,1)->C - inString(Str2,C)-1->K - If C="+" or C="-" - Then - D>0->E - If C="-" - Then 0-S->S - End - Else - K<0->E - D+1->D - V*10+K*S->V - End - N+1->N -End -If E or D<1 or V<0 Then Disp "Usage: please input a non-negative integer" -Else - V->T - 0->R - While T>0 - 10*R+remainder(T,10)->R - int(T/10)->T - End - If R=V Then Disp "true" - Else Disp "false" - End -End - -``` - -{% endraw %} - -Palindromic Number in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/typescript/index.md b/docs/projects/palindromic-number/typescript/index.md deleted file mode 100644 index 850b0e175f..0000000000 --- a/docs/projects/palindromic-number/typescript/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Meet Thakur -date: 2023-10-01 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2023-10-01 -layout: default -tags: -- palindromic-number -- typescript -title: Palindromic Number in TypeScript -title1: Palindromic Number -title2: in TypeScript ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function isPalindrome(num: number): boolean { - const numStr = num.toString(); - const reversedNumStr = numStr.split('').reverse().join(''); - return numStr === reversedNumStr; -} - -if (process.argv.length !== 3) { - console.log("Usage: please input a non-negative integer"); -} else { - const input = process.argv[2]; - const numberToCheck = parseFloat(input); - - if (!isNaN(numberToCheck) && Number.isInteger(numberToCheck) && numberToCheck >= 0) { - if (isPalindrome(numberToCheck)) { - console.log("true"); - } else { - console.log("false"); - } - } else { - console.log("Usage: please input a non-negative integer"); - } -} - -``` - -{% endraw %} - -Palindromic Number in [TypeScript](/languages/typescript) was written by: - -- Meet Thakur - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/visual-basic/index.md b/docs/projects/palindromic-number/visual-basic/index.md deleted file mode 100644 index af4c4233cc..0000000000 --- a/docs/projects/palindromic-number/visual-basic/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- palindromic-number -- visual-basic -title: Palindromic Number in Visual Basic -title1: Palindromic Number -title2: in Visual Basic ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module PalindromeNumber - - Private Sub ShowUsage() - Console.WriteLine("Usage: please input a non-negative integer") - Environment.Exit(1) - End Sub - - - Private Function IsPalindromeNumber(value As Long) As Boolean - - If value < 0 Then Return False - - Dim original As Long = value - Dim reversed As Long = 0 - - While value > 0 - Dim digit As Long = value Mod 10 - reversed = reversed * 10 + digit - value \= 10 - End While - - Return original = reversed - - End Function - - - Public Function Main(args As String()) As Integer - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim value As Long - - If Not Long.TryParse(args(0), value) OrElse value < 0 Then - ShowUsage() - End If - - Console.WriteLine(IsPalindromeNumber(value).ToString().ToLower()) - - Return 0 - - End Function - -End Module -``` - -{% endraw %} - -Palindromic Number in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/palindromic-number/wren/index.md b/docs/projects/palindromic-number/wren/index.md deleted file mode 100644 index 59aa66e7b0..0000000000 --- a/docs/projects/palindromic-number/wren/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-21 -featured-image: palindromic-number-in-every-language.jpg -last-modified: 2025-01-21 -layout: default -tags: -- palindromic-number -- wren -title: Palindromic Number in Wren -title1: Palindromic -title2: Number in Wren ---- - - - -Welcome to the [Palindromic Number](/projects/palindromic-number) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -import "os" for Process - -var args = Process.arguments - -if (args.count < 1 || args[0].count < 1) { - System.print("Usage: please input a non-negative integer") - Fiber.suspend() -} - -var s = args[0] -var n = Num.fromString(s) - -if (n == null || n < 0) { - System.print("Usage: please input a non-negative integer") - Fiber.suspend() -} - -var a = "" - -for (c in s) { - a = c + a - if (c == ".") { - System.print("Usage: please input a non-negative integer") - Fiber.suspend() - } -} - -System.print(a == s) - -``` - -{% endraw %} - -Palindromic Number in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/algol60/index.md b/docs/projects/prime-number/algol60/index.md deleted file mode 100644 index edbeb230a4..0000000000 --- a/docs/projects/prime-number/algol60/index.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-17 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- algol60 -- prime-number -title: Prime Number in ALGOL 60 -title1: Prime Number -title2: in ALGOL 60 ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please input a non-negative integer\n"); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - null byte maps to 17 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch); - integer result, ch; - begin - boolean valid; - integer s; - - result := 0; - valid := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment Ignore characters until end of argument. Indicate invalid - if not whitespace; - ignoreloop: - if ch != -1 then - begin - if ch != 12 then valid := false; - ch := indigit; - goto ignoreloop - end; - - inValidInteger := valid - end inValidInteger; - - integer procedure mod(x, n); - value x, n; - integer x, n; - begin - mod := x - n * (x % n) - end mod; - - boolean procedure isprime(x); - value x; - integer x; - begin - boolean result; - integer i, q; - - result := x = 2 | (x > 2 & mod(x, 2) != 0); - if result then - begin - q := entier(sqrt(x)); - for i := 3, i + 2 while result & i <= q do - begin - result := mod(x, i) != 0 - end - end; - - isprime := result - end isprime; - - integer argc, result, ch; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get integer value from 1st argument. Exit if invalid or - negative; - if !inValidInteger(result, ch) | result < 0 then usage; - - comment Output "prime" if number is prime, "composite" otherwise; - if isprime(result) then outstring(1, "prime\n") - else outstring(1, "composite\n") -end - -``` - -{% endraw %} - -Prime Number in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/algol68/index.md b/docs/projects/prime-number/algol68/index.md deleted file mode 100644 index 33ba5d62f2..0000000000 --- a/docs/projects/prime-number/algol68/index.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-20 -featured-image: prime-number-in-every-language.jpg -last-modified: 2023-01-30 -layout: default -tags: -- algol68 -- prime-number -title: Prime Number in ALGOL 68 -title1: Prime Number -title2: in ALGOL 68 ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC usage = VOID: printf(($gl$, "Usage: please input a non-negative integer")); - -PROC is prime = (INT n) BOOL: -( - # If less than 2 or (not 2 and even), composite # - # Else, check if prime by checking divisibility by odd numbers from 3 to sqrt(n) # - BOOL prime := TRUE; - IF n < 2 OR (n /= 2 AND n MOD 2 = 0) - THEN - prime := FALSE - ELSE - INT q := ENTIER(sqrt(n)); - INT k = 3; - FOR k FROM 3 BY 2 TO q - WHILE prime - DO - IF n MOD k = 0 - THEN - prime := FALSE - FI - OD - FI; - - prime -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINT_RESULT result := parse int(s); - -# If invalid, extra characters, or negative, exit # -INT n := value OF result; -IF NOT (valid OF result) OR (leftover OF result) /= "" OR n < 0 -THEN - usage; - stop -FI; - -# Indicate if prime # -printf(($gl$, (is prime(n) | "Prime" | "Composite"))) - -``` - -{% endraw %} - -Prime Number in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/awk/index.md b/docs/projects/prime-number/awk/index.md deleted file mode 100644 index 2bbd5d5db0..0000000000 --- a/docs/projects/prime-number/awk/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-07 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- prime-number -title: Prime Number in AWK -title1: Prime Number -title2: in AWK ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please input a non-negative integer" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function is_prime(n, result, q, i) { - result = (n == 2) || (n > 2 && n % 2 != 0) - q = sqrt(n) - for (i = 3; result && i <= q; i += 2) { - result = (n % i != 0) - } - - return result -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - result = str_to_number(ARGV[1]) - if (result == "ERROR" || result < 0) { - usage() - } - - print is_prime(result) ? "prime" : "composite" -} - -``` - -{% endraw %} - -Prime Number in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/bash/index.md b/docs/projects/prime-number/bash/index.md deleted file mode 100644 index 0f19f133b8..0000000000 --- a/docs/projects/prime-number/bash/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Jeremy Grifski -- thetbl -date: 2019-10-14 -featured-image: prime-number-in-every-language.jpg -last-modified: 2021-05-22 -layout: default -tags: -- bash -- prime-number -title: Prime Number in Bash -title1: Prime Number -title2: in Bash ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -ERROR="Usage: please input a non-negative integer" - -# based on https://stackoverflow.com/questions/45392068/check-if-a-number-is-a-prime-in-bash -function is_prime(){ - if [[ $1 -eq 2 ]] || [[ $1 -eq 3 ]]; then - return 1 # prime - fi - if [[ $(($1 % 2)) -eq 0 ]] || [[ $(($1 % 3)) -eq 0 ]] || [[ $1 -eq 1 ]]; then - return 0 # not a prime - fi - i=5; w=2 - while [[ $((i * i)) -le $1 ]]; do - if [[ $(($1 % i)) -eq 0 ]]; then - return 0 # not a prime - fi - i=$((i + w)) - w=$((6 - w)) - done - return 1 # prime -} - -# validate input number -if [[ -z "${1}" ]] -then - echo "${ERROR}" - exit 1 -fi - -if ! [[ "${1}" =~ ^[0-9]+$ ]] -then - echo "${ERROR}" - exit 1 -fi - -# sample usage -is_prime ${1} -if [[ $? -eq 0 ]]; -then - echo "composite" -else - echo "prime" -fi - -exit 0 - -``` - -{% endraw %} - -Prime Number in [Bash](/languages/bash) was written by: - -- Jeremy Grifski -- thetbl - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/beef/index.md b/docs/projects/prime-number/beef/index.md deleted file mode 100644 index 8b3d31961f..0000000000 --- a/docs/projects/prime-number/beef/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-22 -featured-image: prime-number-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- prime-number -title: Prime Number in Beef -title1: Prime Number -title2: in Beef ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace PrimeNumber; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please input a non-negative integer"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static bool IsPrime(T val) - where T : IInteger, operator explicit int, operator explicit float, operator T % T, operator T + T - where int : operator T <=> T - where float : operator explicit T - { - bool isPrime = false; - if (val == (T)2) - { - isPrime = true; - } - else if (val >= (T)3 && (val % (T)2) != (T)0) - { - isPrime = true; - T q = (T)Math.Sqrt((float)val); - for (T k = (T)3; k <= q; k += (T)2) - { - if ((val % k) == (T)0) - { - isPrime = false; - break; - } - } - } - - return isPrime; - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - int32 val = 0; - switch (ParseInt(args[0])) - { - case .Ok(out val): - if (val < 0) - { - Usage(); - } - case .Err: - Usage(); - } - - bool isPrime = IsPrime(val); - Console.WriteLine(isPrime ? "prime" : "composite"); - return 0; - } -} - -``` - -{% endraw %} - -Prime Number in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/c-plus-plus/index.md b/docs/projects/prime-number/c-plus-plus/index.md deleted file mode 100644 index 5396235ede..0000000000 --- a/docs/projects/prime-number/c-plus-plus/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- Daffa Daraz -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2019-10-14 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- prime-number -title: Prime Number in C++ -title1: Prime Number -title2: in C++ ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please input a non-negative integer\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_nonnegative_int(std::string_view s) { - s = trim(s); - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size() && value >= 0) - ? std::make_optional(value) - : std::nullopt; -} - -bool is_prime(int n) { - if (n < 2) return false; - if (n <= 3) return true; - if (n % 2 == 0 || n % 3 == 0) return false; - - for (int i = 5; i <= n / i; i += 6) { - if (n % i == 0 || n % (i + 2) == 0) return false; - } - - return true; -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - const auto n = to_nonnegative_int(argv[1]); - if (!n) usage(); - - std::cout << (is_prime(*n) ? "Prime" : "Composite") << '\n'; -} - -``` - -{% endraw %} - -Prime Number in [C++](/languages/c-plus-plus) was written by: - -- Daffa Daraz -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/c-sharp/index.md b/docs/projects/prime-number/c-sharp/index.md deleted file mode 100644 index bc2be444cb..0000000000 --- a/docs/projects/prime-number/c-sharp/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-30 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- prime-number -title: Prime Number in C# -title1: Prime Number -title2: in C# ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var raw] || !ulong.TryParse(raw, out ulong number)) - return ExitWithUsage(); - -Console.WriteLine(IsPrime(number) ? "Prime" : "Composite"); -return 0; - -static bool IsPrime(ulong value) -{ - if (value < 2) - return false; - - if (value == 2) - return true; - - if (value % 2 == 0) - return false; - - for (ulong divisor = 3; divisor * divisor <= value; divisor += 2) - { - if (value % divisor == 0) - return false; - } - - return true; -} - -static int ExitWithUsage() -{ - Console.WriteLine("Usage: please input a non-negative integer"); - return 1; -} - -``` - -{% endraw %} - -Prime Number in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/c/index.md b/docs/projects/prime-number/c/index.md deleted file mode 100644 index 387ec36db6..0000000000 --- a/docs/projects/prime-number/c/index.md +++ /dev/null @@ -1,211 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Matias -- rzuckerm -- shubhragupta-code -- Ștefan-Iulian Alecu -date: 2019-10-15 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- prime-number -title: Prime Number in C -title1: Prime -title2: Number in C ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include - -void prime_number(int number) -{ - if (number < 0) - { - printf("Usage: please input a non-negative integer\n"); - return; - } - else if (number == 0 || number == 1) - { - printf("Composite\n"); - return; - } - - for (int i = 2; i < number; i++) - { - if (number % i == 0) - { - printf("Composite\n"); - return; - } - } - printf("Prime\n"); -} - -int is_int(char *str) -{ - if (str[0] > '9' || str[0] < '0') - return 1; - for (int i = 0; str[i]; i++) - if (str[i] > '9' || str[i] < '0') - return 1; - return 0; -} - -int main(int ac, char **av) -{ - if (ac != 2 || is_int(av[1]) != 0) - { - printf("Usage: please input a non-negative integer\n"); - return 1; - } - prime_number(atoi(av[1])); - return 0; -} - -``` - -{% endraw %} - -Prime Number in [C](/languages/c) was written by: - -- Matias -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Apr 15 2026 00:50:56. The solution was first committed on Oct 15 2019 22:25:24. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Let's understand this code block by block in the order of execution. - -```c -#include -#include -``` - -In the first two lines, we are including header files using [include directive][8] to utilize some functions defined in header files later in the program. -Here, Standard Input/Output header file (*\*) is called to use **printf()** function, C Standard Library (*\*) to use **atoi()** function. - -Before we move onto the control flow, let's look on the functions which we called from header files. -**[atoi()][2]** converts argument string into an integer. **[printf()][4]** prints formatted string as output. - -Next is, - -int main(int ac, char **av) -{ - if (ac != 2 || is_int(av[1]) != 0) { - printf("Usage: please input a non-negative integer\n"); - return (1); - } - prime_number(atoi(av[1])); - return (0); -} -``` - -In C, we declare a function using general form: - -``` -return_type function_name(parameter){ - ... -} -``` - -So, we are declaring main function with return_type integer and **ac** and **av** as parameters to access command line arguments. -**ac** and **av** are variables which main function will get when run in command-line. **ac** stores argument count while **av** stores array of strings that are arguments. This should be kept in mind that all command-line arguments are stored as strings. - -**av[0]** represents first argument which always is equal to name of our program. If we type the following command in terminal: - -```console -./prime-number 2 -``` - -Here, `./prime-number` represents **av[0]** and `2` represents **av[1]**. - -In the main function, if statement checks if **ac** is not equal to 2 or value returned by **is_int()** function is not equal to 0, if so it prints **Usage: please input a non-negative integer** and program gets stopped with an exit code of 1. Otherwise **prime_number()** gets called. - -Now, we will see what happens in **is_int** function. - -```c -int is_int(char *str) { - if (str[0] > '9' || str[0] < '0') - return (1); - for (int i = 0; str[i]; i++) { - if (str[i] > '9' || str[i] < '0') - return (1); - } - return (0); -} -``` - -In this function, if the ASCII value of first character of the string is greater than '9' or less than '0', control goes to the next part and this function returns an exit value of 1. Otherwise every character of the string get checked with the above condition. If this is true, control goes to the next part and this function returns an exit value of 1. -Now, if none of the two conditions is true, the function exits with the return value of 0 indicating zero error. - -Moving to the next block: - -```c -void prime_number(int number) { - if (number < 0) { - printf("Usage: please input a non-negative integer\n"); - return; - } else if (number == 0 || number == 1) { - printf("Composite\n"); - return; - } - - for (int i = 2; i < number; i++) { - if (number % i == 0) { - printf("Composite\n"); - return; - } - } - printf("Prime\n"); -} - -``` -In this function, it is checked if number is not less than 0. If so, **Usage: please input a non-negative integer** gets printed and function returns. -If number is equal to 0 or equal to 1, **Composite** is printed and function returns. -Otherwise, control goes to the for loop which checks if the number is divisible by any other number. If so, **Composite** gets printed and function returns. Else if the function is still on, then it prints **Prime**. - -[8]: https://en.wikipedia.org/wiki/Include_directive -[2]: https://man7.org/linux/man-pages/man3/atoi.3.html -[4]: https://man7.org/linux/man-pages/man3/printf.3.html - - -## How to Run the Solution - -```console -gcc -o prime-number prime-number.c -./prime-number -``` -Another handy option is to compile and run using online C Compiler such as [OnlineGDB][5], [Repl][6] - -[5]: https://www.onlinegdb.com/ -[6]: https://replit.com/languages/c diff --git a/docs/projects/prime-number/cobol/index.md b/docs/projects/prime-number/cobol/index.md deleted file mode 100644 index 1407206e6e..0000000000 --- a/docs/projects/prime-number/cobol/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-18 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- cobol -- prime-number -title: Prime Number in COBOL -title1: Prime Number -title2: in COBOL ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. prime-number. - -data division. -working-storage section. - -01 cmdargs pic x(38). -01 num pic s9(15) comp. -01 dot-count pic 9 value 0. -01 cnt pic s9(15). -01 upper-limit pic s9(15). -01 step pic 9 value 2. - -procedure division. - -main. - accept cmdargs from command-line - - if function test-numval(cmdargs) not = 0 - perform show-usage - stop run - end-if - - inspect cmdargs tallying dot-count for all "." - if dot-count > 0 - perform show-usage - stop run - end-if - - compute num = function numval(cmdargs) - - if num < 0 - perform show-usage - stop run - end-if - - evaluate num - when 0 - when 1 - perform print-composite - stop run - when 2 - when 3 - perform print-prime - stop run - end-evaluate - - if function mod(num 2) = 0 or function mod(num 3) = 0 - perform print-composite - stop run - end-if - - compute upper-limit = function integer-part(function sqrt(num)) - - move 5 to cnt - move 2 to step - - perform until cnt > upper-limit - if function mod(num cnt) = 0 - perform print-composite - stop run - end-if - - add step to cnt - - if step = 2 - move 4 to step - else - move 2 to step - end-if - end-perform - - perform print-prime - stop run. - -print-prime. - display "prime". - -print-composite. - display "composite". - -show-usage. - display "Usage: please input a non-negative integer" - stop run. - -``` - -{% endraw %} - -Prime Number in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/commodore-basic/index.md b/docs/projects/prime-number/commodore-basic/index.md deleted file mode 100644 index e01e968038..0000000000 --- a/docs/projects/prime-number/commodore-basic/index.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: prime-number-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- prime-number -title: Prime Number in Commodore BASIC -title1: Prime Number in -title2: Commodore BASIC ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input N -10 GOSUB 1000 -20 IF V = 0 OR C >=0 OR NR < 0 THEN GOTO 180: REM invalid or not end character -30 N = NR -40 IF N < 2 THEN P = 0: GOTO 140: REM composite if less than 2 -50 IF N = 2 THEN P = 1: GOTO 140: REM prime if 2 -70 IF (N - INT(N / 2) * 2) = 0 THEN P = 0: GOTO 140: REM composite if even -80 P = 1 -90 K = 3 -100 IF (K * K) > N THEN GOTO 140 -110 IF (N - INT(N / K) * K) = 0 THEN P = 0: GOTO 140: REM composite if div by K -120 K = K + 2 -130 GOTO 100 -140 R$ = "Composite" -150 IF P <> 0 THEN R$ = "Prime" -160 PRINT R$ -170 END -180 PRINT "Usage: please input a non-negative integer" -190 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN - -``` - -{% endraw %} - -Prime Number in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/dart/index.md b/docs/projects/prime-number/dart/index.md deleted file mode 100644 index 2bff38c3d7..0000000000 --- a/docs/projects/prime-number/dart/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- gangaasoonu -date: 2025-10-05 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-10-05 -layout: default -tags: -- dart -- prime-number -title: Prime Number in Dart -title1: Prime Number -title2: in Dart ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -// Issue 4970 -import 'dart:math'; -void main(List args){ - const String error_message= "Usage: please input a non-negative integer"; - if (args.isEmpty){ - print(error_message); - return; - } - try{ - int num_needed = int.parse(args[0]); - if (num_needed.isNegative){ - print(error_message); - return; - } - - // If the number is even number other than 2 OR if number is either 0 or 1, Print Composite - if( (num_needed == 0)|| (num_needed == 1) || (num_needed %2 ==0 && num_needed != 2) ){ - print("Composite"); - return; - } - bool is_prime = true; - int max_divisor = sqrt(num_needed).toInt(); - for (int i_index = 3; i_index <= max_divisor; i_index +=2){ - if(num_needed % i_index == 0){ - is_prime = false; - break; - } - } - - print(is_prime ? "Prime" : "Composite"); - } - catch(e){ - print(error_message); - } -} - -``` - -{% endraw %} - -Prime Number in [Dart](/languages/dart) was written by: - -- gangaasoonu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/elvish/index.md b/docs/projects/prime-number/elvish/index.md deleted file mode 100644 index dbd11aa7e4..0000000000 --- a/docs/projects/prime-number/elvish/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-17 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-01-17 -layout: default -tags: -- elvish -- prime-number -title: Prime Number in Elvish -title1: Prime Number -title2: in Elvish ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -use str -use math - -fn die { - echo 'Usage: please input a non-negative integer' - exit 1 -} - -if (> 1 (count $args)) { - die -} - -var n = 0 -try { - set n = (num $args[0]) -} catch _ { - die -} - -if (or (> 0 $n) (str:contains (to-string $n) .)) { - die -} - -if (> 2 $n) { - echo 'composite' - exit 0 -} - -if (== $n 2) { - echo 'prime' - exit 0 -} - -for i [(range 2 (+ 1 (exact-num (math:ceil (math:sqrt $n)))))] { - if (== 0 (% $n $i)) { - echo 'composite' - exit 0 - } -} - -echo 'prime' - -``` - -{% endraw %} - -Prime Number in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/euphoria/index.md b/docs/projects/prime-number/euphoria/index.md deleted file mode 100644 index 889551faaa..0000000000 --- a/docs/projects/prime-number/euphoria/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: prime-number-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- prime-number -title: Prime Number in Euphoria -title1: Prime Number -title2: in Euphoria ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/math.e -include std/utils.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - -procedure usage() - puts(STDOUT, "Usage: please input a non-negative integer\n") - abort(0) -end procedure - -function is_prime(integer value) - -- If less than 2 or (not 2 and even), composite - -- Else, check if prime by checking divisibility by odd numbers from 3 to sqrt(value) - if value < 2 or (value != 2 and is_even(value)) - then - return FALSE - end if - - integer q = floor(sqrt(value)) - for n = 3 to q by 2 - do - if mod(value, n) = 0 - then - return FALSE - end if - end for - - return TRUE -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int(argv[4]) -integer value = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] or value < 0 -then - usage() -end if - --- Indicate whether prime or composite -puts(STDOUT, iif(is_prime(value), "Prime\n", "Composite\n")) - -``` - -{% endraw %} - -Prime Number in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/f-sharp/index.md b/docs/projects/prime-number/f-sharp/index.md deleted file mode 100644 index 30f91ba6c2..0000000000 --- a/docs/projects/prime-number/f-sharp/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- prime-number -title: Prime Number in F# -title1: Prime Number -title2: in F# ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Prime = - let isPrime n = - if n < 2 then false - elif n = 2 then true - elif n % 2 = 0 then false - else - let rec loop d = - if d * d > n then true - elif n % d = 0 then false - else loop (d + 2) - loop 3 - -module Helpers = - let parseArgs = - function - | [| input: string |] -> - match Int32.TryParse input with - | true, n when n >= 0 -> Ok n - | _ -> Error "Usage: please input a non-negative integer" - | _ -> Error "Usage: please input a non-negative integer" - - let handleResult = function - | Ok true -> printfn "prime"; 0 - | Ok false -> printfn "composite"; 0 - | Error e -> eprintfn "%s" e; 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map Prime.isPrime - |> Helpers.handleResult - -``` - -{% endraw %} - -Prime Number in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/fortran/index.md b/docs/projects/prime-number/fortran/index.md deleted file mode 100644 index fcaabbd36f..0000000000 --- a/docs/projects/prime-number/fortran/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- Ștefan-Iulian Alecu -date: 2020-10-30 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-10-15 -layout: default -tags: -- fortran -- prime-number -title: Prime Number in Fortran -title1: Prime Number -title2: in Fortran ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program prime_check - implicit none - integer :: argc, ios, i - character(len=256) :: arg - integer :: number - - argc = command_argument_count() - if (argc /= 1) call usage() - - call get_command_argument(1, arg) - arg = adjustl(trim(arg)) - if (len_trim(arg) == 0) call usage() - - do i = 1, len_trim(arg) - if (arg(i:i) < '0' .or. arg(i:i) > '9') call usage() - end do - - read(arg, *, iostat=ios) number - if (ios /= 0 .or. number < 0) call usage() - - if (is_prime(number)) then - print *, "Prime" - else - print *, "Composite" - end if - -contains - subroutine usage() - print *, "Usage: please input a non-negative integer" - stop - end subroutine usage - - pure function is_prime(n) result(prime) - integer, intent(in) :: n - logical :: prime - integer :: k, w, offsets(8) - - ! Wheel offsets for 30k + {1,7,11,13,17,19,23,29} - offsets = [1, 7, 11, 13, 17, 19, 23, 29] - - if (n < 2) then - prime = .false. - return - elseif (n <= 3) then - prime = .true. - return - elseif (mod(n,2) == 0 .or. mod(n,3) == 0 .or. mod(n,5) == 0) then - prime = .false. - return - end if - - prime = .true. - w = 0 - k = 7 ! start from the first wheel candidate after 5 - - do while (k*k <= n) - do w = 1, 8 - if (mod(n, k + offsets(w) - 1) == 0) then - prime = .false. - return - end if - end do - k = k + 30 - end do - - end function is_prime - -end program prime_check - -``` - -{% endraw %} - -Prime Number in [Fortran](/languages/fortran) was written by: - -- Mallikarjuna S J -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/gnu-make/index.md b/docs/projects/prime-number/gnu-make/index.md deleted file mode 100644 index 3863b29344..0000000000 --- a/docs/projects/prime-number/gnu-make/index.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-07-25 -featured-image: prime-number-in-every-language.jpg -last-modified: 2023-07-25 -layout: default -tags: -- gnu-make -- prime-number -title: Prime Number in GNU Make -title1: Prime Number -title2: in GNU Make ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -USAGE := Usage: please input a non-negative integer - -# Numbers are represented as x's so that they can be manipulated with text functions. -# This idea is based on how the GNU Make Standard Library (https://github.com/jgrahamc/gmsl) -# handles numbers. -X0 := -X1 := x -X2 := x x -X3 := x x x -X4 := x x x x -X5 := x x x x x -X6 := x x x x x x -X7 := x x x x x x x -X8 := x x x x x x x x -X9 := x x x x x x x x x -X10 := x x x x x x x x x x - -# Constants -NUMBERS := 0 1 2 3 4 5 6 7 8 9 - -# Get rest of words in a list -# Arg 1: The list -# Return: List with first word removed -REST = $(wordlist 2,$(words $(1)),$(1)) - -# Repeatedly apply a function -# Arg 1: Name of function. This function must take two arguments: -# - Function Arg1: Current value -# - Function Arg2: New value -# Arg 2: The list to repeated apply the function to -# Arg 3: Initial value -_REDUCE = $(if $(4),$(call _REDUCE,$(1),$(call $(1),$(2),$(3)),$(firstword $(4)),$(call REST,$(4))),$(call $(1),$(2),$(3))) -REDUCE = $(call _REDUCE,$(1),$(3),$(firstword $(2)),$(call REST,$(2))) - -# Split number into individual digits -# Arg 1: Number to split -# Return: Number split into individual digits -_SUBST_SPACE = $(subst $(2), $(2),$(1)) -SPLIT_NUMBER = $(strip $(call REDUCE,_SUBST_SPACE,$(NUMBERS),$(1))) - -# Indicate if valid number -# Arg 1: Number -# Return: $(X1) if valid number, $(X0) otherwise -IS_VALID_NUMBER = $(if $(strip $(1)),$(if $(filter-out $(NUMBERS),$(call SPLIT_NUMBER,$(1))),$(X0),$(X1)),$(X0)) - -# Add function -# Arg 1: Number 1 encoded as x's -# Arg 2: Number 2 encoded as x's -# Return: Number 1 + Number 2 encoded as x's -ADD = $(strip $(1) $(2)) - -# Multiply function -# Arg 1: Number 1 encoded as x's -# Arg 2: Number 2 encoded as x's -# Return: Number 1 * Number 2 encoded as x's -MULT = $(strip $(foreach _,$(2),$(1))) - -# Multiply first number by 10 and add second number -# Arg 1: Number 1 encoded as x's -# Arg 2: Number 2 -# Return: Number1 * 10 + Number 2 encoded as x's -MULT10_ADD_N = $(call ADD,$(call MULT,$(1),$(X10)),$(X$(2))) - -# Represent number as list of x's -# Arg 1: Number -# Return: Number encoded as x's -CONVERT_NUMBER = $(strip $(call REDUCE,MULT10_ADD_N,$(call SPLIT_NUMBER,$(1)),$(X0))) - -# Is divisible function -# Arg 1: Number encoded as x's -# Arg 2: Divisor encoded as x's -# Return: $(X1) if divisible, $(X0) otherwise -IS_DIVISIBLE = $(if $(strip $(subst $(2),,$(1))),$(X0),$(X1)) - -# Increment function -# Arg 1: Number encoded as x's -# Return: Number + 1 encoded as x's -INC = $(strip $(1) $(X1)) - -# Is less than function -# Arg 1: Number 1 encoded as x's -# Arg 2: Number 2 encoded as x's -# Return: $(X1) if Number 1 < Number 2, $(X0) otherwise -IS_LESS_THAN = $(if $(wordlist $(words $(call INC,$(1))),$(words $(2)),$(2)),$(X1),$(X0)) - -# Is less than or equal function -# Arg 1: Number 1 encoded as x's -# Arg 2: Number 2 encoded as x's -# Return: $(X1) if Number 1 <= Number 2, $(X0) otherwise -IS_LESS_OR_EQUAL = $(call IS_LESS_THAN,$(1),$(call INC,$(2))) - -# Is prime function -# -# If number < 2, indicate composite -# Else if number < 3, indicate prime since number must be 2 -# Else if number is even, indicate composite -# Else use trail division to determine if prime -# -# Arg 1: Number to check encoded as x's -# Return: $(X1) if prime, $(X0) if composite -IS_PRIME = $(strip \ - $(if $(call IS_LESS_THAN,$(1),$(X2)),$(X0),\ - $(if $(call IS_LESS_THAN,$(1),$(X3)),$(X1),\ - $(if $(call IS_DIVISIBLE,$(1),$(X2)),$(X0),\ - $(call TRIAL_DIVISION,$(1),$(X3))\ - )\ - )\ - )\ -) - -# Determine if number is prime using trial division while divisor squared is -# less than or equal number, trying successive odd divisors -# -# Arg 1: Number to check encoded as x's -# Arg 2: Divisor (must be odd) encoded as x's -# Return: $(X1) if prime, $(X0) if composite -TRIAL_DIVISION = $(if $(call IS_LESS_OR_EQUAL,$(call MULT,$(2),$(2)),$(1)),\ - $(if $(call IS_DIVISIBLE,$(1),$(2)),$(X0),\ - $(call TRIAL_DIVISION,$(1),$(call ADD,$(2),$(X2)))),\ - $(X1)\ -) - -# If invalid number, display usage statement -# Else if indicate if number is prime or composite -ifeq (,$(call IS_VALID_NUMBER,$(ARGV1))) -$(info $(USAGE)) -else -NUMBER := $(call CONVERT_NUMBER,$(strip $(ARGV1))) -$(info $(if $(call IS_PRIME,$(NUMBER)),prime,composite)) -endif - -.PHONY: -all: ;@: - -``` - -{% endraw %} - -Prime Number in [GNU Make](/languages/gnu-make) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/go/index.md b/docs/projects/prime-number/go/index.md deleted file mode 100644 index c7b128d2f1..0000000000 --- a/docs/projects/prime-number/go/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-05-02 -featured-image: prime-number-in-every-language.jpg -last-modified: 2019-05-02 -layout: default -tags: -- go -- prime-number -title: Prime Number in Go -title1: Prime Number -title2: in Go ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" -) - -func isPrime(n int) bool { - if n < 2 { - return false - } else { - for i := 2; i <= n/2; i++ { - if n%i == 0 { - return false - } - } - } - return true -} - -func exitWithError() { - fmt.Println("Usage: please input a non-negative integer") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - n, err := strconv.Atoi(os.Args[1]) - if err != nil || n < 0 { - exitWithError() - } - - if isPrime(n) { - fmt.Println("Prime") - } else { - fmt.Println("Composite") - } -} - -``` - -{% endraw %} - -Prime Number in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/haskell/index.md b/docs/projects/prime-number/haskell/index.md deleted file mode 100644 index d0203f9273..0000000000 --- a/docs/projects/prime-number/haskell/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-11-16 -featured-image: prime-number-in-every-language.jpg -last-modified: 2019-05-02 -layout: default -tags: -- haskell -- prime-number -title: Prime Number in Haskell -title1: Prime Number -title2: in Haskell ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import Text.Read - -isPrime :: Integral a => a -> Bool -isPrime 0 = False -isPrime 1 = False -isPrime 2 = True -isPrime x = null [n | n <- 2:[3,5..integralSqrt x], x `mod` n == 0] - where integralSqrt = round . sqrt .fromIntegral - -output :: Bool -> String -output True = "Prime" -output False = "Composite" - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - -main :: IO () -main = do - args <- getArgs - let x = headMaybe args - case x >>= readMaybe of - Nothing -> putStrLn "Usage: please input a non-negative integer" - Just x - | x < 0 -> putStrLn "Usage: please input a non-negative integer" - | otherwise -> putStrLn $ output $ isPrime x - -``` - -{% endraw %} - -Prime Number in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/index.md b/docs/projects/prime-number/index.md deleted file mode 100644 index ba8cd80bf5..0000000000 --- a/docs/projects/prime-number/index.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -date: 2018-11-16 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-05-21 -layout: default -tags: -- prime-number -title: Prime Number -title1: Prime -title2: Number ---- - - - -Welcome to the Prime Number page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -A prime number is a positive integer which is divisible only by 1 and itself. -For example: 2, 3, 5, 7, 11, 13 - -Since every number is divisible by One so, Two is the only even and the -smallest prime number. - - -## Requirements - -Create a file called Prime Number using the naming -convention appropriate for your language of choice. - -Write a sample program which accepts an integer on the command line -and outputs if the integer is a Prime number or not. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Prime Number. -In order to keep things simple, we split up the testing as follows: - -- Prime Valid Tests -- Prime Invalid Tests - -### Prime Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input 0 | "0" | "composite" | -| Sample Input 1 | "1" | "composite" | -| Sample Input 2 | "2" | "prime" | -| Sample Input Small Composite | "4" | "composite" | -| Sample Input Small Prime | "7" | "prime" | -| Sample Input Large Composite | "4011" | "composite" | -| Sample Input Large Prime | "3727" | "prime" | - -### Prime Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A Number | "a" | -| Invalid Input: Not An Integer | "6.7" | -| Invalid Input: Negative | "-7" | - -All of these tests should output the following: - -``` -Usage: please input a non-negative integer -``` - - -## Articles - -There are 45 articles: - -- [Prime Number in ALGOL 60](/projects/prime-number/algol60) -- [Prime Number in ALGOL 68](/projects/prime-number/algol68) -- [Prime Number in AWK](/projects/prime-number/awk) -- [Prime Number in Bash](/projects/prime-number/bash) -- [Prime Number in Beef](/projects/prime-number/beef) -- [Prime Number in C](/projects/prime-number/c) -- [Prime Number in C#](/projects/prime-number/c-sharp) -- [Prime Number in C++](/projects/prime-number/c-plus-plus) -- [Prime Number in COBOL](/projects/prime-number/cobol) -- [Prime Number in Commodore BASIC](/projects/prime-number/commodore-basic) -- [Prime Number in Dart](/projects/prime-number/dart) -- [Prime Number in Elvish](/projects/prime-number/elvish) -- [Prime Number in Euphoria](/projects/prime-number/euphoria) -- [Prime Number in F#](/projects/prime-number/f-sharp) -- [Prime Number in Fortran](/projects/prime-number/fortran) -- [Prime Number in GNU Make](/projects/prime-number/gnu-make) -- [Prime Number in Go](/projects/prime-number/go) -- [Prime Number in Haskell](/projects/prime-number/haskell) -- [Prime Number in Java](/projects/prime-number/java) -- [Prime Number in JavaScript](/projects/prime-number/javascript) -- [Prime Number in Julia](/projects/prime-number/julia) -- [Prime Number in Kotlin](/projects/prime-number/kotlin) -- [Prime Number in Lisp](/projects/prime-number/lisp) -- [Prime Number in Lua](/projects/prime-number/lua) -- [Prime Number in Mathematica](/projects/prime-number/mathematica) -- [Prime Number in OCaml](/projects/prime-number/ocaml) -- [Prime Number in Octave](/projects/prime-number/octave) -- [Prime Number in Odin](/projects/prime-number/odin) -- [Prime Number in PHP](/projects/prime-number/php) -- [Prime Number in Pascal](/projects/prime-number/pascal) -- [Prime Number in Perl](/projects/prime-number/perl) -- [Prime Number in PowerShell](/projects/prime-number/powershell) -- [Prime Number in Python](/projects/prime-number/python) -- [Prime Number in R](/projects/prime-number/r) -- [Prime Number in Red](/projects/prime-number/red) -- [Prime Number in Rexx](/projects/prime-number/rexx) -- [Prime Number in Ruby](/projects/prime-number/ruby) -- [Prime Number in Rust](/projects/prime-number/rust) -- [Prime Number in Swift](/projects/prime-number/swift) -- [Prime Number in TI-BASIC](/projects/prime-number/ti-basic) -- [Prime Number in Tcl](/projects/prime-number/tcl) -- [Prime Number in TypeScript](/projects/prime-number/typescript) -- [Prime Number in Visual Basic](/projects/prime-number/visual-basic) -- [Prime Number in Wren](/projects/prime-number/wren) -- [Prime Number in m4](/projects/prime-number/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/prime-number/java/index.md b/docs/projects/prime-number/java/index.md deleted file mode 100644 index 7bcff9656c..0000000000 --- a/docs/projects/prime-number/java/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Ewerton Queiroz -- Ganesh Naik -- Jeremy Grifski -- Juan D Frias -date: 2019-10-10 -featured-image: prime-number-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- java -- prime-number -title: Prime Number in Java -title1: Prime Number -title2: in Java ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -class PrimeNumberException extends Exception { -} - -public class PrimeNumber { - - public static boolean isPrime(int number) { - if ((number % 2 == 0 && number != 2) || number == 1) { - return false; - } - - boolean foundFactor = false; - for (int n = 3; n <= (int) Math.ceil(Math.sqrt(number)); ++n) { - if ((number % n) == 0) { - foundFactor = true; - break; - } - } - return !foundFactor; - } - - public static void main(String[] args) { - try { - - if (args.length < 1 || args[0].indexOf('-') != -1) { - throw new PrimeNumberException(); - } - - if (isPrime(Integer.valueOf(args[0]))) { - System.out.println("Prime"); - - } else { - System.out.println("Composite"); - } - - } catch (NumberFormatException | PrimeNumberException e) { - System.err.println("Usage: please input a non-negative integer"); - } - } -} - -``` - -{% endraw %} - -Prime Number in [Java](/languages/java) was written by: - -- Ewerton Queiroz -- Ganesh Naik -- Jeremy Grifski -- Juan D Frias - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/javascript/index.md b/docs/projects/prime-number/javascript/index.md deleted file mode 100644 index c6abaf7eea..0000000000 --- a/docs/projects/prime-number/javascript/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Ganesh Naik -- Jayden Thrasher -- rzuckerm -date: 2019-10-05 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- javascript -- prime-number -title: Prime Number in JavaScript -title1: Prime Number -title2: in JavaScript ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const isPrime = (number) => { - if(number <= 1) - return false; - - for (let i = 2; i <= Math.sqrt(number); i++) { - if (number % i == 0) { - return false; - } - } - return number > 1; - }; - - const input = process.argv[2]; - let number = Number(input); - - if (input !== '' && Number.isInteger(number) && number >= 0) { - isPrime(input) ? console.log("prime") : console.log("composite"); - } else { - console.log("Usage: please input a non-negative integer") - } - -``` - -{% endraw %} - -Prime Number in [JavaScript](/languages/javascript) was written by: - -- Ganesh Naik -- Jayden Thrasher -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/julia/index.md b/docs/projects/prime-number/julia/index.md deleted file mode 100644 index bac0641f23..0000000000 --- a/docs/projects/prime-number/julia/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Jacob Woodbury -date: 2025-02-13 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-02-13 -layout: default -tags: -- julia -- prime-number -title: Prime Number in Julia -title1: Prime Number -title2: in Julia ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -function err() - return "Usage: please input a non-negative integer" - end - - -function isPrime(num) -# handle 0 and 1 - if num <= 1 - return "composite" - end - -# default handler - for i in 2:sqrt(num) #loop starting at 2, ending at the squareroot of the input - if (num % i == 0) - return "composite" - end - end - return "prime" -end - -#check for a valid input -try - n = parse(Int, ARGS[1]) - if n < 0 - println(err()) - else - println(isPrime(n)) - end -catch e - println(err()) -end - -``` - -{% endraw %} - -Prime Number in [Julia](/languages/julia) was written by: - -- Jacob Woodbury - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/kotlin/index.md b/docs/projects/prime-number/kotlin/index.md deleted file mode 100644 index 3f7ce84b22..0000000000 --- a/docs/projects/prime-number/kotlin/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- Blake.Ke -- smallblack9 -date: 2020-10-08 -featured-image: prime-number-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- kotlin -- prime-number -title: Prime Number in Kotlin -title1: Prime Number -title2: in Kotlin ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) -{ - if (args.isNullOrEmpty() || args[0].isBlank() || args[0].toIntOrNull()?.takeIf { it >= 0 } == null) { - println("Usage: please input a non-negative integer") - return - } - - val num = args[0].toInt() - if(num>1) - { - for(i in 2 until num) - { - if(num%i == 0) - { - println("Composite") - return - } - } - println("Prime") - } - else - { - println("Composite") - } -} - -``` - -{% endraw %} - -Prime Number in [Kotlin](/languages/kotlin) was written by: - -- Blake.Ke -- smallblack9 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/lisp/index.md b/docs/projects/prime-number/lisp/index.md deleted file mode 100644 index 52b600aeea..0000000000 --- a/docs/projects/prime-number/lisp/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Parker Johansen -- Renato -date: 2020-10-01 -featured-image: prime-number-in-every-language.jpg -last-modified: 2020-10-11 -layout: default -tags: -- lisp -- prime-number -title: Prime Number in Lisp -title1: Prime Number -title2: in Lisp ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(defun primep (n) - (cond - ((= 0 n) nil) - ((= 1 n) nil) - ((= 2 n) T) - (t - (loop - :with root = (isqrt n) - :with divisors = (cons 2 (loop :for i :from 3 :to root :by 2 :collect i)) - :for d = (pop divisors) - :if (zerop (mod n d)) - :do (return nil) - :else :do (setf divisors (delete-if (lambda (x) (zerop (mod x d))) divisors)) - :while divisors - :finally (return t))))) - -(defun print-bool (b) - (if b - (write-line "prime") - (write-line "composite"))) - -(defun maybe-pos-int (input) - (cond - ((null input) nil) - ((string= input "") nil) - ((every #'digit-char-p input) (parse-integer input)) - (t nil))) - -(defparameter num (maybe-pos-int (cadr *posix-argv*))) -(cond - ((null num) (write-line "Usage: please input a non-negative integer")) - (t (print-bool (primep num)))) - -``` - -{% endraw %} - -Prime Number in [Lisp](/languages/lisp) was written by: - -- Parker Johansen -- Renato - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/lua/index.md b/docs/projects/prime-number/lua/index.md deleted file mode 100644 index 7ea7e5c49c..0000000000 --- a/docs/projects/prime-number/lua/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- bhaskar_datta -- Jeremy Grifski -date: 2019-10-27 -featured-image: prime-number-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- lua -- prime-number -title: Prime Number in Lua -title1: Prime Number -title2: in Lua ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua ---returns true if prime -function isPrime(n) - comp = "Composite" - prime = "Prime" - usage = "Usage: please input a non-negative integer" - local n = tonumber(n) - --catch nil, negative and non int numbers - if not n or n < 0 or (n % 1 ~= 0) then - print(usage) - --catch 0 and 1 - elseif n < 2 then - print(comp) - --catch even number above 2 - elseif n > 2 and (n % 2 == 0) then - print(comp) - --catch numbers that end in 5 or 0 (multiples of 5) - elseif n>5 and (n % 5 ==0) then - print(comp) - --now check for prime - else - --only do the odds - result = prime - for i = 3, math.sqrt(n), 2 do - --did it divide evenly - if (n % i == 0) then - result = comp - end - end - --can defeat optimus - print(result) - end -end - -isPrime(arg[1]) - -``` - -{% endraw %} - -Prime Number in [Lua](/languages/lua) was written by: - -- bhaskar_datta -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/m4/index.md b/docs/projects/prime-number/m4/index.md deleted file mode 100644 index 52fe2d30e4..0000000000 --- a/docs/projects/prime-number/m4/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-16 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-08-16 -layout: default -tags: -- m4 -- prime-number -title: Prime Number in m4 -title1: Prime Number -title2: in m4 ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please input a non-negative integer -m4exit(`1')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl is_prime(n) -dnl if n < 2 or (n > 2 and (n % 2) == 0): -dnl Output "0" -dnl else: -dnl k = 3 -dnl loop: -dnl if k * k > n: -dnl Output "1" and return -dnl if n % k == 0: -dnl Output "0" and return -dnl k = k + 2 -define(`is_prime', -`ifelse(eval(`$1' < 2 || (`$1' > 2 && `$1' % 2 == 0)), 1, `0', `_is_prime(`$1', 3)')'dnl -) -define(`_is_prime', -`ifelse(eval(`$2' * `$2' > `$1'), 1, `1', eval(`$1' % `$2'), 0, `0', `_is_prime(`$1', eval(`$2' + 2))')'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !is_valid(ARGV1)), 1, `show_usage()')dnl -ifelse(eval(ARGV1 < 0), 1, `show_usage()')dnl -ifelse(is_prime(ARGV1), 1, `prime', `composite') - -``` - -{% endraw %} - -Prime Number in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/mathematica/index.md b/docs/projects/prime-number/mathematica/index.md deleted file mode 100644 index 50a7887102..0000000000 --- a/docs/projects/prime-number/mathematica/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-17 -featured-image: prime-number-in-every-language.jpg -last-modified: 2023-01-17 -layout: default -tags: -- mathematica -- prime-number -title: Prime Number in Mathematica -title1: Prime Number -title2: in Mathematica ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* This is provided by a Mathematica built-in PrimeQ. Only a function to provide the 'user interface' is needed: *) - -primeNumberMain = s \[Function] Module[ - {e = "Usage: please input a non-negative integer"}, - Catch[ - Replace[ - PrimeQ@ - (* convert string to integer, or throw *) - If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - {False -> "Composite", True -> "Prime"}]]]; - - -(* Valid Tests *) - -Print /@ primeNumberMain /@ { - "0", - "1", - "2", - "4", - "7", - "4011", - "3727" - }; - - -(* Invalid Tests *) - -primeNumberMain[""] -primeNumberMain["a"] -palindromicNumberMain["6.7"] -palindromicNumberMain["-7"] - -``` - -{% endraw %} - -Prime Number in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/ocaml/index.md b/docs/projects/prime-number/ocaml/index.md deleted file mode 100644 index 5a1bc33b3e..0000000000 --- a/docs/projects/prime-number/ocaml/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-21 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-05-21 -layout: default -tags: -- ocaml -- prime-number -title: Prime Number in OCaml -title1: Prime Number -title2: in OCaml ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let has_odd_divisor_under_sqrt n = - let rec aux k = k <= n / k && (n mod k = 0 || aux (k + 2)) in - aux 3 (* Assumes n > 3. All other cases will be caught elsewhere *) - -let prime = function - | 0 | 1 -> false - | 2 | 3 -> true - | n when n mod 2 = 0 -> false - | n -> not (has_odd_divisor_under_sqrt n) - -let parse_args argv = - match argv with [| _; n |] -> int_of_string_opt n | _ -> None - -let () = - print_endline - (match parse_args Sys.argv with - | Some num when num >= 0 -> if prime num then "Prime" else "Composite" - | _ -> "Usage: please input a non-negative integer") - -``` - -{% endraw %} - -Prime Number in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/octave/index.md b/docs/projects/prime-number/octave/index.md deleted file mode 100644 index ee5b209df7..0000000000 --- a/docs/projects/prime-number/octave/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: prime-number-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- octave -- prime-number -title: Prime Number in Octave -title1: Prime Number -title2: in Octave ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function prime_number() - usage = 'Usage: please input a non-negative integer'; - arg_list = argv(); - nargin = length(arg_list); - if nargin == 0 - disp(usage); - return; - end - - n = str2num(arg_list{1}); - if length(n) ~= 1 || mod(n, 1) ~= 0 || n < 0 - disp(usage); - return; - end - - isprime = 0; - if n == 2 - isprime = 1; - elseif n < 2 || rem(n, 2) == 0 - isprime = 0; - else - isprime = 1; - q = sqrt(n); - m = 3; - while m <= q - if rem(n, m) == 0 - isprime = 0; - break; - end - m = m + 2; - end - end - - if isprime == 1 - disp('prime'); - else - disp('composite'); - end -end - -``` - -{% endraw %} - -Prime Number in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/odin/index.md b/docs/projects/prime-number/odin/index.md deleted file mode 100644 index 2f6027a4f8..0000000000 --- a/docs/projects/prime-number/odin/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- nallovint -date: 2024-07-10 -featured-image: prime-number-in-every-language.jpg -last-modified: 2024-07-10 -layout: default -tags: -- odin -- prime-number -title: Prime Number in Odin -title1: Prime Number -title2: in Odin ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main - - -import "core:fmt" -import "core:math" -import "core:os" -import "core:strconv" - -is_prime :: proc(n: i64) -> bool { - if n <= 1 { - return false - } - if n == 2 { - return true - } - for i in 2..=i64(math.sqrt(f32(n)) + 1) { - if n % i == 0 { - return false - } - } - return true -} - -usage :: proc() { - fmt.eprintln("Usage: please input a non-negative integer") -} - -prime_numbers :: proc(args : []string) { - n: i64 - ok: bool - // Get command line argument as string - args := os.args - if len(args) < 2 { - usage() - return - } - if n, ok = strconv.parse_i64(args[1]) ; !ok { - usage() - return - } - if n < 0 || n % 1 != 0 { - usage() - return - } - - if is_prime(n) { - fmt.println("prime") - } else { - fmt.println("composite") - } -} - -main :: proc() { - prime_numbers(os.args) -} - -``` - -{% endraw %} - -Prime Number in [Odin](/languages/odin) was written by: - -- nallovint - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/pascal/index.md b/docs/projects/prime-number/pascal/index.md deleted file mode 100644 index cec0baa37a..0000000000 --- a/docs/projects/prime-number/pascal/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- smjalageri -date: 2020-10-18 -featured-image: prime-number-in-every-language.jpg -last-modified: 2020-10-18 -layout: default -tags: -- pascal -- prime-number -title: Prime Number in Pascal -title1: Prime Number -title2: in Pascal ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program prime_check(input, output, stdErr); -(* Read a number from Commandline, Check if it is Prime or Composite*) -var - buf: String; -(* prime, factorial, check:Cardinal;*) -i, max_divisor, check, flag: integer; -prime: Cardinal; -begin - buf:= paramStr(1); - Val(buf, prime, check); - if check <> 0 - then - writeln('Usage: please input a non-negative integer') - else - if prime < 0 - then - writeln('Usage: please input a non-negative integer') - else - begin - if (prime = 2) then - writeln('Prime') - else - if ((prime = 0) or (prime = 1) ) - then - writeln('Composite') - else - if (prime mod 2 = 0) - then - writeln('Composite') - else - begin - flag := 0; - max_divisor := round(prime / 2); - for i := 3 to max_divisor do - begin - if ( prime mod i = 0 ) - then - flag := 1; - break; - end; - if (flag = 0) - then - writeln('Prime') - else - writeln('Composite') - end; - end -end. - -``` - -{% endraw %} - -Prime Number in [Pascal](/languages/pascal) was written by: - -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/perl/index.md b/docs/projects/prime-number/perl/index.md deleted file mode 100644 index 382142bc67..0000000000 --- a/docs/projects/prime-number/perl/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- Ștefan-Iulian Alecu -date: 2019-10-31 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- perl -- prime-number -title: Prime Number in Perl -title1: Prime Number -title2: in Perl ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -sub usage { - say "Usage: please input a non-negative integer"; - exit; -} - -my ($n) = @ARGV; -usage() unless defined $n && $n =~ /\A\d+\z/; - -$n += 0; - -say "Composite" and exit if $n < 2; -say "Prime" and exit if $n == 2; -say "Composite" and exit if $n % 2 == 0; - -for ( my $i = 3 ; $i * $i <= $n ; $i += 2 ) { - say "Composite" and exit if $n % $i == 0; -} - -say "Prime"; - -``` - -{% endraw %} - -Prime Number in [Perl](/languages/perl) was written by: - -- Mallikarjuna S J -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/php/index.md b/docs/projects/prime-number/php/index.md deleted file mode 100644 index 2215136d83..0000000000 --- a/docs/projects/prime-number/php/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Juan D Frias -- Parker Johansen -date: 2019-10-14 -featured-image: prime-number-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- php -- prime-number -title: Prime Number in PHP -title1: Prime Number -title2: in PHP ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Prime Number](/projects/prime-number) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please input a non-negative integer" - Exit 1 -} - -function Test-IsPrime([int]$Value) { - if ($Value -lt 2 -or ($Value -ne 2 -and $Value % 2 -eq 0)) { - return $false - } - - $Q = [Math]::Floor([Math]::Sqrt($Value)) - for ($X = 3; $X -le $Q; $X += 2) { - if ($Value % $X -eq 0) { - return $false - } - } - - $true -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $Value = [int]::Parse($args[0]) -} catch { - Show-Usage -} - -if ($Value -lt 0) { - Show-Usage -} - -Write-Host ((Test-IsPrime $Value) ? "prime" : "composite") - -``` - -{% endraw %} - -Prime Number in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/python/index.md b/docs/projects/prime-number/python/index.md deleted file mode 100644 index 80dd1f0624..0000000000 --- a/docs/projects/prime-number/python/index.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -authors: -- Haseeb Majid -- Jeremy Grifski -- Parker Johansen -- rzuckerm -- Zia -date: 2018-12-23 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-03-25 -layout: default -tags: -- prime-number -- python -title: Prime Number in Python -title1: Prime Number -title2: in Python ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys -from math import sqrt, ceil - - -def is_prime(x): - if (x % 2 == 0 and x != 2) or (x == 1): - return False - return not bool([n for n in range(3, int(ceil(sqrt(x))+1)) if x % n == 0]) - - -def exit_with_error(): - print('Usage: please input a non-negative integer') - sys.exit(1) - - -def main(args): - try: - x = int(args[0]) - if x < 0: - exit_with_error() - print("Prime" if is_prime(x) else "Composite") - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Prime Number in [Python](/languages/python) was written by: - -- Haseeb Majid -- Parker Johansen -- Zia - -This article was written by: - -- Haseeb Majid -- Jeremy Grifski -- Parker Johansen -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Mar 25 2025 08:48:25. The solution was first committed on Dec 23 2018 00:11:48. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -The following sections break down the checking if numbers are prime in Python. - -### The Main Function - -Breaking down this solution bottom up, - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -This bit of code checks to see if this is the `main` module run. If it is, then it calls the `main` function. -In this case the user input would be a natural number greater than 1. - -```python -def main(args): - try: - x = int(args[0]) - if x < 0: - exit_with_error() - print("Prime" if is_prime(x) else "Composite") - except (IndexError, ValueError): - exit_with_error() -``` - -The first thing the main function does is it tries to parse the user input. -All the user inputs are passed in the `args` variable as a list. In this example -we only want the first parameter which we expect to be a natural number. - -The arg will be a string so we should convert them to an integer first `x = int(args[0])`. -If the integer is less than 0 it's not a valid input so we return an error by calling the -`exit_with_error()` function. - -We then call the main part of our program `print(is_prime(x))` which will check if the integer -is prime and print this out on the terminal for the user. - -Finally we wrap this entire block in a `try ... except`, and we catch two exceptions: `IndexError` -and `ValueError`. `IndexError` will be thrown if `args` is empty, and we try to access `args[0]`. -`ValueError` will be thrown if we try to convert a non-integer string into an integer. -For example if `args[0]` was "a" -> `int("a")`. If any exceptions are raised, then we call -the `exit_with_error()` function. - -### Throw Errors - -```python -def exit_with_error(): - print('Usage: please input a non-negative integer') - sys.exit(1) -``` - -This function prints a message and then exits the script with an error, `sys.exit(1)`. -If any non-zero value is returned then the program didn't complete properly. This function is called -if the user input isn't correct. - -### Prime Numbers - -```python -def is_prime(x): - if (x % 2 == 0 and x is not 2) or (x == 1): - return False - return not bool([n for n in range(3, int(ceil(sqrt(x))+1)) if x % n == 0]) -``` - -Now onto the main part of the program. This is the function that actually checks if the integer is prime: - -```python -if (x % 2 == 0 and x is not 2) or (x == 1): - return False -``` - -This part of the code checks if the integer is divisible by 2 (and not equal 2), -if a number can be divided by 2 it cannot be prime however 2 is a prime number. -If the integer is 1, it also cannot be prime by definition. - -The `%` is called the modulo operator which returns the remainder of a division, for -example `10 % 2 = 0` because 2 divides into 10 five times evenly (`2 * 5 = 10`). However if we had -`11 % 2 = 1` because 2 divides into 11 five times with one remaining (`2 * 5 + 1 = 11`). - -This `x % 2 == 0` is used to check if a number is even, because if it can be evenly -divided by 2 it cannot be prime. If integer is not 1 or divisible by two then we -have do a more thorough check. - -```python -return not bool([n for n in range(3, int(ceil(sqrt(x))+1)) if x % n == 0]) -``` - -This is an example of list comprehension which is a way to generate -lists in Python (usually as "one-liners"). - -Lets break this down. - -```python -for n in range(3, int(ceil(sqrt(x))+1)) -``` - -This `range(3, int(ceil(sqrt(x))+1))` generates a list of integers from 3 to the ceiling of the -square of the integer + 1. Ok that sounds complicated but lets take a look at an example -if x was 17, `sqrt(17) = 4.12310.....` -> `ceil(4.1231) = 4.0 + 1 = 5.0` then we convert 5.0 to an -integer `int(5.0) = 5`. So if x is 17 the range function looks like -`range(3, 5)` = `[3, 4, 5]`. We can do this because of some clever maths which means we only -have to check factors up to the square root of the `x` (17) to see if it has any other factors -besides itself and 1. So then `for n in range(3, int(ceil(sqrt(x))+1))` will loop through -every number in that list. So n will be `3, 4, 5`. The range starts at 3 because x will always -be divisible by 1 and we already checked if it's divisible by 2. - -```python -[n for n in range(3, int(ceil(sqrt(x))+1))] -``` - -This on it's own would create a list of the values of `n` so if `x` was `17` then the line above -would generate the list `[3, 4, 5]`. - -```python -[n for n in range(3, int(ceil(sqrt(x))+1)) if x % n == 0] -``` - -Taking a look at the whole list comprehension including `if x % n == 0` -means the current `n` is only added to the list if the if statement evaluates to `True`, -which is this case is true if `n` divides in `x` evenly. This would make `n` a factor of `x` - -So taking a look at our example if `x` is 17 then the list to loop though would -be `[3, 4, 5]`. - -1st Iteration: - -* `n = 3` -* `17 % 3 = 2` -* Current List = `[]` - -2nd Iteration: - -* `n = 4` -* `17 % 4 = 1` -* Current List = `[]` - -3rd Iteration: - -* `n = 5` -* `17 % 5 = 2` -* Current List = `[]` - -So the final generated list for `x = 17` would be `[]` since none of the number `3, 4, 5` divide -evenly into `17`. - -Taking a look at the entire line: - -```python -return not bool([n for n in range(3, int(ceil(sqrt(x))+1)) if x % n == 0])` -``` - -The `bool()` function converts an object into a `True` or `False` boolean value. -The `not bool(...)` then reverses this value, if `bool("a") = True` then `not bool("a") = False`. -Then we return this value `return not bool(...)`. - -Using our `x = 17` example again `[n for n in range(3, int(ceil(sqrt(x))+1)) if x % n == 0]` = `[]`. -So `return not bool([])` = `return not False` = `return True`, so 17 is prime. - -The list that gets generated stores all factors of x except 1 and `17`. So if the list is empty `x` must be prime. -If it contains any factors then it cannot be prime. - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Prime Numbers in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/prime_number.py). -After that, we should make sure we have the [latest Python interpreter](https://www.python.org/downloads/). -From there, we can run the following command in the terminal: - -`python prime_number.py 3` - -Alternatively, we can copy the solution into an [online Python interpreter](https://www.online-python.com/) and hit run. diff --git a/docs/projects/prime-number/r/index.md b/docs/projects/prime-number/r/index.md deleted file mode 100644 index a9b6ddd268..0000000000 --- a/docs/projects/prime-number/r/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- Veena ManikPrabhu -date: 2020-10-19 -featured-image: prime-number-in-every-language.jpg -last-modified: 2020-10-19 -layout: default -tags: -- prime-number -- r -title: Prime Number in R -title1: Prime -title2: Number in R ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -# Program to check if the input number is prime or not -args<-commandArgs(TRUE) -if(length(args) > 0){ - a1 = args[1] - # Check Numeral only, .. - numbers_only <- function(a) !grepl("\\D", a1) - if(numbers_only(a1) == TRUE){ - if (a1 >= 0){ - a = as.integer(a1) - if(a == 2){ - cat("Prime") - # If 0, or 1 or Even Number - }else if (a == 0 || a == 1 || a %% 2 == 0 ) { - cat("Composite") - }else{ - flag = 1 - r = a %/% 2 - for(i in 2:r) { - if (a %% i == 0) { - flag = 0 - break - } - } - if(flag == 1) { - cat("Prime") - } else { - cat("Composite") - } - } - }else{# Empty Input - cat("Usage: please input a non-negative integer") -} -}else{ # Negative Input - cat("Usage: please input a non-negative integer") -} -}else{ # Empty Input - cat("Usage: please input a non-negative integer") -} - -``` - -{% endraw %} - -Prime Number in [R](/languages/r) was written by: - -- Veena ManikPrabhu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/red/index.md b/docs/projects/prime-number/red/index.md deleted file mode 100644 index b7845ed631..0000000000 --- a/docs/projects/prime-number/red/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Darien Arthur-Gocken -date: 2025-10-30 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-10-30 -layout: default -tags: -- prime-number -- red -title: Prime Number in Red -title1: Prime Number -title2: in Red ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Red](/languages/red) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```red -Red [Title: "Prime Number in Red"] - -prime-number: func [number [integer!]] [ - either number <= 1 [ - print "Composite" - ][ - found?: false - limit: to integer! square-root number - repeat i limit - 1 [ - if (number // (i + 1)) = 0 [ - print "Composite" - found?: true - break - ] - ] - if not found? [print "Prime"] - ] -] - -main: func [arg [string!]] [ - - arg: trim/with arg {'"} - - digit: charset "0123456789" - if not parse arg [opt ["+" | "-"] some digit end] [ - print "Usage: please input a non-negative integer" - exit - ] - - either attempt [arg: to-integer arg][ - ][ - print "Usage: please input a non-negative integer" - exit - ] - - if negative? arg [ - print "Usage: please input a non-negative integer" - exit - ] - - prime-number arg -] - -main system/script/args -``` - -{% endraw %} - -Prime Number in [Red](/languages/red) was written by: - -- Darien Arthur-Gocken - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/rexx/index.md b/docs/projects/prime-number/rexx/index.md deleted file mode 100644 index 7b4fe43fc0..0000000000 --- a/docs/projects/prime-number/rexx/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Sudhanshu Dubey -date: 2020-10-07 -featured-image: prime-number-in-every-language.jpg -last-modified: 2020-10-07 -layout: default -tags: -- prime-number -- rexx -title: Prime Number in Rexx -title1: Prime Number -title2: in Rexx ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Rexx](/languages/rexx) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rexx -/* ARG with source string named in REXX program invocation */ -arg number -If (DATATYPE(number, 'W') == 0) then signal err -If (number < 0) then signal err -isPrime = 1 -if \((number // 2 = 0) & (number \= 2) | (number == 1)) then - do - i = TRUNC(number / 2) - do while(i > 3) - if (number // i == 0) then - isPrime = 0 - i = i - 1 - end - end -else - isPrime = 0 - -if (isPrime == 1) then - say "Prime" -else - say "Composite" -;exit - -Err: -say 'Usage: please input a non-negative integer'; exit - -``` - -{% endraw %} - -Prime Number in [Rexx](/languages/rexx) was written by: - -- Sudhanshu Dubey - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/ruby/index.md b/docs/projects/prime-number/ruby/index.md deleted file mode 100644 index 8eaa78e1f8..0000000000 --- a/docs/projects/prime-number/ruby/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- MSJ -- Ștefan-Iulian Alecu -date: 2024-10-02 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- prime-number -- ruby -title: Prime Number in Ruby -title1: Prime Number -title2: in Ruby ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -require "prime" - -def usage! - abort("Usage: please input a non-negative integer") -end - -number = Integer(ARGV.first, exception: false) - -usage! if number.nil? || number.negative? - -puts Prime.prime?(number) ? "prime" : "composite" - -``` - -{% endraw %} - -Prime Number in [Ruby](/languages/ruby) was written by: - -- MSJ -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/rust/index.md b/docs/projects/prime-number/rust/index.md deleted file mode 100644 index fd3f8da398..0000000000 --- a/docs/projects/prime-number/rust/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- Mallikarjuna S J -- rzuckerm -date: 2019-10-31 -featured-image: prime-number-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- prime-number -- rust -title: Prime Number in Rust -title1: Prime Number -title2: in Rust ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -// Requirement https://sample-programs.therenegadecoder.com/projects/prime-number/ -// Accept a number on command line and print if it is Composite or Prime -// Works till 39 digits, ... - -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please input a non-negative integer"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn main() { - let mut args = args().skip(1); - - // Exit if 1st command-line argument not an positive integer - let input_num: u128 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - if input_num < 2 || (input_num != 2 && input_num % 2 == 0) { - println!("Composite"); - exit(0); - } - - let mut n = 3u128; - while n * n <= input_num { - if input_num % n == 0 { - println!("Composite"); - exit(0); - } - n += 2; - } - println!("Prime"); -} - -``` - -{% endraw %} - -Prime Number in [Rust](/languages/rust) was written by: - -- Mallikarjuna S J -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/swift/index.md b/docs/projects/prime-number/swift/index.md deleted file mode 100644 index 691f50eea4..0000000000 --- a/docs/projects/prime-number/swift/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Vidish Kumar -date: 2026-03-10 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-03-10 -layout: default -tags: -- prime-number -- swift -title: Prime Number in Swift -title1: Prime Number -title2: in Swift ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = "Usage: please input a non-negative integer" - -if CommandLine.arguments.count != 2 { - print(usage) - exit(0) -} - -guard let number = Int(CommandLine.arguments[1]), number >= 0 else { - print(usage) - exit(0) -} - -if number < 2 { - print("composite") - exit(0) -} - -var isPrime = true -let limit = Int(Double(number).squareRoot()) - -if limit >= 2 { - for i in 2...limit { - if number % i == 0 { - isPrime = false - break - } - } -} - -print(isPrime ? "prime" : "composite") -``` - -{% endraw %} - -Prime Number in [Swift](/languages/swift) was written by: - -- Vidish Kumar - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/tcl/index.md b/docs/projects/prime-number/tcl/index.md deleted file mode 100644 index f795c6114f..0000000000 --- a/docs/projects/prime-number/tcl/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- prime-number -- tcl -title: Prime Number in Tcl -title1: Prime Number -title2: in Tcl ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 -package require math::numtheory - -proc usage {} { - puts stderr {Usage: please input a non-negative integer} - exit 1 -} - -proc isNonNegativeInteger {s} { - if {[catch {expr {int($s)}} n]} { - return 0 - } - if {$s eq ""} { return 0 } - if {![string is integer -strict $s]} { - return 0 - } - return [expr {$n >= 0}] -} - -if {$argc != 1} { usage } - -set input [string trim [lindex $argv 0]] -if {![isNonNegativeInteger $input]} { usage } - -set n $input -if {$n < 2} { - puts "composite" -} elseif {[math::numtheory::isprime $n]} { - puts "prime" -} else { - puts "composite" -} - - -``` - -{% endraw %} - -Prime Number in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/ti-basic/index.md b/docs/projects/prime-number/ti-basic/index.md deleted file mode 100644 index ba08aa2ead..0000000000 --- a/docs/projects/prime-number/ti-basic/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-02 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-02-02 -layout: default -tags: -- prime-number -- ti-basic -title: Prime Number in TI-BASIC -title1: Prime Number -title2: in TI-BASIC ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -"0123456789"->Str2 -length(Str1)->L -L<1->E -0->D -0->V -1->N -1->S -While E=0 and N<=L - sub(Str1,N,1)->C - inString(Str2,C)-1->K - If C="+" or C="-" - Then - D>0->E - If C="-" - Then 0-S->S - End - Else - K<0->E - D+1->D - V*10+K*S->V - End - N+1->N -End -If E or D<1 or V<0 Then Disp "Usage: please input a non-negative integer" -Else - V=2 or (V>=3 and remainder(V,2)~=0)->P - 3->N - sqrt(V)->Q - While P and N<=Q - remainder(V,N)~=0->P - N+2->N - End - If P Then Disp "prime" - Else Disp "composite" - End -End - -``` - -{% endraw %} - -Prime Number in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/typescript/index.md b/docs/projects/prime-number/typescript/index.md deleted file mode 100644 index a2737bf3ea..0000000000 --- a/docs/projects/prime-number/typescript/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Meet Thakur -- rzuckerm -date: 2023-10-05 -featured-image: prime-number-in-every-language.jpg -last-modified: 2023-10-21 -layout: default -tags: -- prime-number -- typescript -title: Prime Number in TypeScript -title1: Prime Number -title2: in TypeScript ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function isPrime(num: number): boolean { - if (num < 2) { - return false; - } - for (let i = 2; i <= Math.sqrt(num); i++) { - if (num % i === 0) { - return false; - } - } - return true; -} - -function main() { - if (process.argv.length !== 3) { - console.log('Usage: please input a non-negative integer'); - return; - } - - const inputNum = parseFloat(process.argv[2]); - - if (isNaN(inputNum) || inputNum < 0 || inputNum % 1 !== 0) { - console.log('Usage: please input a non-negative integer'); - return; - } - - if (isPrime(inputNum)) { - console.log('prime'); - } else { - console.log('composite'); - } -} -main(); - -``` - -{% endraw %} - -Prime Number in [TypeScript](/languages/typescript) was written by: - -- Meet Thakur -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/visual-basic/index.md b/docs/projects/prime-number/visual-basic/index.md deleted file mode 100644 index f143178201..0000000000 --- a/docs/projects/prime-number/visual-basic/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: prime-number-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- prime-number -- visual-basic -title: Prime Number in Visual Basic -title1: Prime Number in -title2: Visual Basic ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module PrimeNumber - - Private Sub ShowUsage() - Console.WriteLine("Usage: please input a non-negative integer") - Environment.Exit(1) - End Sub - - Private Function IsPrime(value As ULong) As Boolean - - If value <= 1UL Then Return False - If value <> 2UL AndAlso value Mod 2UL = 0 Then Return False - - Dim limit As ULong = CULng(Math.Sqrt(value)) - - Dim i As ULong = 3UL - While i <= limit - - If value Mod i = 0UL Then - Return False - End If - - i += 2UL - - End While - - Return True - - End Function - - - Public Function Main(args As String()) As Integer - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim value As ULong - - If Not ULong.TryParse(args(0), value) Then - ShowUsage() - End If - - Console.WriteLine((If(IsPrime(value), "Prime", "Composite"))) - - Return 0 - - End Function - -End Module -``` - -{% endraw %} - -Prime Number in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/prime-number/wren/index.md b/docs/projects/prime-number/wren/index.md deleted file mode 100644 index 708da05dd5..0000000000 --- a/docs/projects/prime-number/wren/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-26 -featured-image: prime-number-in-every-language.jpg -last-modified: 2025-01-26 -layout: default -tags: -- prime-number -- wren -title: Prime Number in Wren -title1: Prime Number -title2: in Wren ---- - - - -Welcome to the [Prime Number](/projects/prime-number) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -import "os" for Process - -var args = Process.arguments - -if (args.count < 1 || args[0].count < 1) { - System.print("Usage: please input a non-negative integer") - Fiber.suspend() -} - -var n = Num.fromString(args[0]) - -if (n == null || n < 0 || n.floor != n) { - System.print("Usage: please input a non-negative integer") - Fiber.suspend() -} - -if (n < 2) { - System.print("composite") - Fiber.suspend() -} - -if (n == 2) { - System.print("prime") - Fiber.suspend() -} - -for (i in 2..(n.sqrt.floor)) { - if (n % i == 0) { - System.print("composite") - Fiber.suspend() - } -} -System.print("prime") - -``` - -{% endraw %} - -Prime Number in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/algol60/index.md b/docs/projects/quick-sort/algol60/index.md deleted file mode 100644 index 7dfbb27df7..0000000000 --- a/docs/projects/quick-sort/algol60/index.md +++ /dev/null @@ -1,309 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-18 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- quick-sort -title: Quick Sort in ALGOL 60 -title1: Quick Sort -title2: in ALGOL 60 ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of at least two integers " - "to sort in the format \"1, 2, 3, 4, 5\"\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Output integer array; - procedure outIntegerArray(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i; - for i := 1 step 1 until arrLen do - begin - if i > 1 then outstring(1, ", "); - outIntegerNoSpace(arr[i]) - end; - - if arrLen > 0 then outstring(1, "\n") - end outIntegerArray; - - comment Source https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme; - procedure quickSort(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - procedure quickSortRec(lo, hi); - value lo, hi; - integer lo, hi; - begin - integer p; - - if lo < hi & lo > 0 then - begin - p := partition(lo, hi); - quickSortRec(lo, p - 1); - quickSortRec(p + 1, hi) - end - end quickSortRec; - - integer procedure partition(lo, hi); - value lo, hi; - integer lo, hi; - begin - integer i, j, pivot; - - comment Choose the last element as the pivot; - pivot := arr[hi]; - - comment Temporary pivot index; - i := lo; - - for j := lo step 1 until hi - 1 do - begin - comment If the current element is less than or equal to the - pivot; - if arr[j] <= pivot then - begin - comment Swap the current element with the element at the - temporary pivot index and move the temporary pivot - index forward; - swap(i, j); - i := i + 1 - end - end; - - comment Swap the pivot with the last element; - swap(i, hi); - - partition := i - end partition; - - procedure swap(i, j); - value i, j; - integer i, j; - begin - integer t; - - t := arr[i]; - arr[i] := arr[j]; - arr[j] := t - end swap; - - quickSortRec(1, arrLen) - end quickSort; - - integer argc, arrLen; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 2 then usage; - - comment Quick sort input and output result; - quickSort(arr, arrLen); - outIntegerArray(arr, arrLen) -end - -``` - -{% endraw %} - -Quick Sort in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/algol68/index.md b/docs/projects/quick-sort/algol68/index.md deleted file mode 100644 index eaf451df46..0000000000 --- a/docs/projects/quick-sort/algol68/index.md +++ /dev/null @@ -1,235 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-29 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- quick-sort -title: Quick Sort in ALGOL 68 -title1: Quick Sort -title2: in ALGOL 68 ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a list of at least two integers to sort in the format ""1, 2, 3, 4, 5""")) -); - -COMMENT -Source: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme -COMMENT -PROC quick sort = (REF []INT values) VOID: -( - quick sort rec(values, 1, UPB values) -); - -PROC quick sort rec = (REF []INT values, INT lo, INT hi) VOID: -( - IF lo < hi AND lo >= 1 - THEN - # Partition array and get pivot value # - INT p := partition(values, lo, hi); - - # Sort left side of partition # - quick sort rec(values, lo, p - 1); - - # Sort right side of partition # - quick sort rec(values, p + 1, hi) - FI -); - -PROC partition = (REF []INT values, INT lo, INT hi) INT: -( - # Choose last value as pivot # - INT pivot = values[hi]; - - # Set temporary pivot index # - INT i := lo - 1; - - # Swap elements less than or equal to pivot, and increment temporary index # - FOR j FROM lo TO hi - 1 - DO - IF values[j] <= pivot - THEN - i +:= 1; - swap(values, i, j) - FI - OD; - - # Move pivot to correct position # - i +:= 1; - swap(values, i, hi); - - i -); - -PROC swap = (REF []INT values, INT a, INT b) VOID: -( - INT temp := values[a]; - values[a] := values[b]; - values[b] := temp -); - -PROC show list values = (REF []INT values) VOID: -( - INT n = UPB values; - FOR k TO n - DO - IF k > 1 - THEN - print(", ") - FI; - - print(whole(values[k], 0)) - OD; - - IF n > 0 - THEN - print(newline) - FI -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result OR UPB values < 2 -THEN - usage; - stop -FI; - -# Do quick sort and show results # -quick sort(values); -show list values(values) - -``` - -{% endraw %} - -Quick Sort in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/awk/index.md b/docs/projects/quick-sort/awk/index.md deleted file mode 100644 index 65f965c2a3..0000000000 --- a/docs/projects/quick-sort/awk/index.md +++ /dev/null @@ -1,146 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-21 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2025-04-21 -layout: default -tags: -- awk -- quick-sort -title: Quick Sort in AWK -title1: Quick Sort -title2: in AWK ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -# Source: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme -function quick_sort(arr, arr_len) { - quick_sort_rec(arr, 1, arr_len) -} - -function quick_sort_rec(arr, lo, hi, p) { - if (lo < hi && lo >= 1) { - # Partition array and get pivot value - p = partition(arr, lo, hi) - - # Sort left side of partition - quick_sort_rec(arr, lo, p - 1) - - # Sort right side of partition - quick_sort_rec(arr, p + 1, hi) - } -} - -function partition(arr, lo, hi, i, j, pivot) { - # Choose last value as pivot - pivot = arr[hi] - - # Set temporary pivot index - i = lo - 1 - - # Swap elements less than or equal to pivot, and increment temporary index - for (j = lo; j < hi; j++) { - if (arr[j] <= pivot) { - i++ - swap(arr, i, j) - } - } - - # Move pivot to correct position - i++ - swap(arr, i, hi) - - return i -} - -function swap(arr, i, j, t) { - t = arr[i] - arr[i] = arr[j] - arr[j] = t -} - -function show_array(arr, idx, s) { - s = "" - for (idx in arr) { - if (s) { - s = s ", " - } - s = s arr[idx] - } - - print s -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], arr) - arr_len = length(arr) - if (!arr_len || arr_len < 2) { - usage() - } - - quick_sort(arr, arr_len) - show_array(arr) -} - -``` - -{% endraw %} - -Quick Sort in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/bash/index.md b/docs/projects/quick-sort/bash/index.md deleted file mode 100644 index 4f2235a392..0000000000 --- a/docs/projects/quick-sort/bash/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- tehtbl -- thetbl -date: 2019-10-14 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2019-10-14 -layout: default -tags: -- bash -- quick-sort -title: Quick Sort in Bash -title1: Quick Sort -title2: in Bash ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -# based on https://stackoverflow.com/questions/7442417/how-to-sort-an-array-in-bash - -# quicksorts positional arguments -# return is in array qsort_ret -# Note: iterative, NOT recursive! :) -# First argument is a function name that takes two arguments and compares them -qsort_iter() { - (($#<=1)) && return 0 - local compare_fun=$1 - shift - local stack=( 0 $(($#-1)) ) beg end i pivot smaller larger - qsort_ret=("$@") - while ((${#stack[@]})); do - beg=${stack[0]} - end=${stack[1]} - stack=( "${stack[@]:2}" ) - smaller=() larger=() - pivot=${qsort_ret[beg]} - for ((i=beg+1;i<=end;++i)); do - if "$compare_fun" "${qsort_ret[i]}" "$pivot"; then - smaller+=( "${qsort_ret[i]}" ) - else - larger+=( "${qsort_ret[i]}" ) - fi - done - qsort_ret=( "${qsort_ret[@]:0:beg}" "${smaller[@]}" "$pivot" "${larger[@]}" "${qsort_ret[@]:end+1}" ) - if ((${#smaller[@]}>=2)); then stack+=( "$beg" "$((beg+${#smaller[@]}-1))" ); fi - if ((${#larger[@]}>=2)); then stack+=( "$((end-${#larger[@]}+1))" "$end" ); fi - done -} - -# compare function -compare_str() { [[ $1 < $2 ]]; } - -ERROR="Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - -#Validation to fit criteria -if [ "$#" != "1" ]; then echo $ERROR; exit 1; fi; #wrong input -if [[ ! "$1" =~ "," ]]; then echo $ERROR; exit 1; fi; #wrong format - -array=($(echo $@ | tr ", " " ")) - -if [ "${array[0]}" == "" ]; then echo $ERROR; exit 1; fi; #empty input -if [ "${#array[@]}" == "1" ]; then echo $ERROR; exit 1; fi; #not a list - -qsort_iter compare_str "${array[@]}" -arrayString=${qsort_ret[@]} -echo "${arrayString// /, }" - -exit 0 - -``` - -{% endraw %} - -Quick Sort in [Bash](/languages/bash) was written by: - -- tehtbl -- thetbl - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/beef/index.md b/docs/projects/quick-sort/beef/index.md deleted file mode 100644 index 52ca5549de..0000000000 --- a/docs/projects/quick-sort/beef/index.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-04 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2024-02-04 -layout: default -tags: -- beef -- quick-sort -title: Quick Sort in Beef -title1: Quick Sort -title2: in Beef ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace QuickSort; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Reference: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme - public static void QuickSort(List arr) - where int : operator T <=> T - { - QuickSortRec(arr, 0, arr.Count - 1); - } - - public static void QuickSortRec(List arr, int lo, int hi) - where int : operator T <=> T - { - // Exit if no enough elements - if (lo >= hi || lo < 0) - { - return; - } - - // Get partition - int p = Partition(arr, lo, hi); - - // Sort left side of partition - QuickSortRec(arr, lo, p - 1); - - // Sort right side of partition - QuickSortRec(arr, p + 1, hi); - } - - public static int Partition(List arr, int lo, int hi) - where int : operator T <=> T - { - // Set pivot to last element - T pivot = arr[hi]; - - // Set temporary pivot index - int i = lo - 1; - - for (int j in lo..(List arr) - { - String line = scope .(); - for (T val in arr) - { - if (!line.IsEmpty) - { - line += ", "; - } - - line.AppendF("{}", val); - } - - Console.WriteLine(line); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - List arr = scope .(); - switch (ParseIntList(args[0], arr)) - { - case .Ok: - if (arr.Count < 2) - { - Usage(); - } - case .Err: - Usage(); - } - - QuickSort(arr); - ShowList(arr); - return 0; - } -} - -``` - -{% endraw %} - -Quick Sort in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/c-plus-plus/index.md b/docs/projects/quick-sort/c-plus-plus/index.md deleted file mode 100644 index ad913023a3..0000000000 --- a/docs/projects/quick-sort/c-plus-plus/index.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Sumathi Varadharajan -- Ștefan-Iulian Alecu -date: 2019-11-01 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- quick-sort -title: Quick Sort in C++ -title1: Quick Sort -title2: in C++ ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5")" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.size() < 2 ? std::nullopt : std::make_optional(out); -} - -template - requires std::sortable> -void quick_sort(R&& r) { - auto first = ranges::begin(r); - auto last = ranges::end(r); - - auto n = std::distance(first, last); - if (n <= 1) return; - - auto pivot = first + n / 2; - - std::nth_element(first, pivot, last); - - quick_sort(ranges::subrange(first, pivot)); - quick_sort(ranges::subrange(std::next(pivot), last)); -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - auto vec = parse_vec(argv[1]); - if (!vec) usage(); - - quick_sort(*vec); - - for (const char* sep = ""; int val : *vec) { - std::cout << std::exchange(sep, ", ") << val; - } - std::cout << "\n"; -} - -``` - -{% endraw %} - -Quick Sort in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Sumathi Varadharajan -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/c-sharp/index.md b/docs/projects/quick-sort/c-sharp/index.md deleted file mode 100644 index 0f5d70b100..0000000000 --- a/docs/projects/quick-sort/c-sharp/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-30 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- quick-sort -title: Quick Sort in C# -title1: Quick Sort -title2: in C# ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Buffers; - -if (args is not [var input] || !TryParseList(input.AsSpan(), out var numbers)) - return ExitWithUsage(); - -Span span = CollectionsMarshal.AsSpan(numbers); -QuickSort(span); - -Console.WriteLine(string.Join(", ", numbers)); -return 0; - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return numbers.Count > 1; -} - -static void QuickSort(Span span) -{ - if (span.Length <= 1) - return; - - int lo = 0; - int hi = span.Length - 1; - - Sort(span, lo, hi); - - static void Sort(Span s, int lo, int hi) - { - while (lo < hi) - { - int p = Partition(s, lo, hi); - - // Tail recursion elimination: sort smaller side first - if (p - lo < hi - p) - { - Sort(s, lo, p - 1); - lo = p + 1; - } - else - { - Sort(s, p + 1, hi); - hi = p - 1; - } - } - } - - static int Partition(Span s, int lo, int hi) - { - int pivot = s[hi]; - int i = lo; - - for (int j = lo; j < hi; j++) - { - if (s[j] <= pivot) - { - (s[i], s[j]) = (s[j], s[i]); - i++; - } - } - - (s[i], s[hi]) = (s[hi], s[i]); - return i; - } -} - -static int ExitWithUsage() -{ - Console.WriteLine( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - ); - return 1; -} - -``` - -{% endraw %} - -Quick Sort in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/c/index.md b/docs/projects/quick-sort/c/index.md deleted file mode 100644 index ebd1ec1c5c..0000000000 --- a/docs/projects/quick-sort/c/index.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -authors: -- LezendarySandwich -- Ștefan-Iulian Alecu -date: 2019-10-20 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- quick-sort -title: Quick Sort in C -title1: Quick -title2: Sort in C ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -long long get_val(int tmp[], int len) -{ - long long value = 0, mult = 1; - for (int i = len - 1; i > -1; --i) - { - if (tmp[i] == ' ' - '0') - { - printf("Usage: please provide a list of at least two integers to " - "sort in the format \"1, 2, 3, 4, 5\"\n"); - exit(0); - } - value += tmp[i] * mult; - mult *= 10; - } - return value; -} - -void swap(long long *a, long long *b) -{ - int t = *a; - *a = *b; - *b = t; -} - -int partition(long long arr[], int low, int high) -{ - long long pivot = arr[high]; - int i = low - 1; - - for (int j = low; j <= high - 1; j++) - { - if (arr[j] < pivot) - { - i++; - swap(&arr[i], &arr[j]); - } - } - swap(&arr[i + 1], &arr[high]); - return i + 1; -} - -void quickSort(long long arr[], int low, int high) -{ - if (low < high) - { - int pi = partition(arr, low, high); - quickSort(arr, low, pi - 1); - quickSort(arr, pi + 1, high); - } -} - -void print(long long arr[], int size) -{ - for (int i = 0; i < size; i++) - { - printf("%lld", arr[i]); - if (i != size - 1) - printf(", "); - } - - printf("\n"); -} - -int main(int argc, char **argv) -{ - while (argv[1] == NULL || strlen(argv[1]) == 0) - { - printf("Usage: please provide a list of at least two integers to sort " - "in the format \"1, 2, 3, 4, 5\"\n"); - return 0; - } - int len = strlen(argv[1]); - int tmp[10]; - int ind = 0; - int pos = 0; - long long arr[100000]; - - for (int i = 0; i < len; ++i) - { - if (argv[1][i] == ',') - { - long long val = get_val(tmp, ind); - ind = 0; - i++; - arr[pos++] = val; - continue; - } - tmp[ind++] = argv[1][i] - '0'; - } - arr[pos++] = get_val(tmp, ind); - if (pos == 1) - { - printf("Usage: please provide a list of at least two integers to sort " - "in the format \"1, 2, 3, 4, 5\"\n"); - return 0; - } - - quickSort(arr, 0, pos - 1); - print(arr, pos); -} -``` - -{% endraw %} - -Quick Sort in [C](/languages/c) was written by: - -- LezendarySandwich -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/cobol/index.md b/docs/projects/quick-sort/cobol/index.md deleted file mode 100644 index be0b38f82d..0000000000 --- a/docs/projects/quick-sort/cobol/index.md +++ /dev/null @@ -1,245 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-21 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-04-21 -layout: default -tags: -- cobol -- quick-sort -title: Quick Sort in COBOL -title1: Quick Sort -title2: in COBOL ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. quick-sort. - -data division. -working-storage section. - -78 max-entries value 1000. -78 stack-size value 64. - -01 argument-string pic x(32768). -01 token pic x(32). -01 scan-ptr binary-long value 1. -01 list-size binary-long value 0. - -01 array-a. - 05 item occurs 1 to max-entries - depending on list-size - pic s9(9). - -01 stack. - 05 stack-ptr binary-long value 0. - 05 frame occurs stack-size. - 10 low-bound binary-long. - 10 high-bound binary-long. - -01 low binary-long. -01 high binary-long. -01 mid binary-long. -01 i binary-long. -01 j binary-long. - -01 pivot pic s9(9). -01 temp pic s9(9). -01 out-num pic -(10)9. - -procedure division. - -main. - perform initialize-program - perform read-input - - if list-size < 2 - perform display-usage - else - perform quicksort - end-if - - perform display-results - stop run. - -*> ------------------------- -initialize-program. - move 1 to scan-ptr - move 0 to list-size. - -*> ------------------------- -read-input. - accept argument-string from argument-value - - if function trim(argument-string) = spaces - perform display-usage - end-if - - perform tokenize. - -tokenize. - perform until scan-ptr > length of argument-string - move spaces to token - - unstring argument-string - delimited by "," - into token - with pointer scan-ptr - end-unstring - - if function trim(token) not = spaces - if function test-numval(token) not = 0 - perform display-usage - end-if - - add 1 to list-size - if list-size > max-entries - perform display-usage - end-if - - move function numval(token) to item(list-size) - end-if - end-perform. - -*> ------------------------- -quicksort. - move 1 to stack-ptr - move 1 to low-bound(1) - move list-size to high-bound(1) - - perform until stack-ptr = 0 - - move low-bound(stack-ptr) to low - move high-bound(stack-ptr) to high - subtract 1 from stack-ptr - - perform until low >= high - - *> -------- pivot (median of 3) -------- - compute mid = low + (high - low) / 2 - - if item(low) > item(mid) - move item(low) to temp - move item(mid) to item(low) - move temp to item(mid) - end-if - - if item(low) > item(high) - move item(low) to temp - move item(high) to item(low) - move temp to item(high) - end-if - - if item(mid) > item(high) - move item(mid) to temp - move item(high) to item(mid) - move temp to item(high) - end-if - - move item(mid) to pivot - - *> -------- partition -------- - move low to i - move high to j - - perform until i > j - - perform until i > high or item(i) >= pivot - add 1 to i - end-perform - - perform until j < low or item(j) <= pivot - subtract 1 from j - end-perform - - if i <= j - move item(i) to temp - move item(j) to item(i) - move temp to item(j) - add 1 to i - subtract 1 from j - end-if - - end-perform - - *> -------- stack management -------- - if (j - low) < (high - i) - - if i < high and stack-ptr < stack-size - add 1 to stack-ptr - move i to low-bound(stack-ptr) - move high to high-bound(stack-ptr) - end-if - - move j to high - - else - - if low < j and stack-ptr < stack-size - add 1 to stack-ptr - move low to low-bound(stack-ptr) - move j to high-bound(stack-ptr) - end-if - - move i to low - - end-if - - end-perform - - end-perform. - -*> ------------------------- -display-results. - perform varying i from 1 by 1 until i > list-size - move item(i) to out-num - display function trim(out-num) with no advancing - - if i < list-size - display ", " with no advancing - end-if - end-perform - - display space. - -*> ------------------------- -display-usage. - display 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - stop run. - -``` - -{% endraw %} - -Quick Sort in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/commodore-basic/index.md b/docs/projects/quick-sort/commodore-basic/index.md deleted file mode 100644 index e682e1dc35..0000000000 --- a/docs/projects/quick-sort/commodore-basic/index.md +++ /dev/null @@ -1,195 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-10 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2023-10-14 -layout: default -tags: -- commodore-basic -- quick-sort -title: Quick Sort in Commodore BASIC -title1: Quick Sort in -title2: Commodore BASIC ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM -10 DIM A(99) -15 DIM SK(299): REM Need to potentially stack 3 values for each array element -20 GOSUB 2000: REM Get array -25 REM Error if invalid, not end of input/value, or less that 2 items -30 IF V = 0 OR C >= 0 OR NA < 2 THEN GOTO 200 -40 SP = -1: GOSUB 3000: REM Perform quick sort -50 GOSUB 3500: REM Show array -60 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide a list of at least two integers to sort "; -220 PRINT "in the format "; Q$; "1, 2, 3, 4, 5"; Q$ -230 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Quick sort -3001 REM Commodore Basic does not really support recursion because everything -3002 REM is a global variable. However, recursion can be simulated with -3003 REM a "stack". This "stack" is just an array, SK, and a stack index, SP. -3004 REM Source: -3005 REM https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme -3006 REM Inputs: -3007 REM - A contains array to sort -3008 REM - NA contains size of array -3009 REM Outputs: A contains sorted array -3010 LO = 0 -3020 HI = NA - 1 -3030 REM Recursive portion of algorithm -3031 REM Inputs: -3032 REM - A contains array to sort -3033 REM - LO contains low index -3034 REM - HI contains high index -3035 REM Outputs: A contains partially sorted array -3040 IF LO >= HI OR LO < 0 THEN RETURN -3050 GOSUB 3300: REM Parition array and get pivot index (P) -3060 SP = SP + 1: SK(SP) = LO: REM Push LO -3070 SP = SP + 1: SK(SP) = HI: REM Push HI -3080 SP = SP + 1: SK(SP) = P: REM Push P -3090 HI = P - 1: GOSUB 3030: REM Sort left side of partition -3100 P = SK(SP): SP = SP - 1: REM Pop P -3110 HI = SK(SP): SP = SP - 1: REM Pop HI -3120 SP = SP + 1: SK(SP) = HI: REM Push HI -3130 SP = SP + 1: SK(SP) = P: REM Push P -3140 LO = P + 1: GOSUB 3030: REM Sort right side of partition -3150 SP = SP - 1: REM Pop P (don't store) -3160 HI = SK(SP): SP = SP - 1: REM Pop HI -3170 LO = SK(SP): SP = SP - 1: REM Pop LO -3180 RETURN -3300 REM Partition array -3301 REM Inputs: -3302 REM - A contains array to partition -3303 REM - LO contains low index -3304 REM - HI contains high index -3305 REM Outputs: -3306 REM - A contains partitioned array -3307 REM - P contains pivot index -3310 PV = A(HI): REM Choose last value as pivot -3320 P = LO - 1: REM Set temp pivot index -3325 REM Swap elements less than or equal to pivot, and increment temp index -3330 FOR J = LO TO HI - 1 -3340 IF A(J) > PV THEN GOTO 3390 -3350 P = P + 1 -3360 T = A(J) -3370 A(J) = A(P) -3380 A(P) = T -3390 NEXT J -3395 REM Move pivot to correct position -3400 P = P + 1 -3410 T = A(HI) -3420 A(HI) = A(P) -3430 A(P) = T -3440 RETURN -3500 REM Display array -3501 REM A contains array -3502 REM NA contains size of array -3510 IF NA < 1 THEN GOTO 3590 -3520 FOR I = 0 TO NA - 1 -3530 S$ = STR$(A(I)) -3540 IF A(I) >= 0 THEN S$ = MID$(S$, 2): REM strip leading space -3550 PRINT S$; -3560 IF I < (NA - 1) THEN PRINT ", "; -3570 NEXT I -3580 PRINT -3590 RETURN - -``` - -{% endraw %} - -Quick Sort in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/dart/index.md b/docs/projects/quick-sort/dart/index.md deleted file mode 100644 index 2f5b989ac4..0000000000 --- a/docs/projects/quick-sort/dart/index.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -authors: -- Oxymora -date: 2019-10-28 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2019-11-04 -layout: default -tags: -- dart -- quick-sort -title: Quick Sort in Dart -title1: Quick Sort -title2: in Dart ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart - -import 'dart:io'; - -/** - * - * Merge sort Algorithm from introduction to algorithm - */ - -quicksort(List lst,int start,int end){ - if(start < end){ - - int mid = partition(lst,start,end); - //How to use recursive calls - //Divide and conquer - quicksort(lst, start, mid-1); - quicksort(lst, mid, end); - } -} - -partition(List lst,int start,int end){ - //Sort the array accordingly to the pivot_element - var pivot_element = lst[end]; - var start_position = start -1; - for (var i = start; i < end; i++){ - if(lst[i] <= pivot_element){ - start_position++; - swap(lst, start_position, i); - } - } - swap(lst, start_position+1, end); - return start_position+1; -} - -swap(List lst, int position, int position2){ - var tmp = lst[position]; - lst[position] = lst[position2]; - lst[position2] = tmp; -} - -ListparseInput(List input){ - List lst = []; - var inputString = input.join().replaceAll(" ", "").replaceAll("'", "").split(","); - for(var stringNumber in inputString){ - lst.add(int.parse(stringNumber)); - } - return lst; -} - -exitWithError() { - print( - 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - exit(1); -} - - -main(List args) { - - try { - List lst = parseInput(args); - if (lst.length <= 1) exitWithError(); - quicksort(lst, 0, lst.length - 1); - print(lst.join(", ")); - }catch (e) { - exitWithError(); - } -} - -``` - -{% endraw %} - -Quick Sort in [Dart](/languages/dart) was written by: - -- Oxymora - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/euphoria/index.md b/docs/projects/quick-sort/euphoria/index.md deleted file mode 100644 index c765ce4924..0000000000 --- a/docs/projects/quick-sort/euphoria/index.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2023-02-27 -layout: default -tags: -- euphoria -- quick-sort -title: Quick Sort in Euphoria -title1: Quick Sort -title2: in Euphoria ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"\n" - ) - abort(0) -end procedure - -procedure show_list_values(sequence values) - if length(values) > 0 - then - sequence format = repeat_pattern("%d, ", length(values)) - sequence s = sprintf(format[1..$-2], values) - printf(STDOUT, "%s\n", {s}) - end if -end procedure - -function quick_sort(sequence values) - -- Source: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme - - -- Only sort if enough values - integer n = length(values) - if n <= 1 - then - return values - end if - - -- Choose last value as pivot - integer pivot = values[$] - - -- Set temporary pivot index - integer i = 0 - - -- Swap elements less than or equal to pivot, and increment temporary index - integer temp - for j = 1 to n - 1 - do - if values[j] <= pivot - then - i += 1 - temp = values[i] - values[i] = values[j] - values[j] = temp - end if - end for - - -- Move pivot to correct position - i += 1 - values[$] = values[i] - values[i] = pivot - - -- Combine sorted left side, partition value, and sorted right side - return quick_sort(values[1..i - 1]) & values[i] & quick_sort(values[i + 1..$]) -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int_list(argv[4]) -sequence values = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] or length(values) < 2 -then - usage() -end if - --- Do quick sort and show results -values = quick_sort(values) -show_list_values(values) - -``` - -{% endraw %} - -Quick Sort in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/f-sharp/index.md b/docs/projects/quick-sort/f-sharp/index.md deleted file mode 100644 index cd2a7480cb..0000000000 --- a/docs/projects/quick-sort/f-sharp/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- quick-sort -title: Quick Sort in F# -title1: Quick Sort -title2: in F# ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module QuickSort = - let rec private sort = - function - | [] -> [] - | pivot :: rest -> - let smaller, greater = rest |> List.partition (fun x -> x <= pivot) - - (sort smaller) @ (pivot :: sort greater) - - let run numbers = - numbers |> sort |> List.map string |> String.concat ", " |> Ok - -module Result = - let toOption = - function - | Ok x -> Some x - | Error _ -> None - -module Helpers = - let private (|IntList|_|) (s: string) = - let ns = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) - |> Array.toList - |> List.map (fun p -> - match Int32.TryParse(p.Trim()) with - | true, n -> Ok n - | false, _ -> Error $"Invalid integer: '{p}'") - |> List.choose Result.toOption - - if ns.Length >= 2 then Some ns else None - - let parseArgs argv = - match argv with - | [| IntList numbers |] -> Ok numbers - | _ -> Error "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Result.bind QuickSort.run |> Helpers.handleResult - -``` - -{% endraw %} - -Quick Sort in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/go/index.md b/docs/projects/quick-sort/go/index.md deleted file mode 100644 index a2b7410ae2..0000000000 --- a/docs/projects/quick-sort/go/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-03-17 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2019-03-25 -layout: default -tags: -- go -- quick-sort -title: Quick Sort in Go -title1: Quick Sort -title2: in Go ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "encoding/json" - "fmt" - "os" - "regexp" - "strconv" - "strings" -) - -func quickSort(list []int) []int { - if len(list) <= 0 { - return []int{} - } - - var left []int - var right []int - pivot := len(list) / 2 - for i, n := range list { - if i == pivot { - continue - } - if n < list[pivot] { - left = append(left, n) - } else { - right = append(right, n) - } - } - left = quickSort(left) - right = quickSort(right) - return append(append(left, list[pivot]), right...) -} - -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - if len(list) < 2 { - exitWithError() - } - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} - -func sliceIntToString(list []int) (out string) { - bytes, _ := json.Marshal(list) - out = strings.Replace(string(bytes), ",", ", ", -1) - out = strings.Trim(out, "[]") - return -} - -func exitWithError() { - fmt.Println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - nums := strToSliceInt(os.Args[1]) - nums = quickSort(nums) - fmt.Println(sliceIntToString(nums)) -} - -``` - -{% endraw %} - -Quick Sort in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/haskell/index.md b/docs/projects/quick-sort/haskell/index.md deleted file mode 100644 index b6d5e1fd3f..0000000000 --- a/docs/projects/quick-sort/haskell/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-12-04 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2019-03-26 -layout: default -tags: -- haskell -- quick-sort -title: Quick Sort in Haskell -title1: Quick Sort -title2: in Haskell ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Text.Read -import System.Environment -import System.Exit (exitWith, ExitCode(ExitFailure)) -import Data.List (intercalate) - - -quickSort :: Ord a => [a] -> [a] -quickSort [] = [] -quickSort (x:xs) = - let left = quickSort $ filter (<= x) xs - right = quickSort $ filter (> x) xs - in left ++ [x] ++ right - - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - --- Ensure that a list contains at least two elements -verifyListLength :: Ord a => [a] -> Maybe [a] -verifyListLength [] = Nothing -verifyListLength [x] = Nothing -verifyListLength (x:xs) = Just (x:xs) - -listToString :: [Int] -> String -listToString = intercalate ", " . map show - - -main :: IO () -main = do - args <- getArgs - let xs = headMaybe args >>= stringToListMaybe >>= verifyListLength - case xs of - Nothing -> do - putStrLn "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exitWith $ ExitFailure 1 - Just xs -> putStrLn $ listToString $ quickSort xs - - -``` - -{% endraw %} - -Quick Sort in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/index.md b/docs/projects/quick-sort/index.md deleted file mode 100644 index 490c8340a9..0000000000 --- a/docs/projects/quick-sort/index.md +++ /dev/null @@ -1,191 +0,0 @@ ---- -date: 2018-12-04 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- quick-sort -title: Quick Sort -title1: Quick -title2: Sort ---- - - - -Welcome to the Quick Sort page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -Quick sort is an algorithm that works by dividing a list into smaller lists. -It recursively partially sorts and divides each sublist into further lists until it -reaches the base case of a list that is either empty or contains only a single element, because -those cases are by definition already sorted. After that it concatenates all of the sublists -together into a single sorted list. - -Step by step the process is: - -1. Pick an element. This element is called the pivot. -2. Move all elements in the list that are greater than the pivot after the pivot -3. Move all elements that are less than the pivot before the pivot. -4. Recursively repeat steps 1-4 until a list of size 0-1 is found. -5. Concatinate all the sublists into a single sorted list. - -### Performance - -The performance of sorting algorithms is generally defined in "Big O notation". -If you are not familiar with such notations, please refer to the relevant -article by [Rob Bell][1] or the [Wikipedia][2] entry listed in further readings below. - -| Cases | Big O Notatation | -| ------------ | ---------------- | -| Best case | O(n log n) | -| Average case | O(n log n) | -| Worst case | O(n2) | - -As the name implies, quicksort is a rather efficient algorithm; however, -its performance can be affected by the pivot that is selected. For example, -always selecting the last element in the list (or sublist) can make the algorithm easy -to write, but on a sorted list that will lead to an efficiency of O(n2) -(the worst case). - -### Examples - -The example below was taken from [Wikipedia's article about Quick sort][3]. -The __bolded__ elements are the pivots. In this example, the last element in each list/sublist -was chosen to be the pivot, but that is not necesary. (See the section about performance above.) -Each row shows the comparison of an element to the pivot (steps 2-3). -The arrows convey splitting each list into sublists and then bringing them back together (steps -4-5). - -![Quick sort example](https://upload.wikimedia.org/wikipedia/commons/a/af/Quicksort-diagram.svg) - -[1]: https://robbell.io/2009/06/a-beginners-guide-to-big-o-notation -[2]: https://en.wikipedia.org/wiki/Big_O_notation -[3]: https://en.wikipedia.org/wiki/Quicksort - - -## Requirements - -Write a sample program that takes a list of numbers in the format "4, 5, 3, 1, 2". -It should then sort the numbers and output them: - -```console -$ ./quick-sort.lang "4, 5, 3, 1, 2" -1, 2, 3, 4, 5 -``` - -The solution should handle duplicate elements - -```console -$ ./quick-sort.lang "4, 5, 3, 1, 4, 2" -1, 2, 3, 4, 4, 5 -``` - -In addition, there should be some error handling for situations where the user -doesn't supply correct input. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Quick Sort. -In order to keep things simple, we split up the testing as follows: - -- Quick Sort Valid Tests -- Quick Sort Invalid Tests - -### Quick Sort Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input | "4, 5, 3, 1, 2" | "1, 2, 3, 4, 5" | -| Sample Input: With Duplicate | "4, 5, 3, 1, 4, 2" | "1, 2, 3, 4, 4, 5" | -| Sample Input: Already Sorted | "1, 2, 3, 4, 5" | "1, 2, 3, 4, 5" | -| Sample Input: Reverse Sorted | "9, 8, 7, 6, 5, 4, 3, 2, 1" | "1, 2, 3, 4, 5, 6, 7, 8, 9" | - -### Quick Sort Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A List | "1" | -| Invalid Input: Wrong Format | "4 5 3" | - -All of these tests should output the following: - -``` -Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -``` - - -## Articles - -There are 34 articles: - -- [Quick Sort in ALGOL 60](/projects/quick-sort/algol60) -- [Quick Sort in ALGOL 68](/projects/quick-sort/algol68) -- [Quick Sort in AWK](/projects/quick-sort/awk) -- [Quick Sort in Bash](/projects/quick-sort/bash) -- [Quick Sort in Beef](/projects/quick-sort/beef) -- [Quick Sort in C](/projects/quick-sort/c) -- [Quick Sort in C#](/projects/quick-sort/c-sharp) -- [Quick Sort in C++](/projects/quick-sort/c-plus-plus) -- [Quick Sort in COBOL](/projects/quick-sort/cobol) -- [Quick Sort in Commodore BASIC](/projects/quick-sort/commodore-basic) -- [Quick Sort in Dart](/projects/quick-sort/dart) -- [Quick Sort in Euphoria](/projects/quick-sort/euphoria) -- [Quick Sort in F#](/projects/quick-sort/f-sharp) -- [Quick Sort in Go](/projects/quick-sort/go) -- [Quick Sort in Haskell](/projects/quick-sort/haskell) -- [Quick Sort in Java](/projects/quick-sort/java) -- [Quick Sort in JavaScript](/projects/quick-sort/javascript) -- [Quick Sort in Kotlin](/projects/quick-sort/kotlin) -- [Quick Sort in Lisp](/projects/quick-sort/lisp) -- [Quick Sort in Mathematica](/projects/quick-sort/mathematica) -- [Quick Sort in Objective-C](/projects/quick-sort/objective-c) -- [Quick Sort in PHP](/projects/quick-sort/php) -- [Quick Sort in Pascal](/projects/quick-sort/pascal) -- [Quick Sort in Perl](/projects/quick-sort/perl) -- [Quick Sort in PowerShell](/projects/quick-sort/powershell) -- [Quick Sort in Python](/projects/quick-sort/python) -- [Quick Sort in Ruby](/projects/quick-sort/ruby) -- [Quick Sort in Rust](/projects/quick-sort/rust) -- [Quick Sort in Scala](/projects/quick-sort/scala) -- [Quick Sort in Swift](/projects/quick-sort/swift) -- [Quick Sort in Tcl](/projects/quick-sort/tcl) -- [Quick Sort in TypeScript](/projects/quick-sort/typescript) -- [Quick Sort in Visual Basic](/projects/quick-sort/visual-basic) -- [Quick Sort in m4](/projects/quick-sort/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/quick-sort/java/index.md b/docs/projects/quick-sort/java/index.md deleted file mode 100644 index 3f960201e0..0000000000 --- a/docs/projects/quick-sort/java/index.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Sumathi Varadharajan -date: 2019-11-01 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- java -- quick-sort -title: Quick Sort in Java -title1: Quick Sort -title2: in Java ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.ArrayList; - -public class QuickSort { - - public static void main(String[] args) { - ArrayList numList = new ArrayList<>(); - if (args.length < 1) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else if (args[0].length() < 2) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - String[] stringList = args[0].split(","); - if (stringList.length < 2) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - for (int i = 0; i < stringList.length; i++) { - numList.add(Integer.parseInt(stringList[i].trim())); - } - if (numList.size() < 2) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } else { - sort(numList, 0, numList.size() - 1); - String str = ""; - for (int i = 0; i < numList.size() - 1; i++) { - str += String.valueOf(numList.get(i)); - str += ", "; - } - str += String.valueOf(numList.get(numList.size() - 1)); - System.out.println(str); - } - } - } - } - - public static int partition(ArrayList arr, int low, int high) { - int pivot = arr.get(high); - int i = (low - 1); - for (int j = low; j < high; j++) { - if (arr.get(j) <= pivot) { - i++; - int temp = arr.get(i); - arr.set(i, arr.get(j)); - arr.set(j, temp); - } - } - int temp = arr.get(i + 1); - arr.set(i + 1, arr.get(high)); - arr.set(high, temp); - return i + 1; - } - - public static void sort(ArrayList arr, int low, int high) { - if (low < high) { - int pi = partition(arr, low, high); - sort(arr, low, pi - 1); - sort(arr, pi + 1, high); - } - } -} -``` - -{% endraw %} - -Quick Sort in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Sumathi Varadharajan - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/javascript/index.md b/docs/projects/quick-sort/javascript/index.md deleted file mode 100644 index 8449117868..0000000000 --- a/docs/projects/quick-sort/javascript/index.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -authors: -- Gurmeet -- Gurmeet Singh -- rzuckerm -date: 2019-10-16 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- javascript -- quick-sort -title: Quick Sort in JavaScript -title1: Quick Sort in -title2: JavaScript ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -/** - * Quick sort algorithm - * - * @param {Integer array} arr - */ - -const quickSort = (arr, start, end) => { - if(start < end) { - let pivot = partition(arr, start, end); - quickSort(arr, start, pivot - 1); - quickSort(arr, pivot + 1, end); - } -} - -const partition = (arr, start, end) => { - let pivot = end; - let i = start - 1; - let j = start; - while (j < pivot) { - if (arr[j] > arr[pivot]) { - j++; - } else { - i++; - swap(arr, j, i); - j++; - } - } - swap(arr, i + 1, pivot); - return i + 1; -} - -const swap = (arr, first, second) => { - let temp = arr[first]; - arr[first] = arr[second]; - arr[second] = temp; -} - -const main = (input) => { - /** - * If the string matches the format `"[number], [number], (... [number])"`, - * we have a valid input. - */ - const inputValidation = /^"?(\d+,\s*){2,}\d+(,"?|"?)$/gm; - - if (inputValidation.test(input) == true) { - // valid input - let arr; - - /** - * Format string to be quicksorted. - * - strip all whitespace and quotations - * - split into array at ',' character - * - convert all elements to integers - * - filter out NaN elements (uncaught text characters or empty elements) - */ - arr = input.replace(/(\s|"|'|`)/g, ''); - arr = arr.split(','); - arr = arr.map(function (n) { - return parseInt(n, 10); - }); - arr = arr.filter(n => n); - - // apply quicksort and output result - quickSort(arr, 0, arr.length - 1); - console.log(arr.join(", ")); - } - else { - // invalid input - console.log(usage); - } -} - -const usage = `Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"`; - -if (process.argv.length > 2) { - const input = process.argv[2]; - main(input); -} -else { - console.log(usage); -} - -``` - -{% endraw %} - -Quick Sort in [JavaScript](/languages/javascript) was written by: - -- Gurmeet -- Gurmeet Singh -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/kotlin/index.md b/docs/projects/quick-sort/kotlin/index.md deleted file mode 100644 index af6b92f8ed..0000000000 --- a/docs/projects/quick-sort/kotlin/index.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -authors: -- Blake.Ke -- Jeremy Grifski -- mikenmo -date: 2020-10-01 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- kotlin -- quick-sort -title: Quick Sort in Kotlin -title1: Quick Sort -title2: in Kotlin ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) -{ - var arr: IntArray - try - { - arr = args[0].split(", ").map{ it.toInt() }.toIntArray() - if (arr.size < 2) { - throw Exception() - } - } - catch(e: Exception) - { - println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - return - } - - var ans:IntArray = quickSort(arr) - for(i in 0 until ans.count()) - { - if (i==ans.count() - 1) - { - println("${ans[i]}") - return - } - print("${ans[i]}, ") - } -} - -fun quickSort(arr: IntArray):IntArray -{ - if (arr.count() == 1) - { - return(arr.sliceArray(0..0)) - } - var pivot:Int = (arr.count() - 1) / 2 - arr[pivot] = arr[arr.count() - 1].also {arr[arr.count() - 1] = arr[pivot]} - pivot = arr.count()-1 - - var ans = intArrayOf() - var left = intArrayOf() - for(i in 0 until arr.count()) - { - if(arr[i] > arr[pivot] || i == pivot) - { - for(j in arr.count() - 2 downTo 0) - { - if(i>j || j == 0) - { - arr[pivot] = arr[i].also {arr[i] = arr[pivot]} - pivot = i - - if(pivot!=0){ - left = arr.sliceArray(0..pivot-1) - ans = quickSort(arr.sliceArray(0..pivot - 1)) - ans = ans + arr.sliceArray(pivot..pivot) - } - else - { - ans = arr.sliceArray(pivot..pivot) - } - if(pivot!=arr.count()-1){ - ans = ans + quickSort(arr.sliceArray(pivot + 1..arr.count() - 1)) - } - - return (ans) - } - if(arr[j] - -Welcome to the [Quick Sort](/projects/quick-sort) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(defun qsort (L) - (cond - ((null L) nil) - (t - (append - (qsort (list< (car L) (cdr L))) - (cons (car L) nil) - (qsort (list>= (car L) (cdr L))))))) - -(defun list< (a b) - (cond - ((or (null a) (null b)) nil) - ((< a (car b)) (list< a (cdr b))) - (t (cons (car b) (list< a (cdr b)))))) - -(defun list>= (a b) - (cond - ((or (null a) (null b)) nil) - ((>= a (car b)) (list>= a (cdr b))) - (t (cons (car b) (list>= a (cdr b)))))) - -;;Taken from the Common Lisp Cookbook Project (strings page) -(defun split-string (string) - (loop for i = 0 then (1+ j) - as j = (position #\, string :start i) - collect (subseq string i j) - while j)) - -(defun join-string (lst) - (reduce - (lambda (acc n) - (concatenate 'string acc ", " (princ-to-string n))) (cdr lst) - :initial-value (princ-to-string (car lst)))) - -(defun maybe-int (input) - (cond - ((null input) nil) - ((string= input "") nil) - ((every #'digit-char-p (string-left-trim "-" input)) (parse-integer input)) - (t nil))) - -(defun maybe-int-list (input-list &optional (acc)) - (cond - ((<= (length input-list) 0) acc) - (t - (let ((i (maybe-int (string-trim " " (car input-list))))) - (cond - ((null i) nil) - (t (maybe-int-list (cdr input-list) (cons i acc)))))))) - - -(defparameter input (maybe-int-list (split-string (cadr *posix-argv*)))) -(cond - ((or (null input) (= (length input) 1)) (write-line "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"")) - (t (write-line (join-string (qsort input))))) -``` - -{% endraw %} - -Quick Sort in [Lisp](/languages/lisp) was written by: - -- Palash Dubey -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/m4/index.md b/docs/projects/quick-sort/m4/index.md deleted file mode 100644 index e39b2d40b0..0000000000 --- a/docs/projects/quick-sort/m4/index.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-05 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2025-10-05 -layout: default -tags: -- m4 -- quick-sort -title: Quick Sort in m4 -title1: Quick Sort -title2: in m4 ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl array_swap(var_name, idx1, idx2): -dnl t = var_name[idx1] -dnl var_name[idx1] = var_name[idx2] -dnl var_name[idx] = t -define(`array_swap', -`pushdef(`t', array_get(`$1', `$2'))dnl -array_set(`$1', `$2', array_get(`$1', `$3'))dnl -array_set(`$1', `$3', t)dnl -popdef(`t')'dnl -) - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl show_int_list(varname): -dnl for i = 0 to n-1: -dnl if i > 0: -dnl Output ", " -dnl Output varname[i] -define(`show_int_list', `_show_int_list(`$1', 0)') -define(`_show_int_list', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`ifelse(eval($2 > 0), 1, `, ')dnl -array_get(`$1', $2)`'dnl -_show_int_list(`$1', incr($2))'`'dnl -)'dnl -) - -dnl Reference: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme -dnl quick_sort(varname): -dnl quick_sort_rec(varname, 0, varname[length]) -define(`quick_sort', `quick_sort_rec(`$1', 0, decr(array_get(`$1', `length')))') - -dnl quick_sort_rec(varname, lo, hi): -dnl if lo >= 0 and lo < hi: -dnl p = partition(varname, lo, hi) -dnl quick_sort_rec(varname, lo, p-1) -dnl quick_sort_rec(varname, p+1, hi) -define(`quick_sort_rec', -`ifelse(eval($2 >= 0 && $2 < $3), 1, -`pushdef(`p', partition(`$1', `$2', `$3'))dnl -quick_sort_rec(`$1', $2, decr(p))dnl -quick_sort_rec(`$1', incr(p), $3)dnl -popdef(`p')'dnl -)'dnl -) - -dnl partition(varname, lo, hi): -dnl // Choose the last element as the pivot -dnl pivot = varname[hi] -dnl -dnl // Temporary pivot index -dnl i = lo -dnl -dnl // Swap elements less than or equal to pivot, and increment -dnl // temporary index -dnl for j = lo to hi-1: -dnl if varname[j] <= pivot: -dnl swap(varname, i, j) -dnl i = i + 1 -dnl -dnl // Move pivot to correct position -dnl swap(varname, i, hi) -dnl return i -define(`partition', `_partition(`$1', `$3', array_get(`$1', `$3'), `$2', `$2')') - -dnl varname=$1, hi=$2, pivot=$3, i=$4, j=$5 -define(`_partition', -`ifelse(eval($5 >= $2), 1, -`array_swap(`$1', `$4', `$2')$4', -`ifelse(eval(array_get(`$1', `$5') <= $3), 1, -`array_swap(`$1', `$4', `$5')dnl -_partition(`$1', `$2', `$3', incr($4), incr($5))', -`_partition(`$1', `$2', `$3', `$4', incr($5))'dnl -)'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !parse_int_list(`arr', ARGV1)), 1, `show_usage()')dnl -ifelse(eval(array_get(`arr', `length') < 2), 1, `show_usage()')dnl -quick_sort(`arr')dnl -show_int_list(`arr') - -``` - -{% endraw %} - -Quick Sort in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/mathematica/index.md b/docs/projects/quick-sort/mathematica/index.md deleted file mode 100644 index 8825869afe..0000000000 --- a/docs/projects/quick-sort/mathematica/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-19 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2023-01-19 -layout: default -tags: -- mathematica -- quick-sort -title: Quick Sort in Mathematica -title1: Quick Sort in -title2: Mathematica ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* To me, some confusion arises from whether the pivot is a value or -an element-- it should be the former, which emphasizes that the pivot value -can occur multiply. Since we can simultaneously compare for strict inequality -(less than/greater than) and loose inequality (less than or equal/greater than -or equal) we may take advantage of that and not lose that information: this -implies that we should sort pivot values explicitly, into a middle compartment. -Since the pivot values will then already be at the correct position, they -will never undergo resorting. Also, note that a 'swap' is actually 3 copies -(including the temporary variable); in general, a permutation over an n-cycle -requires n+1 copies, so permutations over 3-cycles move 3 elements more -efficiently at the cost of 4/3 of a swap. *) - -(* The partitioning is like Hoare in that it is bidirectional from both ends -until pointers cross. It is different in that the invariant always keeps -pivot elements on the towards-center side, so that at completion all pivot -elements are found in the center. The algorithm performs like Hoare in that -it performs no swaps on lists that are already sorted and lists containing -equal elements. In addition, it excludes all pivot elements from recursive -consideration. It performs better than Sedgewick by not swapping pivots -that are already at the correct location, and handles the case when the -pivot value occurs multiple times. *) - -quicksort = list \[Function] - If[Length[list] > 1, - Module[ - {v = list, - p = list[[Ceiling[Length[list]/2]]], (* choose a pivot value *) - i = 1, l = 1, j = Length[list], h = Length[list]}, - (* until both ends of the partition meet *) - While[i <= j, - (* grow the left side of the partition until a strictly larger element is found *) - While[i <= j, - Switch[v[[i]] - p,(* simultaneously compare loose and strict equality against the pivot *) - (* move strictly lower elements before any accumulated pivot elements *) - c_ /; c < 0, If[i > l, v = Permute[v, Cycles[{{l, i}}]]]; l++, - - (* leave pivot elements at the toward-middle end of the left side *) - 0, Null, - - (* stop if we find an element strictly greater than the pivot *) - _, Break[]]; - i++]; - - (* mutatis mutandis for the right side of the partition *) - While[j >= i, - Switch[v[[j]] - p, - c_ /; c > 0, If[j < h, v = Permute[v, Cycles[{{h, j}}]]]; h--, - 0, Null, - _, Break[]]; - j--]; - - (* pointers have not crossed yet? - Then we have a strictly lower and strictly higher element both on the wrong sides of the partition *) - If[i < j, - If[i == l \[And] j == h, v = Permute[v, Cycles[{{i, j}}]]]; - If[i > l \[And] j == h, v = Permute[v, Cycles[{{j, l, i}}]]]; - If[i == l \[And] j < h, v = Permute[v, Cycles[{{i, h, j}}]]]; - If[i > l \[And] j < h, v = Permute[v, Cycles[{{i, h}, {j, l}}]]]; - i++; l++; j--; h--]]; - - (* recurse *) - Join[ - If[l > 1, quicksort[v[[;; l - 1]]], {}], - If[h >= l, v[[l ;; h]], {}], - If[h < Length[list], quicksort[v[[h + 1 ;;]]], {}]]], - list]; - -(* The outer function provides the 'user interface': *) - -quicksortMain = l \[Function] - Module[{e = "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""}, - Catch[ - StringRiffle[ - quicksort @ - (* list must have more than one element *) - If[Length[#] > 1, #, Throw[e]] & @ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments to bubble sort: list of items *) - StringSplit[l, ", "], - {-1} (* at each leaf *)], - ", "]]]; - - -(* Valid Tests *) - -Print /@ quicksortMain /@ { - "4, 5, 3, 1, 2", - "4, 5, 3, 1, 4, 2", - "1, 2, 3, 4, 5", - "9, 8, 7, 6, 5, 4, 3, 2, 1" - }; - - -(* Invalid Tests *) - -quicksortMain[""] -quicksortMain["1"] -quicksortMain["4 5 3"] - -``` - -{% endraw %} - -Quick Sort in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/objective-c/index.md b/docs/projects/quick-sort/objective-c/index.md deleted file mode 100644 index fc86927da5..0000000000 --- a/docs/projects/quick-sort/objective-c/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -authors: -- niftycode -- rzuckerm -- Ștefan-Iulian Alecu -date: 2020-10-04 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- objective-c -- quick-sort -title: Quick Sort in Objective-C -title1: Quick Sort in -title2: Objective-C ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -@interface NSString (Parsing) -- (nullable NSArray*)strictIntegerList; -@end - -@implementation NSString (Parsing) - -- (NSArray*)strictIntegerList { - NSArray* parts = [self componentsSeparatedByString:@","]; - NSMutableArray* results = - [NSMutableArray arrayWithCapacity:parts.count]; - NSCharacterSet* invertedDigits = - NSCharacterSet.decimalDigitCharacterSet.invertedSet; - - for (NSString* raw in parts) { - NSString* s = [raw stringByTrimmingCharactersInSet: - NSCharacterSet.whitespaceAndNewlineCharacterSet]; - if (s.length == 0) return nil; - - NSString* core = ([s hasPrefix:@"-"] || [s hasPrefix:@"+"]) - ? [s substringFromIndex:1] - : s; - if (core.length == 0 || - [core rangeOfCharacterFromSet:invertedDigits].location != - NSNotFound) - return nil; - - [results addObject:@(s.longLongValue)]; - } - return (results.count >= 2) ? results : nil; -} - -@end - -static void quickSortRange(NSMutableArray* array, NSInteger left, - NSInteger right) { - if (left >= right) return; - - NSInteger i = left; - NSInteger j = right; - long long pivot = array[left + (right - left) / 2].longLongValue; - - while (i <= j) { - while (array[i].longLongValue < pivot) i++; - while (array[j].longLongValue > pivot) j--; - - if (i <= j) { - [array exchangeObjectAtIndex:i withObjectAtIndex:j]; - i++; - j--; - } - } - - quickSortRange(array, left, j); - quickSortRange(array, i, right); -} - -@interface NSArray (Sorting) -- (NSArray*)sortedArrayUsingQuickSort; -@end - -@implementation NSArray (Sorting) - -- (NSArray*)sortedArrayUsingQuickSort { - if (self.count < 2) return self; - - NSMutableArray* buffer = [self mutableCopy]; - quickSortRange(buffer, 0, buffer.count - 1); - - return buffer; -} - -@end - -int main(int argc, const char* argv[]) { - @autoreleasepool { - const char* usage = - "Usage: please provide a list of at least two integers to sort " - "in the format \"1, 2, 3, 4, 5\""; - - if (argc < 2) { - puts(usage); - return 1; - } - - NSArray* numbers = [@(argv[1]) strictIntegerList]; - - if (!numbers) { - puts(usage); - return 1; - } - - NSString* output = [[numbers sortedArrayUsingQuickSort] - componentsJoinedByString:@", "]; - - puts(output.UTF8String); - } - - return 0; -} -``` - -{% endraw %} - -Quick Sort in [Objective-C](/languages/objective-c) was written by: - -- niftycode -- rzuckerm -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/pascal/index.md b/docs/projects/quick-sort/pascal/index.md deleted file mode 100644 index f639dd22e4..0000000000 --- a/docs/projects/quick-sort/pascal/index.md +++ /dev/null @@ -1,258 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-22 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2025-07-22 -layout: default -tags: -- pascal -- quick-sort -title: Quick Sort in Pascal -title1: Quick Sort -title2: in Pascal ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program QuickSort; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - StrUtils, - SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) < 2 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function FormatIntegerList(const List: TIntegerList): string; -var - i: integer; -begin - Result := ''; - for i := 0 to List.Count - 1 do - begin - if i > 0 then - Result += ', '; - Result += IntToStr(List[i]); - end; -end; - -procedure InsertionSort(var A: TIntegerList; Left, Right: integer); -var - i, j, key: integer; -begin - for i := Left + 1 to Right do - begin - key := A[i]; - j := i - 1; - while (j >= Left) and (A[j] > key) do - begin - A[j + 1] := A[j]; - Dec(j); - end; - A[j + 1] := key; - end; -end; - -function MedianOfThree(var List: TIntegerList; Left, Mid, Right: integer): integer; -var - a, b, c: integer; -begin - a := List[Left]; - b := List[Mid]; - c := List[Right]; - - if (a <= b) then - begin - if (b <= c) then - Result := B - else if (a <= c) then - Result := C - else - Result := A; - end - - else - if (a <= c) then - Result := A - else if (b <= c) then - Result := C - else - Result := B; -end; - -function MedianOfNine(var List: TIntegerList; Left, Right: integer): integer; -var - step, mid: integer; - m1, m2, m3: integer; -begin - if (Right - Left) < 8 then - Exit(MedianOfThree(List, Left, Left + (Right - Left) div 2, Right)); - - step := (Right - Left) div 8; - mid := Left + (Right - Left) div 2; - - m1 := MedianOfThree(List, Left, Left + step, Left + 2 * step); - m2 := MedianOfThree(List, mid - step, mid, mid + step); - m3 := MedianOfThree(List, Right - 2 * step, Right - step, Right); - - Result := MedianOfThree(List, m1, m2, m3); -end; - -procedure QuickSort(var List: TIntegerList; Left, Right: integer); -const - INSERTION_SORT_THRESHOLD = 16; -var - i, j, pivotIndex, pivotValue: integer; - - procedure SwapElements(Index1, Index2: integer); - var - Temp: integer; - begin - Temp := List[Index1]; - List[Index1] := List[Index2]; - List[Index2] := Temp; - end; - - // Three-way partitioning (AKA Dutch National Flag partitioning) - procedure Partition(out LeftEnd, RightStart: integer); - var - LeftIndex, RightIndex, CurrentIndex: integer; - begin - LeftIndex := Left; - RightIndex := Right; - CurrentIndex := Left; - - while CurrentIndex <= RightIndex do - if List[CurrentIndex] < pivotValue then - begin - SwapElements(CurrentIndex, LeftIndex); - Inc(LeftIndex); - Inc(CurrentIndex); - end - else if List[CurrentIndex] > pivotValue then - begin - SwapElements(CurrentIndex, RightIndex); - Dec(RightIndex); - end - else - Inc(CurrentIndex); - - LeftEnd := LeftIndex - 1; - RightStart := RightIndex + 1; - end; - -begin - while Left < Right do - begin - if Right - Left + 1 <= INSERTION_SORT_THRESHOLD then - begin - InsertionSort(List, Left, Right); - Exit; - end; - - // Median-of-nine pivot selection - pivotIndex := MedianOfNine(List, Left, Right); - pivotValue := List[pivotIndex]; - // Move pivot to the end - SwapElements(pivotIndex, Right); - - Partition(i, j); - - // Recurse on smaller side first - if (i - Left) < (Right - j) then - begin - QuickSort(List, Left, i); - Left := j; - end - else - begin - QuickSort(List, j, Right); - Right := i; - end; - end; -end; - -var - numbers: TIntegerList; -begin - if ParamCount <> 1 then - ShowUsage; - - numbers := ParseIntegerList(ParamStr(1)); - try - QuickSort(numbers, 0, numbers.Count - 1); - Writeln(FormatIntegerList(numbers)); - finally - numbers.Free; - end; -end. - -``` - -{% endraw %} - -Quick Sort in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/perl/index.md b/docs/projects/quick-sort/perl/index.md deleted file mode 100644 index 64813d2747..0000000000 --- a/docs/projects/quick-sort/perl/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Mr Anand Somashekhara Rao Somavarapete -- Ștefan-Iulian Alecu -date: 2023-10-01 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- perl -- quick-sort -title: Quick Sort in Perl -title1: Quick Sort -title2: in Perl ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -use feature qw/keyword_any/; -no warnings 'experimental::keyword_any'; - -sub usage { - say 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - exit; -} - -sub parse_list ($s) { - return undef unless defined $s; - - my @vals = split /\s*,\s*/, $s; - - return undef if @vals < 2; - return undef if any { $_ !~ /\A-?\d+\z/ } @vals; - - return [ map 0 + $_, @vals ]; -} - -sub quick_sort ($a) { - return $a if @$a <= 1; - - my $pivot = $a->[ @$a >> 1 ]; - - my @left = grep { $_ < $pivot } @$a; - my @mid = grep { $_ == $pivot } @$a; - my @right = grep { $_ > $pivot } @$a; - - return [ @{ quick_sort( \@left ) }, @mid, @{ quick_sort( \@right ) } ]; -} - -my ($input) = @ARGV; -my $a = parse_list($input) or usage(); - -$a = quick_sort($a); -say join ', ', @$a; - -``` - -{% endraw %} - -Quick Sort in [Perl](/languages/perl) was written by: - -- Mr Anand Somashekhara Rao Somavarapete -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/php/index.md b/docs/projects/quick-sort/php/index.md deleted file mode 100644 index 8cd0f12551..0000000000 --- a/docs/projects/quick-sort/php/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Gurmeet -- Jeremy Grifski -date: 2019-10-16 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- php -- quick-sort -title: Quick Sort in PHP -title1: Quick Sort -title2: in PHP ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Quick Sort](/projects/quick-sort) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -# Source: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme -function Invoke-QuickSort([array]$Values) { - Invoke-QuickSortRec $Values 0 ($Values.Length - 1) -} - -function Invoke-QuickSortRec([array]$Values, [int]$Lo, [int]$Hi) { - if ($Lo -ge 0 -and $Lo -le $Hi) { - # Partition array and get pivot value - $p = Invoke-Partition $Values $Lo $Hi - - # Sort left side of partition - Invoke-QuickSortRec $Values $Lo ($p - 1) - - # Sort right side of partition - Invoke-QuickSortRec $Values ($p + 1) $Hi - } -} - -function Invoke-Partition([array]$Values, [int]$Lo, [int]$Hi) { - # Choose the last element as the pivot - $pivot = $Values[$Hi] - - # Temporary pivot index - $i = $Lo - - for ($j = $Lo; $j -le ($Hi - 1); $j++) { - # If the current element is less than or equal to the pivot, - if ($Values[$j] -le $pivot) { - # Swap the current element with the element at the temporary pivot index - $Values[$i], $Values[$j] = $Values[$j], $Values[$i] - - # Move the temporary pivot index forward - $i++ - } - } - - # Swap the pivot with the last element - $Values[$i], $Values[$Hi] = $Values[$Hi], $Values[$i] - - # Return pivot index - $i -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -try { - $values = Parse-IntList $args[0] - if ($values.Length -lt 2) { - Show-Usage - } -} catch { - Show-Usage -} - -Invoke-QuickSort $values -Write-Output ($values -join ', ') - -``` - -{% endraw %} - -Quick Sort in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/python/index.md b/docs/projects/quick-sort/python/index.md deleted file mode 100644 index f7c62e95f0..0000000000 --- a/docs/projects/quick-sort/python/index.md +++ /dev/null @@ -1,261 +0,0 @@ ---- -authors: -- Haseeb Majid -- Jeremy Grifski -- Parker Johansen -- rzuckerm -date: 2018-12-23 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- python -- quick-sort -title: Quick Sort in Python -title1: Quick Sort -title2: in Python ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def quick_sort(xs): - if len(xs) <= 0: - return [] - - left = quick_sort([l for l in xs[1:] if l <= xs[0]]) - right = quick_sort([r for r in xs[1:] if r > xs[0]]) - return left + xs[:1] + right - - -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] - - -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) - - -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(quick_sort(xs)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Quick Sort in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Parker Johansen - -This article was written by: - -- Haseeb Majid -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's dig into the code a bit. The following sections break -down the Quick Sort in Python functionality. - -### The Main Function - -Breaking down this solution bottom up, - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -This bit of code checks to see if this is the `main` module run. If it is, it then calls the `main` -function and passes user input to it. In this case the user input would be a string of numbers -like so `"2, 1, 10, 5, 3"` (to sort). - -```python -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(quick_sort(xs)) - except (IndexError, ValueError): - exit_with_error() -``` - -This is the `main` function of this file. It parses the input, then calls our quick sort -function (and prints the results). It also deals with any errors raised. - -Finally we wrap this entire block in a `try ... except`, and we catch two exceptions: `IndexError` -and `ValueError`. `IndexError` will be thrown if `args` is empty, and we try to access `args[0]`. -`ValueError` will be thrown if we try to convert a non-integer string into an integer. -For example if `args[0]` was "a" -> `int("a")`. If any exceptions are raised, then we call -the `exit_with_error()` function. - -### Transform Input Parameters - -```python -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] -``` - -This function takes a string like `"2, 1, 10, 5, 3"`, and turns into a list of numbers. -It does this using a list comprehension. First, we need to convert our string into a -list `list_str.split(',')` which is a list of strings split by comma (`,`). -So our original input string becomes `["2", " 1", " 10", " 5", " 3"]`. Then for each -element in the list `for x in ...` , we do something to it. - -In this example we convert it into a decimal integer, `int(x.strip(" "), 10)` -`x.strip(" ")`, removes any whitespace so `" 1"` becomes `"1"`, then `int("1", 10)` -converts the string `"1"` into a decimal number in this case `1`. This is done -for every item in the list, so our original input of `"2, 1, 10, 5, 3"` -becomes `[2, 1, 10, 5, 3]`. - -### Throw Errors - -```python -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) -``` - -This function prints a message and then exits the script with an error, `sys.exit(1)`. -If any non-zero value is returned, then the program didn't complete properly. This function is called -if the user input isn't correct. - -### Quick Sort - -```python -def quick_sort(xs): - if len(xs) <= 0: - return [] - - left = quick_sort([l for l in xs[1:] if l <= xs[0]]) - right = quick_sort([r for r in xs[1:] if r > xs[0]]) - return left + xs[:1] + right -``` - -Now onto the main part of the program. This is the function that actually sorts our list. -The first part `len(xs) <= 0` checks if the list is empty. If it is, then it returns an -empty list `return []`. - -In each iteration of the quicksort we have to pick a pivot element. This element is used to break -down the current list into two smaller lists. One list contains all numbers larger than the pivot -and the other list contains all elements smaller (or equal) to the pivot. There are a few ways to -pick a pivot element but in our code we will be using the first element of each list (`xs[0]`). - -We create two sub-lists from our list. `left` will contain all elements smaller than `xs[0]`, -the first element in our list. `right` will contain all elements larger than `xs[0]`. -These lists aren't actually sorted yet so we call the `quick_sort()` function on these sub-lists -recursively until they are sorted. Each of these sub-lists is broken down into two lists every -time the `quick_sort()` function is called. - -```python -left = quick_sort([l for l in xs[1:] if l <= xs[0]]) -``` - -Taking a closer look at how we generate the left sub-list, we use a list comprehension -which is a way to generate lists in Python. In this example `[l for l in xs[1:] if l <= xs[0]]` -we loop through the unsorted list `xs`. Examining the first part `[l for l in xs[1:]]` this would -generate a list which would contain every element in `xs` except the first one. `xs[1:]` means that -the list includes every element except the first one, hence the `[1:]`. This is called index -splicing in Python, and you can learn more about it [here](https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/). - -For example, if `xs = [3, 2, 4, 1]`, then the generated list would be `left = [2, 4, 1]`. -Now including the final part of the list comprehension `[l for l in xs[1:] if l <= xs[0]]`, -`l` is only added to the list if it's less or equal to the first element of `xs`, `if l <= xs[0]`. -So again using our example `xs = [3, 2, 4, 1]` the generated list would be`left = [2, 1]`, -since `4 > 3` and `xs[0] = 3`. This new list is then passed to our quick sort function. - -The `right = quick_sort([r for r in xs[1:] if r > xs[0]])` is very similar except it stores elements -strictly greater than `xs[0]`. But other than that it generates the list in much the same way `left` -does. So using the same example `xs = [3, 2, 4, 1]` then `right = [4]`. Since `4` is the only element -great then `xs[0] = 3`. - -Finally, those two lists are combined into a single list and returned -`return left + xs[:1] + right`, where left contains all elements less than or equal to -`xs[0]` and right contains all the items great than `xs[0]`. `xs[:1]` in this example gets -the first element, except this also works if `xs` is empty. If `xs = []` and you try to get -`xs[0]` the program will throw an `IndexError` whereas `xs[:1] = []` an empty list. - -Let's take a look at an example where `xs = [5, 1, 10]` - -#### Main Quick Sort - -* `xs[0] = 5` -* `left = quick_sort([1])` -* `right = quick_sort([10])` - -##### Left Quick Sort - -* `xs[0] = 1` -* `left = quick_sort([])` -* `right = quick_sort([])` - -Since the lists are empty `quick_sort` will return `[]` an empty list back so. - -* `left = []` -* `right = []` -* `return [] + [1] + []` - -#### Right Quick Sort - -* `xs[0] = 10` -* `left = quick_sort([])` -* `right = quick_sort([])` - -Since the lists are empty `quick_sort` will return `[]` an empty list back so. - -* `left = []` -* `right = []` -* `return [] + [10] + []` - -#### Back to Main Quick Sort - -* `left = [1]` -* `right = [10]` -* `xs[0] = 5` -* `return [1] + [5] + [10]` - -So the final sorted list is [1, 5, 10] - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Quick Sort in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/quick_sort.py). -After that, we should make sure we have the [latest Python interpreter](https://www.python.org/downloads/). From there, we can run the following command in the terminal: - -`python quick-sort.py "3, 2, 10, 6, 1, 7"` - -Alternatively, we can copy the solution into an [online Python interpreter](https://www.online-python.com/) and hit run. diff --git a/docs/projects/quick-sort/ruby/index.md b/docs/projects/quick-sort/ruby/index.md deleted file mode 100644 index ec80697239..0000000000 --- a/docs/projects/quick-sort/ruby/index.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- quick-sort -- ruby -title: Quick Sort in Ruby -title1: Quick Sort -title2: in Ruby ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -def usage! - abort %(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5") -end - -def parse_input - raw = ARGV.first - usage! if raw.nil? || raw.strip.empty? - - numbers = raw.split(",").map { Integer(it.strip) } - usage! if numbers.length < 2 - - numbers -rescue ArgumentError, NoMethodError - usage! -end - -def quicksort!(arr, lo = 0, hi = arr.length - 1) - return arr if lo >= hi - - p = partition(arr, lo, hi) - - quicksort!(arr, lo, p - 1) - quicksort!(arr, p + 1, hi) - - arr -end - -def partition(arr, lo, hi) - pivot = arr[hi] - i = lo - - (lo...hi).each do |j| - if arr[j] <= pivot - arr[i], arr[j] = arr[j], arr[i] - i += 1 - end - end - - arr[i], arr[hi] = arr[hi], arr[i] - i -end - -numbers = parse_input -puts quicksort!(numbers).join(", ") - -``` - -{% endraw %} - -Quick Sort in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/rust/index.md b/docs/projects/quick-sort/rust/index.md deleted file mode 100644 index ec486c933e..0000000000 --- a/docs/projects/quick-sort/rust/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Paolo Cretaro -date: 2022-10-03 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2022-10-03 -layout: default -tags: -- quick-sort -- rust -title: Quick Sort in Rust -title1: Quick Sort -title2: in Rust ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -fn quicksort_recursive(mut vector: Vec) -> Vec { - match vector.len() { - 0|1 => vector, - _ => { - let pivot = vector.pop().unwrap(); // len is always greater than 1 here, so this is safe - let lesser: Vec = vector.iter().cloned().filter(|i| i.lt(&pivot)).collect(); - let greater: Vec = vector.into_iter().filter(|i| i.ge(&pivot)).collect(); - let mut lesser = quicksort_recursive(lesser); - lesser.push(pivot); - lesser.extend(quicksort_recursive(greater).into_iter()); - lesser - }, - } -} - - -fn main() { - let usage_msg = "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""; - - let mut args = std::env::args(); - args.next(); // first arg is command name, so ignore it - - let input_str = args.next().unwrap_or_else(|| {eprintln!("{usage_msg}"); std::process::exit(-1)}); - let input_vec: Vec = input_str.split(",") // parse comma separated input into a i32 vector - .map(|x| x.trim() - .parse() - .unwrap_or_else(|_| {eprintln!("{usage_msg}"); std::process::exit(-1)})) - .collect(); - - if input_vec.len() < 2 { - eprintln!("{usage_msg}"); - std::process::exit(-1); - } - - println!("{:?}", quicksort_recursive(input_vec)); -} - -``` - -{% endraw %} - -Quick Sort in [Rust](/languages/rust) was written by: - -- Paolo Cretaro - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/scala/index.md b/docs/projects/quick-sort/scala/index.md deleted file mode 100644 index 63da4672ed..0000000000 --- a/docs/projects/quick-sort/scala/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Viet Thang Nguyen -- Ștefan-Iulian Alecu -date: 2019-03-22 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- quick-sort -- scala -title: Quick Sort in Scala -title1: Quick Sort -title2: in Scala ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -import scala.util.Try - -object QuickSort: - - def main(args: Array[String]): Unit = - val input = args.headOption.getOrElse("") - - parse(input) match - case Some(nums) if nums.length >= 2 => - println(sort(nums).mkString(", ")) - case _ => - println(usage) - - def usage: String = - """Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"""" - - def sort(xs: List[Int]): List[Int] = - xs match - case Nil => Nil - case pivot :: tail => - val (less, more) = tail.partition(_ < pivot) - sort(less) ++ (pivot :: sort(more)) - - def parse(input: String): Option[List[Int]] = - Try(input.split(',').toList.map(_.trim.toInt)).toOption -``` - -{% endraw %} - -Quick Sort in [Scala](/languages/scala) was written by: - -- Viet Thang Nguyen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/swift/index.md b/docs/projects/quick-sort/swift/index.md deleted file mode 100644 index bc975b7acd..0000000000 --- a/docs/projects/quick-sort/swift/index.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- quick-sort -- swift -title: Quick Sort in Swift -title1: Quick Sort -title2: in Swift ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseIntegers(from args: [String]) -> [Int]? { - guard args.count == 2 else { return nil } - - let parts = args[1].split(separator: ",", omittingEmptySubsequences: false) - let values = parts.compactMap { Int($0.trimmed) } - - guard values.count == parts.count, - values.count >= 2 - else { - return nil - } - - return values -} - -extension RangeReplaceableCollection -where Self: MutableCollection, Self: RandomAccessCollection { - - mutating func quickSort(by areInIncreasingOrder: (Element, Element) -> Bool) { - guard count > 1 else { return } - - var buffer = Array(self) - quickSort(&buffer, low: 0, high: buffer.count - 1, by: areInIncreasingOrder) - self = Self(buffer) - } - - private func quickSort( - _ a: inout [Element], - low: Int, - high: Int, - by areInIncreasingOrder: (Element, Element) -> Bool - ) { - guard low < high else { return } - - let pivotIndex = partition(&a, low: low, high: high, by: areInIncreasingOrder) - - quickSort(&a, low: low, high: pivotIndex - 1, by: areInIncreasingOrder) - quickSort(&a, low: pivotIndex + 1, high: high, by: areInIncreasingOrder) - } - - private func partition( - _ a: inout [Element], - low: Int, - high: Int, - by areInIncreasingOrder: (Element, Element) -> Bool - ) -> Int { - let pivot = a[high] - var i = low - - for j in low.. - -Welcome to the [Quick Sort](/projects/quick-sort) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"} - exit 1 -} - -proc parseList {s} { - set tokens [split [string trim $s] ","] - if {[llength $tokens] < 2} { usage } - - set result {} - foreach token $tokens { - set t [string trim $token] - if {$t eq "" || [catch {expr {int($t)}} val]} usage - lappend result $val - } - return $result -} - -proc swap {varName i j} { - upvar 1 $varName lst - if {$i == $j} return - set tmp [lindex $lst $i] - lset lst $i [lindex $lst $j] - lset lst $j $tmp -} - -proc medianOfThree {varName a b c} { - upvar 1 $varName lst - set va [lindex $lst $a] - set vb [lindex $lst $b] - set vc [lindex $lst $c] - if {$va <= $vb} { - if {$vb <= $vc} { - return $b - } elseif {$va <= $vc} { - return $c - } else { - return $a - } - } else { - if {$va <= $vc} { - return $a - } elseif {$vb <= $vc} { - return $c - } else { - return $b - } - } -} - -proc medianOfNine {varName left right} { - upvar 1 $varName lst - set n [expr {$right - $left}] - if {$n < 8} { - set mid [expr {$left + $n / 2}] - return [medianOfThree lst $left $mid $right] - } - set step [expr {$n / 8}] - set mid [expr {$left + $n / 2}] - set m1 [medianOfThree lst $left [expr {$left+$step}] [expr {$left+2*$step}]] - set m2 [medianOfThree lst [expr {$mid-$step}] $mid [expr {$mid+$step}]] - set m3 [medianOfThree lst [expr {$right-2*$step}] [expr {$right-$step}] $right] - return [medianOfThree lst $m1 $m2 $m3] -} - -proc quicksortInPlace {varName left right} { - upvar 1 $varName lst - - while {$left < $right} { - # median-of-nine pivot - set pivotIndex [medianOfNine lst $left $right] - set pivotValue [lindex $lst $pivotIndex] - swap lst $pivotIndex $right - - # three-way partition - set i $left - set j $right - set k $left - while {$k <= $j} { - set val [lindex $lst $k] - if {$val < $pivotValue} { - swap lst $k $i - incr i - incr k - } elseif {$val > $pivotValue} { - swap lst $k $j - incr j -1 - } else { - incr k - } - } - - # recurse on smaller side first (tail recursion elimination) - set leftEnd [expr {$i - 1}] - set rightStart [expr {$j + 1}] - if {[expr {$leftEnd - $left}] < [expr {$right - $rightStart}]} { - if {$left < $leftEnd} { - quicksortInPlace lst $left $leftEnd - } - set left $rightStart - } else { - if {$rightStart < $right} { - quicksortInPlace lst $rightStart $right - } - set right $leftEnd - } - } -} - -proc quicksort {lst} { - set n [llength $lst] - if {$n <= 1} { return $lst } - quicksortInPlace lst 0 [expr {$n - 1}] - return $lst -} - -proc formatList {lst} { return [join $lst ", "] } - -if {$argc != 1} { usage } - -set numbers [parseList [lindex $argv 0]] -puts [formatList [quicksort $numbers]] - - -``` - -{% endraw %} - -Quick Sort in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/typescript/index.md b/docs/projects/quick-sort/typescript/index.md deleted file mode 100644 index c17d5b3c1a..0000000000 --- a/docs/projects/quick-sort/typescript/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Raakesh.R -date: 2023-10-21 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2023-10-21 -layout: default -tags: -- quick-sort -- typescript -title: Quick Sort in TypeScript -title1: Quick Sort in -title2: TypeScript ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function quickSort(arr: number[]): number[] { - if (arr.length <= 1) { - return arr; - } - - const pivot = arr[0]; - const left = []; - const right = []; - - for (let i = 1; i < arr.length; i++) { - if (arr[i] < pivot) { - left.push(arr[i]); - } else { - right.push(arr[i]); - } - } - - return [...quickSort(left), pivot, ...quickSort(right)]; -} - -const error_msg: string = - 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - -if (process.argv.length != 3) { - console.log(error_msg); - process.exit(1); -} - -let list_str: string = process.argv[2]; - -if (list_str.length == 0) { - console.log(error_msg); - process.exit(1); -} -let list: number[] = list_str.split(",").map((x: string) => parseInt(x)); -if (list.length < 2) { - console.log(error_msg); - process.exit(1); -} -const sortedArray: number[] = quickSort(list); -console.log(sortedArray.join(", ")); - -``` - -{% endraw %} - -Quick Sort in [TypeScript](/languages/typescript) was written by: - -- Raakesh.R - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quick-sort/visual-basic/index.md b/docs/projects/quick-sort/visual-basic/index.md deleted file mode 100644 index 208f751294..0000000000 --- a/docs/projects/quick-sort/visual-basic/index.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: quick-sort-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- quick-sort -- visual-basic -title: Quick Sort in Visual Basic -title1: Quick Sort in -title2: Visual Basic ---- - - - -Welcome to the [Quick Sort](/projects/quick-sort) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module QuickSort - - Public Function Sort(Of T)(input As IEnumerable(Of T), - Optional compare As IComparer(Of T) = Nothing) As List(Of T) - - If compare Is Nothing Then - compare = Comparer(Of T).Default - End If - - Dim list As New List(Of T)(input) - If list.Count < 2 Then Return list - - QuickSortInternal(list, 0, list.Count - 1, compare) - Return list - - End Function - - - Private Sub QuickSortInternal(Of T)(list As List(Of T), - low As Integer, - high As Integer, - comparer As IComparer(Of T)) - - If low >= high Then - Return - End If - - Dim pivotIndex As Integer = Partition(list, low, high, comparer) - - QuickSortInternal(list, low, pivotIndex - 1, comparer) - QuickSortInternal(list, pivotIndex + 1, high, comparer) - - End Sub - - - Private Function Partition(Of T)(list As List(Of T), - low As Integer, - high As Integer, - comparer As IComparer(Of T)) As Integer - - Dim pivot = list(high) - Dim i As Integer = low - 1 - - For j As Integer = low To high - 1 - - If comparer.Compare(list(j), pivot) <= 0 Then - i += 1 - Swap(list, i, j) - End If - - Next - - Swap(list, i + 1, high) - - Return i + 1 - - End Function - - - Private Sub Swap(Of T)(list As List(Of T), i As Integer, j As Integer) - Dim temp = list(i) - list(i) = list(j) - list(j) = temp - End Sub - - - Private Sub ShowUsage() - - Console.WriteLine( - "Usage: please provide a list of at least two integers to sort " & - "in the format ""1, 2, 3, 4, 5""" - ) - - Environment.Exit(1) - - End Sub - - - Public Sub Main(args As String()) - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim parts = args(0).Split(","c, StringSplitOptions.RemoveEmptyEntries) - - Dim numbers As New List(Of Integer) - - For Each p In parts - - Dim value As Integer - - If Not Integer.TryParse(p.Trim(), value) Then - ShowUsage() - End If - - numbers.Add(value) - - Next - - If numbers.Count < 2 Then - ShowUsage() - End If - - Dim sorted = Sort(numbers) - - Console.WriteLine(String.Join(", ", sorted)) - - End Sub - -End Module -``` - -{% endraw %} - -Quick Sort in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/algol60/index.md b/docs/projects/quine/algol60/index.md deleted file mode 100644 index ea25f70457..0000000000 --- a/docs/projects/quine/algol60/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-28 -featured-image: quine-in-every-language.jpg -last-modified: 2026-03-28 -layout: default -tags: -- algol60 -- quine -title: Quine in ALGOL 60 -title1: Quine in -title2: ALGOL 60 ---- - - - -Welcome to the [Quine](/projects/quine) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin procedure q(a,b,c);string a,b,c;begin outstring(1,c);outchar(1,a,2);outchar(1,a,1);outchar(1,a,1);outstring(1,a);outchar(1,a,2);outchar(1,a,3);outchar(1,a,2);outstring(1,b);outchar(1,a,2);outchar(1,a,3);outchar(1,a,2);outstring(1,c);outchar(1,a,2);outstring(1,b) end q;q("\\\",",") end","begin procedure q(a,b,c);string a,b,c;begin outstring(1,c);outchar(1,a,2);outchar(1,a,1);outchar(1,a,1);outstring(1,a);outchar(1,a,2);outchar(1,a,3);outchar(1,a,2);outstring(1,b);outchar(1,a,2);outchar(1,a,3);outchar(1,a,2);outstring(1,c);outchar(1,a,2);outstring(1,b) end q;q(") end -``` - -{% endraw %} - -Quine in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/algol68/index.md b/docs/projects/quine/algol68/index.md deleted file mode 100644 index b3670199cc..0000000000 --- a/docs/projects/quine/algol68/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-22 -featured-image: quine-in-every-language.jpg -last-modified: 2023-01-22 -layout: default -tags: -- algol68 -- quine -title: Quine in ALGOL 68 -title1: Quine in -title2: ALGOL 68 ---- - - - -Welcome to the [Quine](/projects/quine) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -STRINGs:="STRINGs:="";printf(($gl$,s[:10]*2+s[10:]*2))";printf(($gl$,s[:10]*2+s[10:]*2)) - -``` - -{% endraw %} - -Quine in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/awk/index.md b/docs/projects/quine/awk/index.md deleted file mode 100644 index 1c23849877..0000000000 --- a/docs/projects/quine/awk/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-07 -featured-image: quine-in-every-language.jpg -last-modified: 2025-04-07 -layout: default -tags: -- awk -- quine -title: Quine in AWK -title1: Quine -title2: in AWK ---- - - - -Welcome to the [Quine](/projects/quine) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -BEGIN{s="BEGIN{s=%c%s%c;printf(s,34,s,34,10)}%c";printf(s,34,s,34,10)} - -``` - -{% endraw %} - -Quine in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/bash/index.md b/docs/projects/quine/bash/index.md deleted file mode 100644 index 3c3fbdd7bc..0000000000 --- a/docs/projects/quine/bash/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeng -date: 2020-10-04 -featured-image: quine-in-every-language.jpg -last-modified: 2020-10-04 -layout: default -tags: -- bash -- quine -title: Quine in Bash -title1: Quine -title2: in Bash ---- - - - -Welcome to the [Quine](/projects/quine) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -echo $BASH_COMMAND - -``` - -{% endraw %} - -Quine in [Bash](/languages/bash) was written by: - -- Jeng - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/beef/index.md b/docs/projects/quine/beef/index.md deleted file mode 100644 index b2d0246d6b..0000000000 --- a/docs/projects/quine/beef/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-18 -featured-image: quine-in-every-language.jpg -last-modified: 2024-01-18 -layout: default -tags: -- beef -- quine -title: Quine in Beef -title1: Quine -title2: in Beef ---- - - - -Welcome to the [Quine](/projects/quine) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -namespace Quine; -class Program -{ - public static int Main(String[] args) - { - String s = """ -using System; -namespace Quine; -class Program -{{ - public static int Main(String[] args) - {{ - String s = {1}{1}{1} -{0} -{1}{1}{1}; - Console.WriteLine(s, s, '"'); - return 0; - }} -}} -"""; - Console.WriteLine(s, s, '"'); - return 0; - } -} - -``` - -{% endraw %} - -Quine in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/befunge/index.md b/docs/projects/quine/befunge/index.md deleted file mode 100644 index bd9c62e02c..0000000000 --- a/docs/projects/quine/befunge/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-12 -featured-image: quine-in-every-language.jpg -last-modified: 2025-04-12 -layout: default -tags: -- befunge -- quine -title: Quine in Befunge -title1: Quine in -title2: Befunge ---- - - - -Welcome to the [Quine](/projects/quine) in [Befunge](/languages/befunge) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```befunge -:0g,:66+`#@_1+ -``` - -{% endraw %} - -Quine in [Befunge](/languages/befunge) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/c-plus-plus/index.md b/docs/projects/quine/c-plus-plus/index.md deleted file mode 100644 index 414efbca88..0000000000 --- a/docs/projects/quine/c-plus-plus/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: quine-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- c-plus-plus -- quine -title: Quine in C++ -title1: Quine -title2: in C++ ---- - - - -Welcome to the [Quine](/projects/quine) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -char*s="#include %cchar*s=%c%s%c;%cint main(){printf(s,10,34,s,34,10,10);}%c"; -int main(){printf(s,10,34,s,34,10,10);} -``` - -{% endraw %} - -Quine in [C++](/languages/c-plus-plus) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/c-sharp/index.md b/docs/projects/quine/c-sharp/index.md deleted file mode 100644 index 6a86310621..0000000000 --- a/docs/projects/quine/c-sharp/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-12-30 -featured-image: quine-in-every-language.jpg -last-modified: 2018-12-30 -layout: default -tags: -- c-sharp -- quine -title: Quine in C# -title1: Quine -title2: in C# ---- - - - -Welcome to the [Quine](/projects/quine) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -class Quine { static void Main() { var s = "class Quine {{ static void Main() {{ var s = {0}{1}{0}; System.Console.WriteLine(s, (char)34, s); }} }}"; System.Console.WriteLine(s, (char)34, s); } } -``` - -{% endraw %} - -Quine in [C#](/languages/c-sharp) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/c/index.md b/docs/projects/quine/c/index.md deleted file mode 100644 index de10a43e1d..0000000000 --- a/docs/projects/quine/c/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- Juan D Frias -date: 2019-10-18 -featured-image: quine-in-every-language.jpg -last-modified: 2019-10-18 -layout: default -tags: -- c -- quine -title: Quine in C -title1: Quine -title2: in C ---- - - - -Welcome to the [Quine](/projects/quine) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include "stdio.h" -int main() { char* s="#include %cstdio.h%c%cint main() { char* s=%c%s%c; printf(s,34,34,10,34,s,34,10); return 0; }%c"; printf(s,34,34,10,34,s,34,10); return 0; } - -``` - -{% endraw %} - -Quine in [C](/languages/c) was written by: - -- Juan D Frias - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/cobol/index.md b/docs/projects/quine/cobol/index.md deleted file mode 100644 index 1ee4dd2af8..0000000000 --- a/docs/projects/quine/cobol/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: quine-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- quine -title: Quine in COBOL -title1: Quine in -title2: COBOL ---- - - - -Welcome to the [Quine](/projects/quine) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -program-id.quine.data division.linkage section. 78 c value"procedure division.display'program-id.quine.data division.linkage section. 78 c value'x'22'c x'222e'c.".procedure division.display'program-id.quine.data division.linkage section. 78 c value'x'22'c x'222e'c. - -``` - -{% endraw %} - -Quine in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/coffeescript/index.md b/docs/projects/quine/coffeescript/index.md deleted file mode 100644 index ba49af43e6..0000000000 --- a/docs/projects/quine/coffeescript/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeng -date: 2020-10-04 -featured-image: quine-in-every-language.jpg -last-modified: 2020-10-04 -layout: default -tags: -- coffeescript -- quine -title: Quine in CoffeeScript -title1: Quine in -title2: CoffeeScript ---- - - - -Welcome to the [Quine](/projects/quine) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -a="a=%j; console.log a,a"; console.log a,a - -``` - -{% endraw %} - -Quine in [CoffeeScript](/languages/coffeescript) was written by: - -- Jeng - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/commodore-basic/index.md b/docs/projects/quine/commodore-basic/index.md deleted file mode 100644 index 41148145f3..0000000000 --- a/docs/projects/quine/commodore-basic/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: quine-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- quine -title: Quine in Commodore BASIC -title1: Quine in -title2: Commodore BASIC ---- - - - -Welcome to the [Quine](/projects/quine) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 LIST - -``` - -{% endraw %} - -Quine in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/cython/index.md b/docs/projects/quine/cython/index.md deleted file mode 100644 index c6d7fec550..0000000000 --- a/docs/projects/quine/cython/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-31 -featured-image: quine-in-every-language.jpg -last-modified: 2025-10-31 -layout: default -tags: -- cython -- quine -title: Quine in Cython -title1: Quine in -title2: Cython ---- - - - -Welcome to the [Quine](/projects/quine) in [Cython](/languages/cython) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cython -from libc.stdio cimport printf - -def main(): - cdef bytes s = b"""from libc.stdio cimport printf - -def main(): - cdef bytes s = b%c%c%c%s%c%c%c - printf(s, 34, 34, 34, s, 34, 34, 34) - -if __name__ == "__main__": - main()""" - printf(s, 34, 34, 34, s, 34, 34, 34) - -if __name__ == "__main__": - main() - -``` - -{% endraw %} - -Quine in [Cython](/languages/cython) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/dg/index.md b/docs/projects/quine/dg/index.md deleted file mode 100644 index 7d8322fcda..0000000000 --- a/docs/projects/quine/dg/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- Riley Martine -date: 2018-10-03 -featured-image: quine-in-every-language.jpg -last-modified: 2018-10-03 -layout: default -tags: -- dg -- quine -title: Quine in Dg -title1: Quine -title2: in Dg ---- - - - -Welcome to the [Quine](/projects/quine) in [Dg](/languages/dg) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dg -s = 's = %r\nprint $ s%%s' -print $ s%s - -``` - -{% endraw %} - -Quine in [Dg](/languages/dg) was written by: - -- Riley Martine - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/euphoria/index.md b/docs/projects/quine/euphoria/index.md deleted file mode 100644 index 5ac75e862f..0000000000 --- a/docs/projects/quine/euphoria/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-15 -featured-image: quine-in-every-language.jpg -last-modified: 2023-02-15 -layout: default -tags: -- euphoria -- quine -title: Quine in Euphoria -title1: Quine in -title2: Euphoria ---- - - - -Welcome to the [Quine](/projects/quine) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -constant s="constant s=%s%s%sprintf(1,s&10,{34,s,34})"printf(1,s&10,{34,s,34}) - -``` - -{% endraw %} - -Quine in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/f-sharp/index.md b/docs/projects/quine/f-sharp/index.md deleted file mode 100644 index 9988caf35d..0000000000 --- a/docs/projects/quine/f-sharp/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: quine-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- quine -title: Quine in F# -title1: Quine -title2: in F# ---- - - - -Welcome to the [Quine](/projects/quine) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -let s = "let s = {0}{1}{0} in System.Console.WriteLine(s, char 34, s);;" in System.Console.WriteLine(s, char 34, s);; -``` - -{% endraw %} - -Quine in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/gnu-make/index.md b/docs/projects/quine/gnu-make/index.md deleted file mode 100644 index 982b598e48..0000000000 --- a/docs/projects/quine/gnu-make/index.md +++ /dev/null @@ -1,153 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-02 -featured-image: quine-in-every-language.jpg -last-modified: 2023-08-07 -layout: default -tags: -- gnu-make -- quine -title: Quine in GNU Make -title1: Quine in -title2: GNU Make ---- - - - -Welcome to the [Quine](/projects/quine) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -q=$(info q=$(value q))$(info $$(q))$(eval q:;@:) -$(q) - -``` - -{% endraw %} - -Quine in [GNU Make](/languages/gnu-make) was written by: - -- rzuckerm - -This article was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -I can't take credit for this solution. I got the code from [Rosetta Code][1]. - -Let's break it down. First, there is this variable assignment: - -```make -q=$(info q=$(value q))$(info $$(q))$(eval q:;@:) -``` - -Since `=` is used, [deferred evaluation is done][2]. This means that the -expression is not evaluated until it is needs to be. In other words, the -variable `q` is just set to the value after the equal sign. - -The real magic doesn't happen until this line: - -```make -$(q) -``` - -This forces `q` to be evaluted. The first expression to be evaluated is this: - -```make -$(info q=$(value q)) -``` - -The [value][3] function returns the value of the specified variable without -expanding it. The [info][4] function displays the text that follows it. -Putting those together, this displays the `q=` followed by the value of `q`. -This displays the first line of the code. - -The second expression to be evaluated is this: - -```make -$(info $$(q)) -``` - -The `$$` is just the way that a literal `$` character must be represented -since `$` has a special meaning in GNU Make. Therefore, this just displays the -second line of the code. - -The final expression to be evaluated is this: - -```make -$(eval q:;@:) -``` - -The [eval][5] function evaluation the expression that follows it and returns -an empty string. In this case, it is creating this target: - -```make -q:;@: -``` - -Since GNU Make is a build system, it needs something to build, or else it will -give this error: - -``` -make: *** No targets. Stop. -``` - -To give `make` something to do, this "do nothing" target called `q` is -provided. The `q` target is written in the [alternate form][6]. - -```make -target:;command -``` - -This means that whenever the target needs to be built, `make` will execute the -command following the semicolon. By default, `make` [echoes each command][7] -that it executes. To suppress this, `@` may be used before the command. The -[colon (:) command][8] just exits with non-error status. - - -[1]: https://rosettacode.org/wiki/Quine#make -[2]: https://www.gnu.org/software/make/manual/html_node/Reading-Makefiles.html -[3]: https://www.gnu.org/software/make/manual/html_node/Value-Function.html -[4]: https://www.gnu.org/software/make/manual/html_node/Make-Control-Functions.html -[5]: https://www.gnu.org/software/make/manual/html_node/Eval-Function.html -[6]: https://www.gnu.org/software/make/manual/html_node/Rule-Syntax.html -[7]: https://www.gnu.org/software/make/manual/html_node/Echoing.html -[8]: https://man7.org/linux/man-pages/man1/colon.1p.html - - -## How to Run the Solution - -To run this program, download and install the latest GNU Make using these -instructions: - -* [Windows][9] -* For [Linux][10], see "How to Download" section -* [Mac][11] - -Download a copy of [Quine in GNU Make][12], and run this command: - -``` -make -sf quine.mk -``` - -[9]: https://leangaurav.medium.com/how-to-setup-install-gnu-make-on-windows-324480f1da69 -[10]: https://www.incredibuild.com/integrations/gnu-make -[11]: https://formulae.brew.sh/formula/make -[12]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/g/gnu-make/quine.mk diff --git a/docs/projects/quine/go/index.md b/docs/projects/quine/go/index.md deleted file mode 100644 index 862f7f5e52..0000000000 --- a/docs/projects/quine/go/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-03-17 -featured-image: quine-in-every-language.jpg -last-modified: 2019-03-17 -layout: default -tags: -- go -- quine -title: Quine in Go -title1: Quine -title2: in Go ---- - - - -Welcome to the [Quine](/projects/quine) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import "fmt" - -func main() { - a := "package main\n\nimport \"fmt\"\n\nfunc main() {\n\ta := %q\n\tfmt.Printf(a, a)\n}\n" - fmt.Printf(a, a) -} - -``` - -{% endraw %} - -Quine in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/haskell/index.md b/docs/projects/quine/haskell/index.md deleted file mode 100644 index 2b9493b0a7..0000000000 --- a/docs/projects/quine/haskell/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-11-19 -featured-image: quine-in-every-language.jpg -last-modified: 2018-11-19 -layout: default -tags: -- haskell -- quine -title: Quine in Haskell -title1: Quine in -title2: Haskell ---- - - - -Welcome to the [Quine](/projects/quine) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -main = putStrLn $ (++) <*> show $ "main = putStrLn $ (++) <*> show $ " - -``` - -{% endraw %} - -Quine in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/index.md b/docs/projects/quine/index.md deleted file mode 100644 index 96b42c0302..0000000000 --- a/docs/projects/quine/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -date: 2018-08-07 -featured-image: quine-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- quine -title: Quine -title1: Quine -title2: '' ---- - - - -Welcome to the Quine page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman -- rzuckerm - -## Description - -For those of you that don't know, a quine is a program which can replicate -itself--or more specifically: - -> A quine is a non-empty computer program which takes no input and produces a -> copy of its own source code as its only output. - -Thanks, [Wikipedia][1]! - -[1]: https://en.wikipedia.org/wiki/Quine_(computing) - - -## Requirements - -For the purposes of this repo, the solution should be simple. We're not here -to play code golf, but we're also not here to practice obfuscation. Just be -reasonable with your solution. Finally, the solution must **not** read its own -source code file. For example, this is **not** a permissible solution: - -```python -with open("quine.py") as f: - print(f.read()) -``` - - -## Testing - -Verify that the actual output matches the expected output -(see [Requirements](#requirements)). - - -## Articles - -There are 37 articles: - -- [Quine in ALGOL 60](/projects/quine/algol60) -- [Quine in ALGOL 68](/projects/quine/algol68) -- [Quine in AWK](/projects/quine/awk) -- [Quine in Bash](/projects/quine/bash) -- [Quine in Beef](/projects/quine/beef) -- [Quine in Befunge](/projects/quine/befunge) -- [Quine in C](/projects/quine/c) -- [Quine in C#](/projects/quine/c-sharp) -- [Quine in C++](/projects/quine/c-plus-plus) -- [Quine in COBOL](/projects/quine/cobol) -- [Quine in CoffeeScript](/projects/quine/coffeescript) -- [Quine in Commodore BASIC](/projects/quine/commodore-basic) -- [Quine in Cython](/projects/quine/cython) -- [Quine in Dg](/projects/quine/dg) -- [Quine in Euphoria](/projects/quine/euphoria) -- [Quine in F#](/projects/quine/f-sharp) -- [Quine in GNU Make](/projects/quine/gnu-make) -- [Quine in Go](/projects/quine/go) -- [Quine in Haskell](/projects/quine/haskell) -- [Quine in Java](/projects/quine/java) -- [Quine in JavaScript](/projects/quine/javascript) -- [Quine in Kotlin](/projects/quine/kotlin) -- [Quine in Mathematica](/projects/quine/mathematica) -- [Quine in PHP](/projects/quine/php) -- [Quine in Pascal](/projects/quine/pascal) -- [Quine in Perl](/projects/quine/perl) -- [Quine in PowerShell](/projects/quine/powershell) -- [Quine in Python](/projects/quine/python) -- [Quine in Ruby](/projects/quine/ruby) -- [Quine in Rust](/projects/quine/rust) -- [Quine in Swift](/projects/quine/swift) -- [Quine in Tcl](/projects/quine/tcl) -- [Quine in TypeScript](/projects/quine/typescript) -- [Quine in Visual Basic](/projects/quine/visual-basic) -- [Quine in Whitespace](/projects/quine/whitespace) -- [Quine in m4](/projects/quine/m4) -- [Quine in x86-64](/projects/quine/x86-64) - -*** - - \ No newline at end of file diff --git a/docs/projects/quine/java/index.md b/docs/projects/quine/java/index.md deleted file mode 100644 index bc54015784..0000000000 --- a/docs/projects/quine/java/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Karl Marx -date: 2020-10-04 -featured-image: quine-in-every-language.jpg -last-modified: 2020-10-04 -layout: default -tags: -- java -- quine -title: Quine in Java -title1: Quine -title2: in Java ---- - - - -Welcome to the [Quine](/projects/quine) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class Quine{public static void main(String[] args){char quote=34;String code="public class Quine{public static void main(String[] args){char quote=34;String code=;System.out.println(code.substring(0,84)+quote+code+quote+code.substring(84));}}";System.out.println(code.substring(0,84)+quote+code+quote+code.substring(84));}} - -``` - -{% endraw %} - -Quine in [Java](/languages/java) was written by: - -- Karl Marx - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/javascript/index.md b/docs/projects/quine/javascript/index.md deleted file mode 100644 index e59c361912..0000000000 --- a/docs/projects/quine/javascript/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-05-04 -featured-image: quine-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- javascript -- quine -title: Quine in JavaScript -title1: Quine in -title2: JavaScript ---- - - - -Welcome to the [Quine](/projects/quine) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -(function(){console.log('('+arguments.callee.toString()+')();')})(); - -``` - -{% endraw %} - -Quine in [JavaScript](/languages/javascript) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/kotlin/index.md b/docs/projects/quine/kotlin/index.md deleted file mode 100644 index b8b59f8e53..0000000000 --- a/docs/projects/quine/kotlin/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- Stuart Irwin -date: 2019-10-19 -featured-image: quine-in-every-language.jpg -last-modified: 2019-10-19 -layout: default -tags: -- kotlin -- quine -title: Quine in Kotlin -title1: Quine in -title2: Kotlin ---- - - - -Welcome to the [Quine](/projects/quine) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array) { //Prints out it's own code - val s = """fun main(args: Array) { //Prints out it's own code - val s = """ - - val a = """^s\"\"\"^s\"\"\"\n\n\tval a = \"\"\"^a\"\"\"\n\tprint(\"^{a.replace(']' + 1, '$')}\")\n}\n""" - print("$s\"\"\"$s\"\"\"\n\n\tval a = \"\"\"$a\"\"\"\n\tprint(\"${a.replace(']' + 1, '$')}\")\n}\n") -} -``` - -{% endraw %} - -Quine in [Kotlin](/languages/kotlin) was written by: - -- Stuart Irwin - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/m4/index.md b/docs/projects/quine/m4/index.md deleted file mode 100644 index b00801b0e6..0000000000 --- a/docs/projects/quine/m4/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-09 -featured-image: quine-in-every-language.jpg -last-modified: 2025-08-09 -layout: default -tags: -- m4 -- quine -title: Quine in m4 -title1: Quine -title2: in m4 ---- - - - -Welcome to the [Quine](/projects/quine) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -define(`q',``$1(`$1')'')dnl -q(`define(`q',``$1(`$1')'')dnl -q') -``` - -{% endraw %} - -Quine in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/mathematica/index.md b/docs/projects/quine/mathematica/index.md deleted file mode 100644 index 4c5da08110..0000000000 --- a/docs/projects/quine/mathematica/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-17 -featured-image: quine-in-every-language.jpg -last-modified: 2023-01-17 -layout: default -tags: -- mathematica -- quine -title: Quine in Mathematica -title1: Quine in -title2: Mathematica ---- - - - -Welcome to the [Quine](/projects/quine) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Credit to https://mathematica.stackexchange.com/a/6110/61814 for this answer: *) - -Print[ToString[#0][]] &[] - -``` - -{% endraw %} - -Quine in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/pascal/index.md b/docs/projects/quine/pascal/index.md deleted file mode 100644 index 70578c0612..0000000000 --- a/docs/projects/quine/pascal/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-21 -featured-image: quine-in-every-language.jpg -last-modified: 2025-07-21 -layout: default -tags: -- pascal -- quine -title: Quine in Pascal -title1: Quine in -title2: Pascal ---- - - - -Welcome to the [Quine](/projects/quine) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program s;const bbb='program s;const bbb';a='a';b='b';bb=');writeln('; -aa='''';ab='=''';ba=''';'; -aaa='begin writeln(bbb,ab,bbb,ba,a,ab,a,ba,b,ab,b,ba,b,b,ab,bb,ba'; -aba='a,a,ab,aa,aa,ba,a,b,ab,ab,aa,ba,b,a,ab,aa,ba,ba'; -abb='a,a,a,ab,aaa,ba);writeln(a,b,a,ab,aba,ba);writeln(a,b,b,ab,abb,ba'; -baa='b,a,a,ab,baa,ba);writeln(b,a,b,ab,bab,ba);writeln(aaa,bb'; -bab='aba,bb);writeln(abb);writeln(bb,baa);writeln(bb,bab)end.'; -begin writeln(bbb,ab,bbb,ba,a,ab,a,ba,b,ab,b,ba,b,b,ab,bb,ba);writeln( -a,a,ab,aa,aa,ba,a,b,ab,ab,aa,ba,b,a,ab,aa,ba,ba);writeln( -a,a,a,ab,aaa,ba);writeln(a,b,a,ab,aba,ba);writeln(a,b,b,ab,abb,ba -);writeln(b,a,a,ab,baa,ba);writeln(b,a,b,ab,bab,ba);writeln(aaa,bb -);writeln(aba,bb);writeln(abb);writeln(bb,baa);writeln(bb,bab)end. - -``` - -{% endraw %} - -Quine in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/perl/index.md b/docs/projects/quine/perl/index.md deleted file mode 100644 index 676e707928..0000000000 --- a/docs/projects/quine/perl/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Juan D Frias -date: 2019-10-18 -featured-image: quine-in-every-language.jpg -last-modified: 2019-10-18 -layout: default -tags: -- perl -- quine -title: Quine in Perl -title1: Quine -title2: in Perl ---- - - - -Welcome to the [Quine](/projects/quine) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -$s='$s=%c%s%c;printf($s,39,$s,39,10);%c';printf($s,39,$s,39,10); - -``` - -{% endraw %} - -Quine in [Perl](/languages/perl) was written by: - -- Juan D Frias - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/php/index.md b/docs/projects/quine/php/index.md deleted file mode 100644 index 93448c9153..0000000000 --- a/docs/projects/quine/php/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Juan D Frias -date: 2019-10-18 -featured-image: quine-in-every-language.jpg -last-modified: 2019-10-18 -layout: default -tags: -- php -- quine -title: Quine in PHP -title1: Quine -title2: in PHP ---- - - - -Welcome to the [Quine](/projects/quine) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php -%c'; printf($s,39,$s,39,10); ?> - -``` - -{% endraw %} - -Quine in [PHP](/languages/php) was written by: - -- Juan D Frias - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/powershell/index.md b/docs/projects/quine/powershell/index.md deleted file mode 100644 index 4e3e94397e..0000000000 --- a/docs/projects/quine/powershell/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-05-12 -featured-image: quine-in-every-language.jpg -last-modified: 2025-05-12 -layout: default -tags: -- powershell -- quine -title: Quine in PowerShell -title1: Quine in -title2: PowerShell ---- - - - -Welcome to the [Quine](/projects/quine) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -$S='$S={0}{1}{0}{2}Write-Host ($S -f [string][char]39,$S,[string][char]10)' -Write-Host ($S -f [string][char]39,$S,[string][char]10) - -``` - -{% endraw %} - -Quine in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/python/index.md b/docs/projects/quine/python/index.md deleted file mode 100644 index 6813e2edab..0000000000 --- a/docs/projects/quine/python/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-08-07 -featured-image: quine-in-every-language.jpg -last-modified: 2018-08-07 -layout: default -tags: -- python -- quine -title: Quine in Python -title1: Quine in -title2: Python ---- - - - -Welcome to the [Quine](/projects/quine) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -s='s=%r;print(s%%s)';print(s%s) - -``` - -{% endraw %} - -Quine in [Python](/languages/python) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/ruby/index.md b/docs/projects/quine/ruby/index.md deleted file mode 100644 index c6afb48d09..0000000000 --- a/docs/projects/quine/ruby/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2018-08-12 -featured-image: quine-in-every-language.jpg -last-modified: 2018-08-12 -layout: default -tags: -- quine -- ruby -title: Quine in Ruby -title1: Quine -title2: in Ruby ---- - - - -Welcome to the [Quine](/projects/quine) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -s="s=%c%s%c; printf s,34,s,34,10%c"; printf s,34,s,34,10 - -``` - -{% endraw %} - -Quine in [Ruby](/languages/ruby) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/rust/index.md b/docs/projects/quine/rust/index.md deleted file mode 100644 index 01b2917eb0..0000000000 --- a/docs/projects/quine/rust/index.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -authors: -- Ron Zuckerman -- rzuckerm -date: 2023-04-05 -featured-image: quine-in-rust.jpg -last-modified: 2023-04-06 -layout: default -tags: -- quine -- rust -title: Quine in Rust -title1: Quine -title2: in Rust ---- - - - -Welcome to the [Quine](/projects/quine) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -fn main(){println!("fn main(){{println!({0:?},{0:?})}}","fn main(){{println!({0:?},{0:?})}}")} - -``` - -{% endraw %} - -Quine in [Rust](/languages/rust) was written by: - -- rzuckerm - -This article was written by: - -- Ron Zuckerman -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's break this down. In Rust, the `println!` function displays the desired text -with a newline. The first argument of `println!` is either an ordinary string or -a format string. If it is a format string, the subsequent arguments are values -to be formatted. Format strings in Rust are rather complex and powerful. If you -want to learn more about this, see the -[official Rust documentation](https://doc.rust-lang.org/std/fmt/). - -Let's take at look at this particular one: - -{% raw %} -``` -{0:?} -``` -{% endraw %} - -* All format strings are enclosed in braces `{}`. -* `0` means the first (zeroth in 0-based counting) argument after the format - string. -* `:?` shows an item in its natural form. For strings, this shows the value - enclosed in double quotes. - -You'll notice that both the format string and the value to be formatted are -identical: - -{% raw %} -``` -"fn main(){{println!({0:?},{0:?})}}" -``` -{% endraw %} - -In other words, we're using the format string to format itself! Notice that -these characters are used in this format string: - -{% raw %} -* `{{` -* `}}` -{% endraw %} - -These display like this, respectively: - -{% raw %} -* `{` -* `}` -{% endraw %} - -The braces have to be doubled up since, as mentioned above, all format string -are enclosed in braces. - -Notice that the left side of that string is this: - -{% raw %} -``` -fn main(){{println!( -``` -{% endraw %} - -That corresponds to the left-hand side of the program. The right-hand side of -that string is this: - -{% raw %} -``` -)}} -``` -{% endraw %} - -That corresponds to the right-hand side of the program. If you put this all -together, you will get this output: - -{% raw %} -```rust -fn main(){println!("fn main(){{println!({0:?},{0:?})}}","fn main(){{println!({0:?},{0:?})}}")} -``` -{% endraw %} - -This is the same as the program. How cool is that?! - -Anyway, I have to give credit where credit is due. I am a Rust newbie, and I -would be hard-pressed to come up with this on my own. I got this code -[here](https://cs.lmu.edu/~ray/notes/quineprograms/); scroll down the Rust -implementation. However, I learned a lot from this, and now I truly understand it -after writing this article. - - -## How to Run the Solution - -If you want to run this program, you'll first need to download a -copy of the -[Rust compiler](https://www.rust-lang.org/tools/install), -and follow the installation instructions. From there, open a terminal, and -run this command: - -``` -rustc quine.rs -./quine -``` diff --git a/docs/projects/quine/swift/index.md b/docs/projects/quine/swift/index.md deleted file mode 100644 index f9626dda67..0000000000 --- a/docs/projects/quine/swift/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: quine-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- quine -- swift -title: Quine in Swift -title1: Quine in -title2: Swift ---- - - - -Welcome to the [Quine](/projects/quine) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -let s = "print(\"let s = \\(s.debugDescription)\\n\\(s)\")" -print("let s = \(s.debugDescription)\n\(s)") -``` - -{% endraw %} - -Quine in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/tcl/index.md b/docs/projects/quine/tcl/index.md deleted file mode 100644 index 6d7ac23ad5..0000000000 --- a/docs/projects/quine/tcl/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: quine-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- quine -- tcl -title: Quine in Tcl -title1: Quine -title2: in Tcl ---- - - - -Welcome to the [Quine](/projects/quine) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc q {} {foreach {p a} [info level 0] {puts "[list proc $p $a [info body $p]];$p"}};q - -``` - -{% endraw %} - -Quine in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/typescript/index.md b/docs/projects/quine/typescript/index.md deleted file mode 100644 index 7bf4a4352b..0000000000 --- a/docs/projects/quine/typescript/index.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: quine-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- quine -- typescript -title: Quine in TypeScript -title1: Quine in -title2: TypeScript ---- - - - -Welcome to the [Quine](/projects/quine) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -var s=";console.log('var s='+JSON.stringify(s)+s);";console.log('var s='+JSON.stringify(s)+s); -``` - -{% endraw %} - -Quine in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/visual-basic/index.md b/docs/projects/quine/visual-basic/index.md deleted file mode 100644 index 1f7f61d425..0000000000 --- a/docs/projects/quine/visual-basic/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: quine-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- quine -- visual-basic -title: Quine in Visual Basic -title1: Quine in -title2: Visual Basic ---- - - - -Welcome to the [Quine](/projects/quine) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Module Quine - Sub Main() - Dim s As String = "Module Quine{0} Sub Main(){0} Dim s As String = {1}{2}{1}{0} Console.WriteLine(s, Chr(10), Chr(34), s){0} End Sub{0}End Module" - Console.WriteLine(s, Chr(10), Chr(34), s) - End Sub -End Module -``` - -{% endraw %} - -Quine in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/quine/whitespace/index.md b/docs/projects/quine/whitespace/index.md deleted file mode 100644 index c933d4bea4..0000000000 --- a/docs/projects/quine/whitespace/index.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-16 -featured-image: quine-in-whitespace.jpg -last-modified: 2025-04-27 -layout: default -tags: -- quine -- whitespace -title: Quine in Whitespace -title1: Quine in -title2: Whitespace ---- - - - -Welcome to the [Quine](/projects/quine) in [Whitespace](/languages/whitespace) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```whitespace - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -``` - -{% endraw %} - -Quine in [Whitespace](/languages/whitespace) was written by: - -- rzuckerm - -This article was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -The code listed in the "Current Solution" section looks like a polar bear in a -blizzard! In other words, it is nothing but whitespace characters. The reason -is two-fold: - -1. In Whitespace, the only characters that contain instructions are whitespace - characters. Everything else is ignored. -2. While it is possible to write a program that generates comments or other - annotation, it would require a lot more code to do so. It is easier to just - generate the whitespace characters that represent the code. - -At the highest level, the code consists of the following: - -- Push P (an integer value that represents the rest of the code) onto the - stack. -- The rest of the code (for brevity, let's call this R). - -The value of P is calculated by representing each whitespace character in -R as a base-3 number, least-significant value first, where: - -- 0 = space -- 1 = tab -- 2 = linefeed - -In other words: - -- P = 30r1 + 31r2 + 32r3 + ... + 3T-1rT - -where: - -- T is the number of values in R. -- ri is the ith value of R. - -P is a very large number: 125 base-10 digits! - -So how does this approach generate an output that is identical to the actual -program file? The idea is based on a [description in RosettaCode][1] (the code -is not present since it looks like RosettaCode trims whitespace, and the code -is all whitespace). Let's break it down. The rest of the code, R, does this: - -- Output the `Push` instruction as whitespace characters. -- Output P as whitespace characters. - -The `Push` instruction consists of the following: - -- The `Push` opcode: space, space -- The sign bit of P (0 for positive): space -- The value of P in base-2, most-significant bit first: space for 0, tab - for 1 -- The terminator for the `Push` instruction: newline - -Outputting the `Push` instruction consists of the following: - -- Output 3 spaces for the opcode and sign bit. -- Output the value of P as whitespace characters. -- Output linefeed. - -In order to easily translate integers into whitespace characters, memory -(`mem`) is set up as follows: - -- mem\[0\] = space -- mem\[1\] = tab -- mem\[2\] = linefeed - -Outputting the value of P as whitespace characters is done like this: - -- Find D = 2K such that D is greater than or equal to P: - ``` - D = 1 - Do - D = D * 2 - While D < P - ``` -- Output P in base-2, most-significant bit first, translated to whitespace - characters: - ``` - While (D = D // 2) != 0 - N = P // D - Output mem[N % 2] - End While - ``` - where `//` means integer division, and `%` means modulo. - -Outputting the rest of the program as whitespace characters consists of this: - -- Output P in base-3, least-significant value first, translated to whitespace - characters: - ``` - While P != 0 - Output mem[P % 3] - P = P // 3 - End While - ``` - -To balance out the stack and end the program, there is a `Pop` instruction and -an `End` instruction that tells the Whitespace interpreter to end the program, -but those are already accounted for in the value of P. - -To see this all together, take a look at the [Whitespace Assembly Code][2] -that was used to generate this sample. The Whitespace Assembly Language was -converted to whitespace characters using the [Whitespace Assembler][3]. This -sample is the output of the Assembler. - -[1]: https://rosettacode.org/wiki/Quine#Whitespace -[2]: https://github.com/rzuckerm/whitespace-quine/blob/main/quine.ws.asm -[3]: https://pypi.org/project/whitespace-asm/ - - -## How to Run the Solution - -To run this program: - -- Download a copy of [Quine in Whitespace][4]. -- Browse to the [Try It Online Whitespace Interpreter][5]. -- Open the code in an editor, select all, and copy the code to the clipboard. -- Paste it into the `Code` section in the browser window. The size of the code - should be 679 bytes. If it is less, scroll all the way to the bottom and - press Enter. -- Press the "Play" button at the top of the browser window to run the code. -- The `Output` section at the bottom should be identical to the original code. - -[4]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/w/whitespace/quine.ws -[5]: https://tio.run/#whitespace diff --git a/docs/projects/quine/x86-64/index.md b/docs/projects/quine/x86-64/index.md deleted file mode 100644 index 8e255a95c8..0000000000 --- a/docs/projects/quine/x86-64/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -authors: -- Raymond Marx -date: 2026-01-06 -featured-image: quine-in-every-language.jpg -last-modified: 2026-01-06 -layout: default -tags: -- quine -- x86-64 -title: Quine in x86-64 -title1: Quine in -title2: x86-64 ---- - - - -Welcome to the [Quine](/projects/quine) in [x86-64](/languages/x86-64) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```x86-64 -; SYSCALLS -%DEFINE SYS_READ 0 -%DEFINE SYS_WRITE 1 -%DEFINE STDOUT 1 -%DEFINE SYS_EXIT 60 -section .data -string: -.msg db "; SYSCALLS%DEFINE SYS_READ 0%DEFINE SYS_WRITE 1%DEFINE STDOUT 1%DEFINE SYS_EXIT 60section .datastring:.msg db .len equ $- .msgquote db 0x22newline db 0xAlinestarts dw 0, 10, 18, 19, 16, 19, 13, 7, 8linestarts2 dw 16, 13, 14, 45, 312, 17, 13, 13, 7, 19, 10, 11, 12, 6, 12, 18, 15, 12, 31, 24, 7, 12, 12, 8, 18, 15, 16, 10, 7, 12, 10, 12, 9, 6, 18, 15, 14, 10, 7, 18, 15, 19, 19, 7, 18, 15, 14, 10, 7, 18, 15, 16, 10, 7, 10, 6, 12, 18, 15, 12, 32, 25, 7, 12, 12, 8, 18, 15, 16, 10, 7, 12, 10, 12, 9, 6, 11, 10, 7%DEFINE PRINT1 90section .textglobal _start_start:MOV R12, string.msgMOV R13, 2MOV R14, 16MOV R15, 158loop0:MOV RCX, R13MOV RAX, SYS_WRITEMOV RDI, STDOUTMOV RSI, R12ADD R12W, WORD [linestarts+RCX]MOV DX, [linestarts+RCX]SYSCALLMOV RCX, R13CMP RCX, R14JE exit1MOV RAX, SYS_WRITEMOV RDI, STDOUTMOV RSI, newlineMOV RDX, 1SYSCALLMOV RCX, R13ADD RCX, 2MOV R13, RCXJMP loop0exit1:MOV RAX, SYS_WRITEMOV RDI, STDOUTMOV RSI, quoteMOV RDX, 1SYSCALLMOV RAX, SYS_WRITEMOV RDI, STDOUTMOV RSI, string.msgMOV RDX, string.lenSYSCALLMOV RAX, SYS_WRITEMOV RDI, STDOUTMOV RSI, quoteMOV RDX, 1SYSCALLMOV RAX, SYS_WRITEMOV RDI, STDOUTMOV RSI, newlineMOV RDX, 1SYSCALLMOV R13, 0loop1:MOV RCX, R13MOV RAX, SYS_WRITEMOV RDI, STDOUTMOV RSI, R12ADD R12W, WORD [linestarts2+RCX]MOV DX, [linestarts2+RCX]SYSCALLMOV RCX, R13CMP RCX, R15JE exit2MOV RAX, SYS_WRITEMOV RDI, STDOUTMOV RSI, newlineMOV RDX, 1SYSCALLMOV RCX, R13ADD RCX, 2MOV R13, RCXJMP loop1exit2:MOV RAX, 60MOV RDI, 0SYSCALL" -.len equ $- .msg -quote db 0x22 -newline db 0xA -linestarts dw 0, 10, 18, 19, 16, 19, 13, 7, 8 -linestarts2 dw 16, 13, 14, 45, 312, 17, 13, 13, 7, 19, 10, 11, 12, 6, 12, 18, 15, 12, 31, 24, 7, 12, 12, 8, 18, 15, 16, 10, 7, 12, 10, 12, 9, 6, 18, 15, 14, 10, 7, 18, 15, 19, 19, 7, 18, 15, 14, 10, 7, 18, 15, 16, 10, 7, 10, 6, 12, 18, 15, 12, 32, 25, 7, 12, 12, 8, 18, 15, 16, 10, 7, 12, 10, 12, 9, 6, 11, 10, 7 -%DEFINE PRINT1 90 -section .text -global _start -_start: -MOV R12, string.msg -MOV R13, 2 -MOV R14, 16 -MOV R15, 158 -loop0: -MOV RCX, R13 -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, R12 -ADD R12W, WORD [linestarts+RCX] -MOV DX, [linestarts+RCX] -SYSCALL -MOV RCX, R13 -CMP RCX, R14 -JE exit1 -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, newline -MOV RDX, 1 -SYSCALL -MOV RCX, R13 -ADD RCX, 2 -MOV R13, RCX -JMP loop0 -exit1: -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, quote -MOV RDX, 1 -SYSCALL -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, string.msg -MOV RDX, string.len -SYSCALL -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, quote -MOV RDX, 1 -SYSCALL -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, newline -MOV RDX, 1 -SYSCALL -MOV R13, 0 -loop1: -MOV RCX, R13 -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, R12 -ADD R12W, WORD [linestarts2+RCX] -MOV DX, [linestarts2+RCX] -SYSCALL -MOV RCX, R13 -CMP RCX, R15 -JE exit2 -MOV RAX, SYS_WRITE -MOV RDI, STDOUT -MOV RSI, newline -MOV RDX, 1 -SYSCALL -MOV RCX, R13 -ADD RCX, 2 -MOV R13, RCX -JMP loop1 -exit2: -MOV RAX, 60 -MOV RDI, 0 -SYSCALL - -``` - -{% endraw %} - -Quine in [x86-64](/languages/x86-64) was written by: - -- Raymond Marx - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/algol60/index.md b/docs/projects/remove-all-whitespace/algol60/index.md deleted file mode 100644 index 000761fd6f..0000000000 --- a/docs/projects/remove-all-whitespace/algol60/index.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-03 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-04-03 -layout: default -tags: -- algol60 -- remove-all-whitespace -title: Remove All Whitespace in ALGOL 60 -title1: Remove All Whitespace -title2: in ALGOL 60 ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please provide a string\n"); - stop - end usage; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - procedure outAsciiChar(ch); - value ch; - integer ch; - begin - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - outchar( - 1, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ) - end outAsciiChar; - - procedure outCharArray(s, len); - value len; - integer array s; - integer len; - begin - integer i; - for i := 1 step 1 until len do outAsciiChar(s[i]) - end outCharArray; - - integer procedure removeAllWhitespace(s, len); - value len; - integer array s; - integer len; - begin - integer i, ch, newLen; - - newLen := 0; - for i := 1 step 1 until len do - begin - comment Store character is not whitespace. Otherwise, skip it; - ch := s[i]; - if ch != 9 & ch != 10 & ch != 13 & ch != 32 then - begin - newLen := newLen + 1; - s[newLen] := ch - end - end; - - removeAllWhitespace := newLen - end removeAllWhitespace; - - integer argc, len, newLen; - integer array s[1:256]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get string as integer array. Exit if empty; - len := inCharArray(s, 256); - if len < 1 then usage; - - comment Remove all whitespace and output string as integer array; - newLen := removeAllWhitespace(s, len); - outCharArray(s, newLen); - if newLen > 0 then outstring(1, "\n") -end - -``` - -{% endraw %} - -Remove All Whitespace in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/algol68/index.md b/docs/projects/remove-all-whitespace/algol68/index.md deleted file mode 100644 index cf77ddaa8e..0000000000 --- a/docs/projects/remove-all-whitespace/algol68/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-24 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2023-01-31 -layout: default -tags: -- algol68 -- remove-all-whitespace -title: Remove All Whitespace in ALGOL 68 -title1: Remove All Whitespace -title2: in ALGOL 68 ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC usage = VOID: printf(($gl$, "Usage: please provide a string")); - -PROC remove all whitespace := (STRING s) STRING: -( - STRING t; - FOR n TO UPB s - DO - IF NOT isspace(s[n]) - THEN - t +:= s[n] - FI - OD; - - t -); - -# Get 1st command-line argument. Exit if empty # -STRING s := argv(4); -IF UPB s = 0 -THEN - usage; - stop -FI; - -# Remove all whitespace and display result # -s := remove all whitespace(s); -printf(($gl$, s)) - -``` - -{% endraw %} - -Remove All Whitespace in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/awk/index.md b/docs/projects/remove-all-whitespace/awk/index.md deleted file mode 100644 index 2b87f6d880..0000000000 --- a/docs/projects/remove-all-whitespace/awk/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-14 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- remove-all-whitespace -title: Remove All Whitespace in AWK -title1: Remove All -title2: Whitespace in AWK ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a string" - exit(1) -} - -function remove_whitespace(s, arr, result) { - split(s, arr, /\s+/) - result = "" - for (k in arr) { - result = result arr[k] - } - - return result -} - -BEGIN { - if (ARGC < 2 || !ARGV[1]) { - usage() - } - - print remove_whitespace(ARGV[1]) -} - -``` - -{% endraw %} - -Remove All Whitespace in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/beef/index.md b/docs/projects/remove-all-whitespace/beef/index.md deleted file mode 100644 index e77c4c71ef..0000000000 --- a/docs/projects/remove-all-whitespace/beef/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-18 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2024-01-18 -layout: default -tags: -- beef -- remove-all-whitespace -title: Remove All Whitespace in Beef -title1: Remove All -title2: Whitespace in Beef ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace RemoveAllWhitespace; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a string"); - Environment.Exit(0); - } - - public static void RemoveAllWhitespace(StringView str, ref String result) - { - result.Clear(); - result.Join("", str.Split(' ', '\t', '\r', '\n')); - } - - public static int Main(String[] args) - { - if (args.Count < 1 || args[0].Length < 1) - { - Usage(); - } - - String result = scope .(); - RemoveAllWhitespace(args[0], ref result); - Console.WriteLine(result); - return 0; - } -} - -``` - -{% endraw %} - -Remove All Whitespace in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/brainfuck/index.md b/docs/projects/remove-all-whitespace/brainfuck/index.md deleted file mode 100644 index 8ba1921950..0000000000 --- a/docs/projects/remove-all-whitespace/brainfuck/index.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-21 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2023-12-21 -layout: default -tags: -- brainfuck -- remove-all-whitespace -title: Remove All Whitespace in Brainfuck -title1: Remove All Whitespace -title2: in Brainfuck ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Brainfuck](/languages/brainfuck) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```brainfuck -[ - Source for error message text: - https://copy.sh/brainfuck/text.html -] -; Mem 0 = 1 (indicate no input) -+ -; Mem 1 = input; Loop while input not null ->,[ - ; Mem 0 = 0 (indicate input) - <[-] - ; Mem 2 = input; Mem 3 = input; Mem 1 = 0 - >>[-] ; Mem 2 = 0 - >[-] ; Mem 3 = 0 - <<[ - >+ ; Inc Mem 2 - >+ ; Mem Mem 3 - <<- ; Dec Mem 1 - ] - ; Sub 9 from Mem 3; If not zero (not tab) - >>---------[ - ; Dec Mem 3; If not zero (not newline) - -[ - ; Sub 3 from Mem 3; If not zero (not carriage return) - ---[ - ; Sub 19 from Mem 3; If not zero (not space) - >+++[ ; Mem 4 = 3 - <------ ; Sub 6 from Mem 3 - >- ; Dec Mem 4 - ] - <- ; Dec Mem 3 - [ - ; Display input (Mem 2) and reset Mem 3 - <. - >[-] - ] - ] - ] - ] - ; Mem 1 = input - <<, -] -; If no input; display error message -<[ - [-] - -[--->+<]>. - +[--->+<]>+. - ++[->+++<]>++. - ++++++. - --. - +++[->+++<]>++. - [-->+<]>+++. - [-->+++++++<]>. - ----. - -------. - ----. - --[--->+<]>--. - ++++[->+++<]>. - --[--->+<]>-. - [-->+++++++<]>. - ++. - ---. - +++++++. - [------>+<]>. - -----. - +. - --[--->+<]>-. - [->+++<]>+. - -[->+++<]>. - ---[->++++<]>-. - +. - --. - ---------. - +++++. - -------. - [-] -] - -``` - -{% endraw %} - -Remove All Whitespace in [Brainfuck](/languages/brainfuck) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/c-plus-plus/index.md b/docs/projects/remove-all-whitespace/c-plus-plus/index.md deleted file mode 100644 index 404907cc90..0000000000 --- a/docs/projects/remove-all-whitespace/c-plus-plus/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- LauraV-702 -- Ștefan-Iulian Alecu -date: 2024-11-07 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- remove-all-whitespace -title: Remove All Whitespace in C++ -title1: Remove All -title2: Whitespace in C++ ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please provide a string\n"; - std::exit(1); -} - -int main(int argc, char* argv[]) { - if (argc < 2) usage(); - - std::string_view input = argv[1]; - if (input.empty()) usage(); - - auto is_not_space = [](unsigned char c) { return !std::isspace(c); }; - auto filtered = input | std::views::filter(is_not_space); - - std::string result; - std::ranges::copy(filtered, std::back_inserter(result)); - - std::cout << result << '\n'; -} -``` - -{% endraw %} - -Remove All Whitespace in [C++](/languages/c-plus-plus) was written by: - -- LauraV-702 -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/c-sharp/index.md b/docs/projects/remove-all-whitespace/c-sharp/index.md deleted file mode 100644 index 52ac2d688d..0000000000 --- a/docs/projects/remove-all-whitespace/c-sharp/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2024-11-11 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- remove-all-whitespace -title: Remove All Whitespace in C# -title1: Remove All -title2: Whitespace in C# ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var input] || string.IsNullOrEmpty(input)) - return ExitWithError(); - -RemoveWhitespace(input.AsSpan()); -return 0; - -static void RemoveWhitespace(ReadOnlySpan input) -{ - char[] buffer = new char[input.Length]; - int j = 0; - - foreach (char c in input) - { - if (!char.IsWhiteSpace(c)) - buffer[j++] = c; - } - - Console.WriteLine(new string(buffer, 0, j)); -} - -static int ExitWithError() -{ - Console.WriteLine("Usage: please provide a string"); - return 1; -} -``` - -{% endraw %} - -Remove All Whitespace in [C#](/languages/c-sharp) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/c/index.md b/docs/projects/remove-all-whitespace/c/index.md deleted file mode 100644 index 950923faa8..0000000000 --- a/docs/projects/remove-all-whitespace/c/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- qopci -- Ștefan-Iulian Alecu -date: 2024-11-06 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- remove-all-whitespace -title: Remove All Whitespace in C -title1: Remove All -title2: Whitespace in C ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include - -int main(int argc, char *argv[]) -{ - // check whether the passed argument is a string or empty - if (argc < 2 || argv[1][0] == '\0') - { - printf("Usage: please provide a string\n"); - return 1; - } - - char *input = argv[1]; - char output[1000]; - int j = 0; - - for (int i = 0; input[i] != '\0'; i++) - { - // check if current character is not a whitespace character - if (!isspace(input[i])) - output[j++] = input[i]; - } - - // null terminator to mark the end of a string - output[j] = '\0'; - - // print the output string with no spaces - printf("%s\n", output); - - return 0; -} - -``` - -{% endraw %} - -Remove All Whitespace in [C](/languages/c) was written by: - -- qopci -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/cobol/index.md b/docs/projects/remove-all-whitespace/cobol/index.md deleted file mode 100644 index 7f372a5d65..0000000000 --- a/docs/projects/remove-all-whitespace/cobol/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- remove-all-whitespace -title: Remove All Whitespace in COBOL -title1: Remove All -title2: Whitespace in COBOL ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. remove-all-whitespace. - -data division. -working-storage section. -01 arg-count pic 9(4) comp. -01 input-len pic 9(4) comp. -01 i pic 9(4) comp. -01 out-ptr pic 9(4) comp value 1. - -01 input-area. - 05 input-string pic x(500). - 05 in-char redefines input-string - pic x occurs 500 times. - -01 output-area. - 05 output-string pic x(500) value spaces. - 05 out-char redefines output-string - pic x occurs 500 times. - -procedure division. -main. - accept arg-count from argument-number - if arg-count = 0 - display "Usage: please provide a string" - stop run - end-if - - accept input-string from argument-value - if input-string = spaces - display "Usage: please provide a string" - stop run - end-if - - inspect input-string replacing - all x"09" by space *> \t - all x"0A" by space *> \n - all x"0D" by space. *> \r - - compute input-len = function stored-char-length(input-string) - - perform varying i from 1 by 1 until i > input-len - if in-char(i) not = space - move in-char(i) to out-char(out-ptr) - add 1 to out-ptr - end-if - end-perform - - if out-ptr > 1 - subtract 1 from out-ptr - display output-string(1:out-ptr) - else - stop run - end-if - - goback. - -``` - -{% endraw %} - -Remove All Whitespace in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/coffeescript/index.md b/docs/projects/remove-all-whitespace/coffeescript/index.md deleted file mode 100644 index ae1b6f1cf1..0000000000 --- a/docs/projects/remove-all-whitespace/coffeescript/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Ryan Mills -date: 2025-10-29 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-10-29 -layout: default -tags: -- coffeescript -- remove-all-whitespace -title: Remove All Whitespace in CoffeeScript -title1: Remove All Whitespace -title2: in CoffeeScript ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript - -removeAllWhitespace = (inputString) -> - return usage() if not inputString - words = inputString.split(/[\s]+/) - finalString = '' - for word in words - finalString += word - return finalString -usage = () -> - "Usage: please provide a string" - -main = () -> - args = process.argv - return removeAllWhitespace(args[2]) - -console.log main() - -``` - -{% endraw %} - -Remove All Whitespace in [CoffeeScript](/languages/coffeescript) was written by: - -- Ryan Mills - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/commodore-basic/index.md b/docs/projects/remove-all-whitespace/commodore-basic/index.md deleted file mode 100644 index 092af72835..0000000000 --- a/docs/projects/remove-all-whitespace/commodore-basic/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-17 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2023-09-17 -layout: default -tags: -- commodore-basic -- remove-all-whitespace -title: Remove All Whitespace in Commodore BASIC -title1: Remove All Whitespace -title2: in Commodore BASIC ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input string -10 GOSUB 1000 -20 R$ = "" -30 IF S$ = "" OR S$ = CHR$(13) THEN GOTO 120 -40 FOR K = 1 TO LEN(S$) -50 A$ = MID$(S$, K, 1) -60 IF A$ = CHR$(9) OR A$ = CHR$(10) OR A$ = CHR$(13) THEN GOTO 90 -70 IF A$ = " " THEN GOTO 90: REM Can't put on above line, too long -80 R$ = R$ + A$ -90 NEXT K -100 PRINT R$ -110 END -120 PRINT "Usage: please provide a string" -130 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 255 THEN RETURN: REM end of input -1050 S$ = S$ + A$ -1060 GOTO 1020 - -``` - -{% endraw %} - -Remove All Whitespace in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/dart/index.md b/docs/projects/remove-all-whitespace/dart/index.md deleted file mode 100644 index 7902e52f63..0000000000 --- a/docs/projects/remove-all-whitespace/dart/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- gangaasoonu -date: 2025-10-05 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-10-05 -layout: default -tags: -- dart -- remove-all-whitespace -title: Remove All Whitespace in Dart -title1: Remove All -title2: Whitespace in Dart ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -// Issue 4973 -void main(List argv){ - const String error_message = "Usage: please provide a string"; - if (argv.isEmpty || argv[0].isEmpty){ - print(error_message); - return; - } - //Do not convert \r, \n and \t explicitly into carriage return, newline and tab, as per Jeremy inputs - // Use Regular Expressin to replace carriage return, newline and tab with empty string - String sentence_no_spaces = argv[0].replaceAll(RegExp(r'[\t\r\n ]'), ''); - print(sentence_no_spaces); -} - -``` - -{% endraw %} - -Remove All Whitespace in [Dart](/languages/dart) was written by: - -- gangaasoonu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/elvish/index.md b/docs/projects/remove-all-whitespace/elvish/index.md deleted file mode 100644 index 16cce8fa42..0000000000 --- a/docs/projects/remove-all-whitespace/elvish/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-15 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-01-15 -layout: default -tags: -- elvish -- remove-all-whitespace -title: Remove All Whitespace in Elvish -title1: Remove All -title2: Whitespace in Elvish ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -use re - -if (> 1 (count $args)) { - echo "Usage: please provide a string" - exit 1 -} - -if (> 1 (count $args[0])) { - echo "Usage: please provide a string" - exit 1 -} - -echo (re:replace '\s' '' $args[0]) - -``` - -{% endraw %} - -Remove All Whitespace in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/euphoria/index.md b/docs/projects/remove-all-whitespace/euphoria/index.md deleted file mode 100644 index f86b112cba..0000000000 --- a/docs/projects/remove-all-whitespace/euphoria/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- remove-all-whitespace -title: Remove All Whitespace in Euphoria -title1: Remove All Whitespace -title2: in Euphoria ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/regex.e as re -include std/sequence.e -include std/text.e - -function remove_all_whitespace(sequence s) - -- Trim off leading and trailing whitespace, then split into words - sequence words = re:split(re:new(`\s+`), trim(s)) - - -- Join words together without spaces - return join(words, "") -end function - -procedure usage() - printf(STDOUT, "Usage: please provide a string") - abort(0) -end procedure - --- Parse 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Remove all whitespace and show result -sequence s = argv[4] -sequence t = remove_all_whitespace(s) -printf(STDOUT, "%s\n", {t}) - -``` - -{% endraw %} - -Remove All Whitespace in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/f-sharp/index.md b/docs/projects/remove-all-whitespace/f-sharp/index.md deleted file mode 100644 index 56c02931a8..0000000000 --- a/docs/projects/remove-all-whitespace/f-sharp/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- JesseChum -- Ștefan-Iulian Alecu -date: 2024-11-14 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-04-05 -layout: default -tags: -- f-sharp -- remove-all-whitespace -title: Remove All Whitespace in F# -title1: Remove All -title2: Whitespace in F# ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -let removeAllWhitespace = String.filter (Char.IsWhiteSpace >> not) - -[] -let main argv = - match argv with - | [| input |] when not (String.IsNullOrEmpty input) -> - input |> removeAllWhitespace |> printfn "%s" - 0 - | _ -> - printfn "Usage: please provide a string" - 1 - -``` - -{% endraw %} - -Remove All Whitespace in [F#](/languages/f-sharp) was written by: - -- JesseChum -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/gnu-make/index.md b/docs/projects/remove-all-whitespace/gnu-make/index.md deleted file mode 100644 index 195f546353..0000000000 --- a/docs/projects/remove-all-whitespace/gnu-make/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-05 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-10-05 -layout: default -tags: -- gnu-make -- remove-all-whitespace -title: Remove All Whitespace in GNU Make -title1: Remove All Whitespace -title2: in GNU Make ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [GNU Make](/languages/gnu-make) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```gnu_make -USAGE := Usage: please provide a string - -# Constants -EMPTY := -SPACE := $(EMPTY) $(EMPTY) - -# Note that this is non-portable, but it's the only way I could get a carriage return -# assigned to a variable -CR := $(shell printf '\r') - -# Remove all whitespace -# -# Note that GNU Make automatically converts tab and newline ('\n') to a space and -# that leading and trailing whitespace are ignore, so all that needs to be done -# is to remove carriage return (`\r') and space. -# -# Arg 1: The string -# Return: The string without whitespace -REMOVE_ALL_WHITESPACE = $(subst $(CR),,$(subst $(SPACE),,$(1))) - -# If string not provided, display usage statement -# Else display string without whitespace -ifeq (,$(ARGV1)) -$(info $(USAGE)) -else -NUMBER := $(call CONVERT_NUMBER,$(strip $(ARGV1))) -$(info $(call REMOVE_ALL_WHITESPACE,$(ARGV1))) -endif - -.PHONY: -all: ;@: - -``` - -{% endraw %} - -Remove All Whitespace in [GNU Make](/languages/gnu-make) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/go/index.md b/docs/projects/remove-all-whitespace/go/index.md deleted file mode 100644 index 0254fcba20..0000000000 --- a/docs/projects/remove-all-whitespace/go/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2024-10-08 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2024-10-08 -layout: default -tags: -- go -- remove-all-whitespace -title: Remove All Whitespace in Go -title1: Remove All -title2: Whitespace in Go ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strings" -) - -func main() { - errorMessage := "Usage: please provide a string" - - if len(os.Args) < 2 || os.Args[1] == "" { - fmt.Println(errorMessage) - os.Exit(1) - } - - inputString := os.Args[1] - outputString := strings.Join(strings.Fields(inputString), "") - fmt.Println(outputString) -} - -``` - -{% endraw %} - -Remove All Whitespace in [Go](/languages/go) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/haskell/index.md b/docs/projects/remove-all-whitespace/haskell/index.md deleted file mode 100644 index 0b9d90d47a..0000000000 --- a/docs/projects/remove-all-whitespace/haskell/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-04-29 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-04-29 -layout: default -tags: -- haskell -- remove-all-whitespace -title: Remove All Whitespace in Haskell -title1: Remove All Whitespace -title2: in Haskell ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Data.Char (isSpace) -import System.Environment - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - -verifyStringNotEmpty :: String -> Maybe String -verifyStringNotEmpty "" = Nothing -verifyStringNotEmpty xs = Just xs - -main :: IO () -main = do - args <- getArgs - let inputStr = headMaybe args >>= verifyStringNotEmpty - case inputStr of - Just str -> putStrLn $ filter (not . isSpace) str - Nothing -> putStrLn "Usage: please provide a string" - -``` - -{% endraw %} - -Remove All Whitespace in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/index.md b/docs/projects/remove-all-whitespace/index.md deleted file mode 100644 index c3cbe5fddb..0000000000 --- a/docs/projects/remove-all-whitespace/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -date: 2022-04-28 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- remove-all-whitespace -title: Remove All Whitespace -title1: Remove All -title2: Whitespace ---- - - - -Welcome to the Remove All Whitespace page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -A string is a collection of characters. Sometimes strings contain whitespace characters like " ", "\t", and "\n". -The purpose of this project is to remove all such spaces from a string. For example, given the string -"Remove All Whitespace", we could generate a new string with all the whitespace removed as follows: -"RemoveAllWhitespace". In this case, two spaces were removed at positions 6 and 10. - -For simplicity, we will be restricting the types of whitespace to these four types of characters: spaces (" "), -tabs ("\t"), newlines ("\n"), and carriage returns ("\r"). We are aware that other types of whitespace exist. -That said, programs in this collection tend to be simple, so we can replicate them in as many programming -languages as possible. - - -## Requirements - -To satisfy the requirements, a program must accept a string on the command line and return a new string -with all spaces removed as follows: - -```shell -$ remove-all-whitespace.lang " Hello, World! " -$ "Hello,World!" -``` - -In this case, we start with a string that has leading, trailing, and inner spaces. Ultimately, we want to -return a string with all of the spaces removed. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Remove All Whitespace. -In order to keep things simple, we split up the testing as follows: - -- Remove All Whitespace Valid Tests -- Remove All Whitespace Invalid Tests - -### Remove All Whitespace Valid Tests - -| Description | Input | -| ----------- | ----- | -| Sample Input: No Spaces | "RemoveAllWhitespace" | -| Sample Input: Leading Spaces | " RemoveAllWhitespace" | -| Sample Input: Trailing Spaces | "RemoveAllWhitespace " | -| Sample Input: Inner Spaces | "Remove All Whitespace" | -| Sample Input: Tabs | "\tRemove\tAll\tWhitespace\t" | -| Sample Input: Newlines | "\nRemove\nAll\nWhitespace\n" | -| Sample Input: Carriage Returns | "\rRemove\rAll\rWhitespace\r" | - -All of these tests should output the following: - -``` -RemoveAllWhitespace -``` - -### Remove All Whitespace Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | - -All of these tests should output the following: - -``` -Usage: please provide a string -``` - - -## Articles - -There are 36 articles: - -- [Remove All Whitespace in ALGOL 60](/projects/remove-all-whitespace/algol60) -- [Remove All Whitespace in ALGOL 68](/projects/remove-all-whitespace/algol68) -- [Remove All Whitespace in AWK](/projects/remove-all-whitespace/awk) -- [Remove All Whitespace in Beef](/projects/remove-all-whitespace/beef) -- [Remove All Whitespace in Brainfuck](/projects/remove-all-whitespace/brainfuck) -- [Remove All Whitespace in C](/projects/remove-all-whitespace/c) -- [Remove All Whitespace in C#](/projects/remove-all-whitespace/c-sharp) -- [Remove All Whitespace in C++](/projects/remove-all-whitespace/c-plus-plus) -- [Remove All Whitespace in COBOL](/projects/remove-all-whitespace/cobol) -- [Remove All Whitespace in CoffeeScript](/projects/remove-all-whitespace/coffeescript) -- [Remove All Whitespace in Commodore BASIC](/projects/remove-all-whitespace/commodore-basic) -- [Remove All Whitespace in Dart](/projects/remove-all-whitespace/dart) -- [Remove All Whitespace in Elvish](/projects/remove-all-whitespace/elvish) -- [Remove All Whitespace in Euphoria](/projects/remove-all-whitespace/euphoria) -- [Remove All Whitespace in F#](/projects/remove-all-whitespace/f-sharp) -- [Remove All Whitespace in GNU Make](/projects/remove-all-whitespace/gnu-make) -- [Remove All Whitespace in Go](/projects/remove-all-whitespace/go) -- [Remove All Whitespace in Haskell](/projects/remove-all-whitespace/haskell) -- [Remove All Whitespace in Java](/projects/remove-all-whitespace/java) -- [Remove All Whitespace in JavaScript](/projects/remove-all-whitespace/javascript) -- [Remove All Whitespace in Julia](/projects/remove-all-whitespace/julia) -- [Remove All Whitespace in Kotlin](/projects/remove-all-whitespace/kotlin) -- [Remove All Whitespace in Mathematica](/projects/remove-all-whitespace/mathematica) -- [Remove All Whitespace in PHP](/projects/remove-all-whitespace/php) -- [Remove All Whitespace in Pascal](/projects/remove-all-whitespace/pascal) -- [Remove All Whitespace in PowerShell](/projects/remove-all-whitespace/powershell) -- [Remove All Whitespace in Python](/projects/remove-all-whitespace/python) -- [Remove All Whitespace in R](/projects/remove-all-whitespace/r) -- [Remove All Whitespace in Ruby](/projects/remove-all-whitespace/ruby) -- [Remove All Whitespace in Rust](/projects/remove-all-whitespace/rust) -- [Remove All Whitespace in Swift](/projects/remove-all-whitespace/swift) -- [Remove All Whitespace in Tcl](/projects/remove-all-whitespace/tcl) -- [Remove All Whitespace in TypeScript](/projects/remove-all-whitespace/typescript) -- [Remove All Whitespace in Visual Basic](/projects/remove-all-whitespace/visual-basic) -- [Remove All Whitespace in Wren](/projects/remove-all-whitespace/wren) -- [Remove All Whitespace in m4](/projects/remove-all-whitespace/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/java/index.md b/docs/projects/remove-all-whitespace/java/index.md deleted file mode 100644 index e0ac33b6cc..0000000000 --- a/docs/projects/remove-all-whitespace/java/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- java -- remove-all-whitespace -title: Remove All Whitespace in Java -title1: Remove All -title2: Whitespace in Java ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class RemoveAllWhitespace { - public static void main(String[] args) { - if (args.length == 0 || args[0].isEmpty()) { - showUsage(); - } - - System.out.println(removeAllWhitespace(args[0])); - } - - private static void showUsage() { - System.out.println("Usage: please provide a string"); - System.exit(1); - } - - private static boolean isWhitespace(char c) { - return switch (c) { - case ' ', '\t', '\n', '\r' -> true; - default -> false; - }; - } - - private static String removeAllWhitespace(String input) { - var result = new StringBuilder(input.length()); - - for (char c : input.toCharArray()) { - if (!isWhitespace(c)) { - result.append(c); - } - } - - return result.toString(); - } -} -``` - -{% endraw %} - -Remove All Whitespace in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/javascript/index.md b/docs/projects/remove-all-whitespace/javascript/index.md deleted file mode 100644 index 5903a9d7d4..0000000000 --- a/docs/projects/remove-all-whitespace/javascript/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-12 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-01-12 -layout: default -tags: -- javascript -- remove-all-whitespace -title: Remove All Whitespace in JavaScript -title1: Remove All Whitespace -title2: in JavaScript ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const die = () => { - console.log("Usage: please provide a string"); - process.exit(1); -} - -if (process.argv.length != 3) { - die(); -} - -process.argv[2].length > 0 - ? console.log(process.argv[2].replace(/\s/g, '')) - : die(); - -``` - -{% endraw %} - -Remove All Whitespace in [JavaScript](/languages/javascript) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/julia/index.md b/docs/projects/remove-all-whitespace/julia/index.md deleted file mode 100644 index 4041b4d39f..0000000000 --- a/docs/projects/remove-all-whitespace/julia/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- smjalageri -date: 2022-10-05 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2022-10-05 -layout: default -tags: -- julia -- remove-all-whitespace -title: Remove All Whitespace in Julia -title1: Remove All -title2: Whitespace in Julia ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -using Core: print -function err() - println("Usage: please provide a string") -end - -function remove_all_whitespaces(n) - if (length(n) in [0,1]) - err() - else - n_nospace = (filter(x -> !isspace(x), n)) - n_notab = replace(n_nospace, "\t" => "") - n_nonewline = replace(n_notab, "\n" => "") - n_nonewline = replace(n_notab, "\r" => "") - println(n_nonewline) - end -end - -try - # remove_all_whitespaces(parse(ARGS[1])) - remove_all_whitespaces(ARGS[1]) -catch e - err() -end - -``` - -{% endraw %} - -Remove All Whitespace in [Julia](/languages/julia) was written by: - -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/kotlin/index.md b/docs/projects/remove-all-whitespace/kotlin/index.md deleted file mode 100644 index 68fcb0d826..0000000000 --- a/docs/projects/remove-all-whitespace/kotlin/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2025-10-06 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-10-06 -layout: default -tags: -- kotlin -- remove-all-whitespace -title: Remove All Whitespace in Kotlin -title1: Remove All -title2: Whitespace in Kotlin ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -import kotlin.system.exitProcess - -fun main(args: Array) { - val phrase: String = errorChecking(args) - println(removeWhitespace(phrase)) -} - -fun usageError() { - println("Usage: please provide a string") -} - -fun errorChecking(args: Array): String { - if (args.size == 0 || args[0] == "") { - usageError() - exitProcess(1) - } - return args[0] -} - -fun removeWhitespace(phrase: String): String { - return phrase.filter { !it.isWhitespace() } -} - -``` - -{% endraw %} - -Remove All Whitespace in [Kotlin](/languages/kotlin) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/m4/index.md b/docs/projects/remove-all-whitespace/m4/index.md deleted file mode 100644 index ab0fd64ad9..0000000000 --- a/docs/projects/remove-all-whitespace/m4/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-13 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-08-13 -layout: default -tags: -- m4 -- remove-all-whitespace -title: Remove All Whitespace in m4 -title1: Remove All -title2: Whitespace in m4 ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a string -m4exit(`1')') - -define(`remove_all_whitespace', `patsubst(`$1', `\s')') -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1), 1, `show_usage()', `remove_all_whitespace(ARGV1)') - -``` - -{% endraw %} - -Remove All Whitespace in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/mathematica/index.md b/docs/projects/remove-all-whitespace/mathematica/index.md deleted file mode 100644 index c26b35bdac..0000000000 --- a/docs/projects/remove-all-whitespace/mathematica/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-16 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2023-01-16 -layout: default -tags: -- mathematica -- remove-all-whitespace -title: Remove All Whitespace in Mathematica -title1: Remove All Whitespace -title2: in Mathematica ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual function operating on Mathematica strings is trivial: *) - -removeAllWhitespace = StringDelete[WhitespaceCharacter]; - -(* The outer function provides the 'user interface': *) - -removeAllWhitespaceMain = s \[Function] - Catch[ - removeAllWhitespace[ - If[ - StringQ[s] \[And] \[Not] StringMatchQ[s, ""], - s, - Throw["Usage: please provide a string"]]]]; - - -(* Valid Tests *) - -Print /@ removeAllWhitespaceMain /@ { - "RemoveAllWhitespace", - " RemoveAllWhitespace", - "RemoveAllWhitespace ", - "Remove All Whitespace", - "\tRemove\tAll\tWhitespace\t", - "\nRemove\nAll\nWhitespace\n", - "\rRemove\rAll\rWhitespace\r" - }; - - -(* Invalid Tests *) - -removeAllWhitespaceMain[""] - -``` - -{% endraw %} - -Remove All Whitespace in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/pascal/index.md b/docs/projects/remove-all-whitespace/pascal/index.md deleted file mode 100644 index 3c6cbf1def..0000000000 --- a/docs/projects/remove-all-whitespace/pascal/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-21 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-07-21 -layout: default -tags: -- pascal -- remove-all-whitespace -title: Remove All Whitespace in Pascal -title1: Remove All -title2: Whitespace in Pascal ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program RemoveAllWhitespace; - -{$mode objfpc}{$H+} - -uses - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a string'); - Halt(1); -end; - -function RemoveWhitespace(const S: string): string; -var - builder: TStringBuilder; - ch: char; -begin - builder := TStringBuilder.Create; - try - for ch in S do - case ch of - ' ', #9, #10, #13: Continue; - else - builder.Append(ch); - end; - - Result := builder.ToString; - finally - builder.Free; - end; -end; - -var - Input: string; - Output: string; -begin - if ParamCount <> 1 then - ShowUsage; - - Input := ParamStr(1); - if Input = '' then - ShowUsage; - - Output := RemoveWhitespace(Input); - Writeln(Output); -end. - -``` - -{% endraw %} - -Remove All Whitespace in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/php/index.md b/docs/projects/remove-all-whitespace/php/index.md deleted file mode 100644 index ff49d89a5f..0000000000 --- a/docs/projects/remove-all-whitespace/php/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-23 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-08-02 -layout: default -tags: -- php -- remove-all-whitespace -title: Remove All Whitespace in PHP -title1: Remove All -title2: Whitespace in PHP ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide a string" - Exit 1 -} - -function Invoke-RemoveAllWhitespace([string]$Str) { - $Str -replace "\s", "" -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -Write-Output (Invoke-RemoveAllWhitespace $args[0]) - -``` - -{% endraw %} - -Remove All Whitespace in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/python/index.md b/docs/projects/remove-all-whitespace/python/index.md deleted file mode 100644 index 426a80a9eb..0000000000 --- a/docs/projects/remove-all-whitespace/python/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2022-05-12 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2022-05-12 -layout: default -tags: -- python -- remove-all-whitespace -title: Remove All Whitespace in Python -title1: Remove All -title2: Whitespace in Python ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - -error = "Usage: please provide a string" - -if len(sys.argv) == 1 or sys.argv[1] == "": - print(error) - sys.exit(1) - -input_string = sys.argv[1] -print("".join(input_string.split())) - -``` - -{% endraw %} - -Remove All Whitespace in [Python](/languages/python) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/r/index.md b/docs/projects/remove-all-whitespace/r/index.md deleted file mode 100644 index ce97910b8e..0000000000 --- a/docs/projects/remove-all-whitespace/r/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-06 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-05-06 -layout: default -tags: -- r -- remove-all-whitespace -title: Remove All Whitespace in R -title1: Remove All -title2: Whitespace in R ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -args <- commandArgs(trailingOnly = TRUE) - -if (length(args) != 1 || !nzchar(args[[1]])) { - cat("Usage: please provide a string\n") - quit(status = 1) -} - -cat(gsub("\\s+", "", args[[1]]), "\n") -``` - -{% endraw %} - -Remove All Whitespace in [R](/languages/r) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/ruby/index.md b/docs/projects/remove-all-whitespace/ruby/index.md deleted file mode 100644 index d730c20ae4..0000000000 --- a/docs/projects/remove-all-whitespace/ruby/index.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- remove-all-whitespace -- ruby -title: Remove All Whitespace in Ruby -title1: Remove All -title2: Whitespace in Ruby ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -input = ARGV.first.to_s - -abort("Usage: please provide a string") if input.empty? - -puts input.delete(" \t\r\n") - -``` - -{% endraw %} - -Remove All Whitespace in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/rust/index.md b/docs/projects/remove-all-whitespace/rust/index.md deleted file mode 100644 index e31070cba0..0000000000 --- a/docs/projects/remove-all-whitespace/rust/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-09 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- remove-all-whitespace -- rust -title: Remove All Whitespace in Rust -title1: Remove All -title2: Whitespace in Rust ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; - -fn usage() -> ! { - println!("Usage: please provide a string"); - exit(0); -} -fn remove_all_whitespaces(s: String) -> String { - s.chars().filter(|c| !c.is_whitespace()).collect() -} - -fn main() { - let mut args = args().skip(1); - - // Get first command-line argument - let s: String = args - .next() - .unwrap_or_else(|| usage()); - - // Make sure not empty - if s.len() < 1 { - usage(); - } - - // Remove all whitespace and show results - let t: String = remove_all_whitespaces(s); - println!("{t}"); -} - -``` - -{% endraw %} - -Remove All Whitespace in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/swift/index.md b/docs/projects/remove-all-whitespace/swift/index.md deleted file mode 100644 index ab47895b2f..0000000000 --- a/docs/projects/remove-all-whitespace/swift/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- remove-all-whitespace -- swift -title: Remove All Whitespace in Swift -title1: Remove All -title2: Whitespace in Swift ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = "Usage: please provide a string" - -guard - let input = CommandLine.arguments.dropFirst().first, - !input.isEmpty -else { - print(usage) - exit(1) -} - -print(input.filter { !$0.isWhitespace }) - -``` - -{% endraw %} - -Remove All Whitespace in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/tcl/index.md b/docs/projects/remove-all-whitespace/tcl/index.md deleted file mode 100644 index bfb6ae86ed..0000000000 --- a/docs/projects/remove-all-whitespace/tcl/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- remove-all-whitespace -- tcl -title: Remove All Whitespace in Tcl -title1: Remove All -title2: Whitespace in Tcl ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 - -proc usage {} { - puts stderr {Usage: please provide a string} - exit 1 -} - -proc removeWhitespace {str} { - regsub -all {\s} $str {} result - return $result -} - -if {$argc != 1} { usage } -set input [lindex $argv 0] -if {$input eq ""} { usage } - -puts [removeWhitespace $input] - -``` - -{% endraw %} - -Remove All Whitespace in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/typescript/index.md b/docs/projects/remove-all-whitespace/typescript/index.md deleted file mode 100644 index 69d2570c06..0000000000 --- a/docs/projects/remove-all-whitespace/typescript/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- remove-all-whitespace -- typescript -title: Remove All Whitespace in TypeScript -title1: Remove All Whitespace -title2: in TypeScript ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function printUsage(): void { - console.log("Usage: please provide a string"); - process.exit(1); -} - -function main(): void { - const input = process.argv[2]; - - if (process.argv.length !== 3 || !input || input.length === 0) { - printUsage(); - } - - const result = input.replace(/\s/g, ""); - console.log(result); -} - -main(); - -``` - -{% endraw %} - -Remove All Whitespace in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/visual-basic/index.md b/docs/projects/remove-all-whitespace/visual-basic/index.md deleted file mode 100644 index 1143fc47d5..0000000000 --- a/docs/projects/remove-all-whitespace/visual-basic/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- remove-all-whitespace -- visual-basic -title: Remove All Whitespace in Visual Basic -title1: Remove All Whitespace -title2: in Visual Basic ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module RemoveAllWhitespace - - Private Sub ShowUsage() - Console.WriteLine("Usage: please provide a string") - Environment.Exit(1) - End Sub - - - Private Sub RemoveAllWhitespace(input As String) - - Dim result As New System.Text.StringBuilder() - - For Each ch As Char In input - - If Not Char.IsWhiteSpace(ch) Then - result.Append(ch) - End If - - Next - - Console.WriteLine(result.ToString()) - - End Sub - - - Public Function Main(args As String()) As Integer - - If args Is Nothing OrElse args.Length = 0 OrElse String.IsNullOrEmpty(args(0)) Then - ShowUsage() - End If - - RemoveAllWhitespace(args(0)) - - Return 0 - - End Function - -End Module -``` - -{% endraw %} - -Remove All Whitespace in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/remove-all-whitespace/wren/index.md b/docs/projects/remove-all-whitespace/wren/index.md deleted file mode 100644 index 745d58bb25..0000000000 --- a/docs/projects/remove-all-whitespace/wren/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-25 -featured-image: remove-all-whitespace-in-every-language.jpg -last-modified: 2025-01-25 -layout: default -tags: -- remove-all-whitespace -- wren -title: Remove All Whitespace in Wren -title1: Remove All -title2: Whitespace in Wren ---- - - - -Welcome to the [Remove All Whitespace](/projects/remove-all-whitespace) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -import "os" for Process - -var args = Process.arguments - -if (args.count < 1 || args[0].count < 1) { - System.print("Usage: please provide a string") - Fiber.suspend() -} - -var s = "" - -for (c in args[0]) { - if (c != " " && c != "\n" && c != "\t" && c != "\r" && c != "\f") { - s = s + c - } -} - -System.print(s) - -``` - -{% endraw %} - -Remove All Whitespace in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/algol60/index.md b/docs/projects/reverse-string/algol60/index.md deleted file mode 100644 index a7dfac8dac..0000000000 --- a/docs/projects/reverse-string/algol60/index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-01 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-04-03 -layout: default -tags: -- algol60 -- reverse-string -title: Reverse String in ALGOL 60 -title1: Reverse String -title2: in ALGOL 60 ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - procedure outAsciiChar(ch); - value ch; - integer ch; - begin - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - outchar( - 1, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ) - end outAsciiChar; - - procedure outCharArray(s, len); - value len; - integer array s; - integer len; - begin - integer i; - for i := 1 step 1 until len do outAsciiChar(s[i]) - end outCharArray; - - procedure reverseString(s, len); - value len; - integer array s; - integer len; - begin - integer left, right, temp; - - left := 1; - right := len; - revloop: - if left < right then - begin - temp := s[left]; - s[left] := s[right]; - s[right] := temp; - left := left + 1; - right := right - 1; - goto revloop - end - end reverseString; - - integer argc, len; - integer array s[1:256]; - - comment Get number of parameters; - ininteger(0, argc); - - comment If any parameters,; - if argc > 0 then - begin - comment Get string as integer array; - len := inCharArray(s, 256); - - comment Reverse string and output string as integer array; - reverseString(s, len); - outCharArray(s, len); - if len > 0 then outstring(1, "\n") - end -end - -``` - -{% endraw %} - -Reverse String in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/algol68/index.md b/docs/projects/reverse-string/algol68/index.md deleted file mode 100644 index 9725b59217..0000000000 --- a/docs/projects/reverse-string/algol68/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-24 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- algol68 -- reverse-string -title: Reverse String in ALGOL 68 -title1: Reverse String -title2: in ALGOL 68 ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC reverse string = (STRING s) STRING: -( - STRING t; - FOR n FROM UPB s DOWNTO 1 - DO - t +:= s[n] - OD; - - t -); - -# Get 1st command-line argument # -STRING s := argv(4); - -# Reverse string and show result # -s := reverse string(s); -printf(($gl$, s)) - -``` - -{% endraw %} - -Reverse String in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/awk/index.md b/docs/projects/reverse-string/awk/index.md deleted file mode 100644 index 4313bd5d92..0000000000 --- a/docs/projects/reverse-string/awk/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-07 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- reverse-string -title: Reverse String in AWK -title1: Reverse -title2: String in AWK ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function reverse_string(s, result, i) { - result = "" - for (i = length(s); i > 0; i--) { - result = result substr(s, i, 1) - } - - return result -} - -BEGIN { - if (ARGC > 1) { - print reverse_string(ARGV[1]) - } -} - -``` - -{% endraw %} - -Reverse String in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/bash/index.md b/docs/projects/reverse-string/bash/index.md deleted file mode 100644 index e30f3de76b..0000000000 --- a/docs/projects/reverse-string/bash/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Abdus -- Parker Johansen -date: 2018-05-09 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2019-03-21 -layout: default -tags: -- bash -- reverse-string -title: Reverse String in Bash -title1: Reverse String -title2: in Bash ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash - -string=$1 -strLength=${#string} - -for ((i=$strLength-1;i>-1;i--)); -do - reverseStr+=${string:i:1} -done -echo $reverseStr -``` - -{% endraw %} - -Reverse String in [Bash](/languages/bash) was written by: - -- Abdus -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/beef/index.md b/docs/projects/reverse-string/beef/index.md deleted file mode 100644 index c2ac0b8355..0000000000 --- a/docs/projects/reverse-string/beef/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-14 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2024-01-14 -layout: default -tags: -- beef -- reverse-string -title: Reverse String in Beef -title1: Reverse String -title2: in Beef ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace ReverseString; - -class Program -{ - public static void ReverseString(StringView str, ref String reversed) - { - reversed.Clear(); - reversed.Reserve(str.Length); - for (char8 ch in str.Reversed) - { - reversed += ch; - } - } - - public static int Main(String[] args) - { - if (args.Count > 0) - { - String reversed = scope String(); - ReverseString(args[0], ref reversed); - Console.WriteLine(reversed); - } - - return 0; - } -} - - -``` - -{% endraw %} - -Reverse String in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/brainfuck/index.md b/docs/projects/reverse-string/brainfuck/index.md deleted file mode 100644 index f1f06b91f1..0000000000 --- a/docs/projects/reverse-string/brainfuck/index.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -date: 2018-08-23 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2018-08-23 -layout: default -tags: -- brainfuck -- reverse-string -title: Reverse String in Brainfuck -title1: Reverse String -title2: in Brainfuck ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Brainfuck](/languages/brainfuck) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```brainfuck ->,[>,]<[.<] - -``` - -{% endraw %} - -Reverse String in [Brainfuck](/languages/brainfuck) was written by: - -- Christoph Böhmwalder - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/c-plus-plus/index.md b/docs/projects/reverse-string/c-plus-plus/index.md deleted file mode 100644 index 0d55096638..0000000000 --- a/docs/projects/reverse-string/c-plus-plus/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Noah -- Ștefan-Iulian Alecu -date: 2018-09-14 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- reverse-string -title: Reverse String in C++ -title1: Reverse -title2: String in C++ ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -int main(int argc, char* argv[]) { - if (argc < 2 || std::string_view(argv[1]).empty()) { - return 0; - } - - std::string s = argv[1]; - std::ranges::reverse(s); - - std::cout << s << '\n'; -} -``` - -{% endraw %} - -Reverse String in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Noah -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/c-sharp/index.md b/docs/projects/reverse-string/c-sharp/index.md deleted file mode 100644 index 3ee5543b69..0000000000 --- a/docs/projects/reverse-string/c-sharp/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Ștefan-Iulian Alecu -date: 2018-04-25 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- reverse-string -title: Reverse String in C# -title1: Reverse -title2: String in C# ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is [var input] && !string.IsNullOrEmpty(input)) - Console.WriteLine(Reverse(input.AsSpan())); - -static string Reverse(ReadOnlySpan s) -{ - int n = s.Length; - char[] result = new char[n]; - - for (int i = 0; i < n; i++) - result[i] = s[n - 1 - i]; - - return new string(result); -} -``` - -{% endraw %} - -Reverse String in [C#](/languages/c-sharp) was written by: - -- Jeremy Grifski -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/c/index.md b/docs/projects/reverse-string/c/index.md deleted file mode 100644 index 1068797a8a..0000000000 --- a/docs/projects/reverse-string/c/index.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -authors: -- Abhishek Dinkar Raut -- Christoph Böhmwalder -- Jeremy Grifski -- rzuckerm -- Ștefan-Iulian Alecu -date: 2018-07-24 -featured-image: reverse-string-in-c.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- reverse-string -title: Reverse String in C -title1: Reverse -title2: String in C ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include - -int main(int argc, char **argv) -{ - char *text = ""; - size_t textlen; - - /* get text from command line and calculate length */ - if (argc >= 2) - text = argv[1]; - - textlen = strlen(text); - - /* print characters in reverse */ - while (textlen-- > 0) - putchar(text[textlen]); - - /* put a newline at the end */ - putchar('\n'); - - return 0; -} - -``` - -{% endraw %} - -Reverse String in [C](/languages/c) was written by: - -- Christoph Böhmwalder -- rzuckerm -- Ștefan-Iulian Alecu - -This article was written by: - -- Abhishek Dinkar Raut -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Apr 15 2026 00:50:56. The solution was first committed on Jul 24 2018 12:26:56. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -### Approach - -We get the length of the input string and iteration from the last character to the first, displaying each character. - -[Time complexity][1]: O(n) - -
- -### Breakdown - -Now let us see step-by-step how the code works. - -```c -#include -#include -``` - -Here we are including header files (`.h` files) to use functions like `printf()`. Header files provided us with tested ready to use functions to ease the software development work. - -By including `#include ` we can use `printf()` method without worrying about how it is implemented. - -```c -int main(int argc, char **argv) -{ - char *text = ""; - size_t textlen; - - /* get text from command line and calculate length */ - if (argc >= 2) { - text = argv[1]; - } - - textlen = strlen(text); -``` - -This get the first command-line argument if it is present. Otherwise, an empty string it assumed. The variable `text` contains -a pointer to the string to be reversed. Then, the length of the string is calculated using **strlen()** and stored in `textlen`. - -Now we get to actual code that displays the string in reverse: - -```c -/* print characters in reverse */ -while (textlen-- > 0) { - putchar(text[textlen]); -} -``` - -This goes through the string in reverse order and displays each character. - -Then, a newline is displayed: - -```c -/* put a newline at the end */ -putchar('\n'); -``` - -Finally the code exits: - -```c -return 0; -``` - -[1]: https://en.wikipedia.org/wiki/Time_complexity - - -## How to Run the Solution - -The easiest way to run this program is to go to this [LeetCode Playground][2] and run the program. You can tweak the program or provide different input strings to understand how it works. - -Alternatively, you can copy the [code from GitHub][3] code and run the program on an [online C compiler][4] or in an IDE. - -[2]: https://leetcode.com/ -[3]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/c/c/reverse-string.c -[4]: https://www.onlinegdb.com/online_c_compiler diff --git a/docs/projects/reverse-string/clojure/index.md b/docs/projects/reverse-string/clojure/index.md deleted file mode 100644 index 6b006f849d..0000000000 --- a/docs/projects/reverse-string/clojure/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- pablocostass -- rzuckerm -date: 2019-10-11 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- clojure -- reverse-string -title: Reverse String in Clojure -title1: Reverse String -title2: in Clojure ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Clojure](/languages/clojure) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```clojure -(ns reverse-string - (:gen-class)) - -(defn main [args] - (if (not= (count args) 0) - (println(clojure.string/reverse (first args))) - )) - -(main *command-line-args*) - -``` - -{% endraw %} - -Reverse String in [Clojure](/languages/clojure) was written by: - -- pablocostass -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/cobol/index.md b/docs/projects/reverse-string/cobol/index.md deleted file mode 100644 index b7db9796ee..0000000000 --- a/docs/projects/reverse-string/cobol/index.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- reverse-string -title: Reverse String in COBOL -title1: Reverse String -title2: in COBOL ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. reverse-string. - -data division. -working-storage section. -01 arg-count pic 9(4) comp. -01 input-string pic x(500). - -procedure division. -main. - accept arg-count from argument-number - if arg-count = 0 - stop run - end-if - - accept input-string from argument-value - - if input-string = spaces - stop run - end-if - - display function reverse(input-string) - - goback. - -``` - -{% endraw %} - -Reverse String in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/coffeescript/index.md b/docs/projects/reverse-string/coffeescript/index.md deleted file mode 100644 index 97a2ca83bd..0000000000 --- a/docs/projects/reverse-string/coffeescript/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Brendan Villaraza -date: 2025-11-02 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-11-02 -layout: default -tags: -- coffeescript -- reverse-string -title: Reverse String in CoffeeScript -title1: Reverse String -title2: in CoffeeScript ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [CoffeeScript](/languages/coffeescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```coffeescript -reverseString = (arg) -> - reversed = "" - if not arg - return "" - for char, i in arg - reversed += arg[arg.length - 1 - i] - return reversed - -main = () -> - args = process.argv[2] - return reverseString(args) - -console.log(main()) -``` - -{% endraw %} - -Reverse String in [CoffeeScript](/languages/coffeescript) was written by: - -- Brendan Villaraza - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/commodore-basic/index.md b/docs/projects/reverse-string/commodore-basic/index.md deleted file mode 100644 index 17cb95a911..0000000000 --- a/docs/projects/reverse-string/commodore-basic/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- reverse-string -title: Reverse String in Commodore BASIC -title1: Reverse String in -title2: Commodore BASIC ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input string -10 GOSUB 1000 -20 R$ = "" -30 IF S$ = "" THEN GOTO 70 -40 FOR K = LEN(S$) TO 1 STEP -1 -50 R$ = R$ + MID$(S$, K, 1) -60 NEXT K -70 PRINT R$ -80 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of value or input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 13 OR C = 255 THEN RETURN: REM end of value or input -1050 S$ = S$ + A$ -1060 GOTO 1020 - -``` - -{% endraw %} - -Reverse String in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/dart/index.md b/docs/projects/reverse-string/dart/index.md deleted file mode 100644 index c935f645d5..0000000000 --- a/docs/projects/reverse-string/dart/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Bassem Mohamed -- Jeremy Grifski -- Paddy -- Patrick -- rzuckerm -date: 2018-10-01 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- dart -- reverse-string -title: Reverse String in Dart -title1: Reverse String -title2: in Dart ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -// Run using : dart reverse-string.dart hello-world -void main(List args) { - if ( args.length > 0 ) { - print( reverse(args[0]) ); - } -} -String reverse(input) { - return input.split('').reversed.join(); -} -``` - -{% endraw %} - -Reverse String in [Dart](/languages/dart) was written by: - -- Bassem Mohamed -- rzuckerm - -This article was written by: - -- Jeremy Grifski -- Paddy -- Patrick -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Much like C or Java, Dart uses the function name `main` as an entry point for the program. In this case, we don't need `main` to return any data so the type `void` is used. Within the `main` function's parameters, you'll see `List args` which will define `args` as a list of strings and fill this list with input from the command line in the form of arguments. - -For example: - -``` -dart reverse-string.dart "Hello World" -``` - -would fill the args list as `["Hello World"]`. - -``` -dart reverse-string.dart "Hello" "World" -``` - -would fill the args list as `["Hello", "World"]`. - -It should be noted that in this example program only the first argument passed to the program will be processed because we're only passing the first string in the list to our reverse function's input by adding the index position `[0]` to `args` in the `print( reverse(args[0]) );` line. So, in the second example above, only `Hello` would get reversed. - -So let's look at that `reverse` function. We've defined the function with type `String` as it'll return our reversed string to be printed to the console. It takes the parameter `input` as an undefined variable but we're assuming here that it will be a string value. - -The `Dart:core` library `String` class contains the `split` method which will split a string or list of strings into a list of substrings based on the pattern given to it. If the pattern is empty as in our reverse function, split will break up the input into single-code unit strings (individual characters). So `"Hello"` with the empty pattern `''` returns `["H", "e", "l", "l", "o"]. - -After we've broken the string into characters with split, we'll use the `reversed` property from the `Dart:core` library's List class. This property simply takes a list and returns it in reversed order as an Iterable object. So our example list, `["H", "e", "l", "l", "o"]`, becomes `["o", "l", "l", "e", "H"]`. - -For the purposes of this sample program, there is very little difference between List and Iterable objects. Both are in fact iterable. At a high level, lists will have additional functionality such as indexed read/write access to its elements and sorting functions. Iterables on the other hand are typically created once then accessed as readonly data during an iteration operation like a for-loop. - -Both Iterables and Lists have the `join` method which will take their elements and concatenate them into a string. We use `join` here on the reversed Iterable which is returned as the final string value of our `reverse` function. This value is then printed out to the console from `print` function within `main`. - - -## How to Run the Solution - -To run the Dart string reversal program, download the [dart file from GitHub](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/d/dart/reverse-string.dart), install the Dart SDK as described at [dart.dev](https://dart.dev/get-dart), and run the following from the command line: - -```console -dart reverse-string.dart "Hello, World!" -``` - -Alternatively, you can copy the source code into [DartPad](https://dartpad.dartlang.org/), an online Dart interpreter. Just keep in mind that you won't have access to the command line arguments input using this method so you'll have to populate the args variable in the code instead. For example: - -```dart -void main(List args) { - args = ['Hello World']; - print( reverse(args[0]) ); -} -String reverse(input) { - return input.split('').reversed.join(); -} -``` diff --git a/docs/projects/reverse-string/dg/index.md b/docs/projects/reverse-string/dg/index.md deleted file mode 100644 index dd430a0d0d..0000000000 --- a/docs/projects/reverse-string/dg/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- Riley Martine -date: 2018-10-03 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2018-10-03 -layout: default -tags: -- dg -- reverse-string -title: Reverse String in Dg -title1: Reverse -title2: String in Dg ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Dg](/languages/dg) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dg -import "/sys/argv" - -snd_if_exists = xs -> if - (len xs) > 1 => snd xs - otherwise => "" - -reverse = s -> if - len s => last s + (init s |> reverse) - otherwise => "" - -print $ reverse <| snd_if_exists argv - -``` - -{% endraw %} - -Reverse String in [Dg](/languages/dg) was written by: - -- Riley Martine - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/elvish/index.md b/docs/projects/reverse-string/elvish/index.md deleted file mode 100644 index 7f34b3b39d..0000000000 --- a/docs/projects/reverse-string/elvish/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-15 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-01-15 -layout: default -tags: -- elvish -- reverse-string -title: Reverse String in Elvish -title1: Reverse String -title2: in Elvish ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -if (> 1 (count $args)) { - echo '' - exit -} - -echo $args[0] | rev - -``` - -{% endraw %} - -Reverse String in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/erlang/index.md b/docs/projects/reverse-string/erlang/index.md deleted file mode 100644 index 7a9e306a65..0000000000 --- a/docs/projects/reverse-string/erlang/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Mark Magahis -- rzuckerm -date: 2019-10-06 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-11-21 -layout: default -tags: -- erlang -- reverse-string -title: Reverse String in Erlang -title1: Reverse String -title2: in Erlang ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Erlang](/languages/erlang) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```erlang --module(reverse_string). --export([main/1]). - -%%-------------------------------------------------------------------- -%% Reverse a given string -%%-------------------------------------------------------------------- -reverse_string(String) -> - lists:reverse(String). - -main(Args) -> - if - length(Args) >= 1 -> - Str = lists:nth(1, Args); - true -> - Str = "" - end, - - ReverseStr = reverse_string(Str), - io:format("~s~n", [ReverseStr]). - -``` - -{% endraw %} - -Reverse String in [Erlang](/languages/erlang) was written by: - -- Mark Magahis -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/euphoria/index.md b/docs/projects/reverse-string/euphoria/index.md deleted file mode 100644 index 064028d106..0000000000 --- a/docs/projects/reverse-string/euphoria/index.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-02-19 -layout: default -tags: -- euphoria -- reverse-string -title: Reverse String in Euphoria -title1: Reverse String -title2: in Euphoria ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/sequence.e - --- Parse 1st command-line argument -sequence argv = command_line() -sequence s = "" -if length(argv) >= 4 -then - s = argv[4] -end if - --- Show reversed string -sequence t = reverse(s) -printf(STDOUT, "%s\n", {t}) - -``` - -{% endraw %} - -Reverse String in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/f-sharp/index.md b/docs/projects/reverse-string/f-sharp/index.md deleted file mode 100644 index e1b71ced54..0000000000 --- a/docs/projects/reverse-string/f-sharp/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- reverse-string -title: Reverse String in F# -title1: Reverse -title2: String in F# ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Reverse = - let run (s: string) = - let arr = s.ToCharArray() - Array.Reverse arr - String arr - -module Helpers = - - let parseArgs = function - | [| s |] -> Some s - | _ -> None - - let handle = function - | Some s -> - s |> Reverse.run |> printfn "%s" - | None -> - printfn "" - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Helpers.handle - - 0 -``` - -{% endraw %} - -Reverse String in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/fortran/index.md b/docs/projects/reverse-string/fortran/index.md deleted file mode 100644 index 5e8b9b2955..0000000000 --- a/docs/projects/reverse-string/fortran/index.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-15 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-10-15 -layout: default -tags: -- fortran -- reverse-string -title: Reverse String in Fortran -title1: Reverse String -title2: in Fortran ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Fortran](/languages/fortran) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```fortran -program reverse_string - implicit none - character(len=:), allocatable :: arg, rev - integer :: i, n, error - - if (command_argument_count() < 1) then - print '("")' - stop - end if - - ! Get length of argument - call get_command_argument(1, length=n, status=error) - if (error /= 0 .or. n == 0) then - print '("")' - stop - end if - - ! Allocate and read argument - allocate(character(len=n) :: arg) - call get_command_argument(1, arg, status=error) - if (error /= 0) then - print '("")' - deallocate(arg) - stop 0 - end if - - ! Allocate and create reversed string - allocate(character(len=n) :: rev) - do i = 1, n - rev(i:i) = arg(n-i+1:n-i+1) - end do - - print '(A)', rev -end program reverse_string - -``` - -{% endraw %} - -Reverse String in [Fortran](/languages/fortran) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/go/index.md b/docs/projects/reverse-string/go/index.md deleted file mode 100644 index 80b06c3b43..0000000000 --- a/docs/projects/reverse-string/go/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Parker Johansen -- Riddhi K -date: 2018-10-15 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2019-04-01 -layout: default -tags: -- go -- reverse-string -title: Reverse String in Go -title1: Reverse -title2: String in Go ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import "fmt" -import "os" - -//Function to reverse a string -func reverse_string(str string) string { - chars := []rune(str) - for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { - chars[i], chars[j] = chars[j], chars[i] - } - return string(chars) -} - -func main() { - // Check the command line args length - var argslen = len(os.Args) - - // If the length is 2, one command line arg exist - if argslen == 2 { - input := os.Args[1] - fmt.Printf("%v\n", reverse_string(input)) - } -} - -``` - -{% endraw %} - -Reverse String in [Go](/languages/go) was written by: - -- Parker Johansen -- Riddhi K - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/groovy/index.md b/docs/projects/reverse-string/groovy/index.md deleted file mode 100644 index af0f1520c1..0000000000 --- a/docs/projects/reverse-string/groovy/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- robin -- rzuckerm -date: 2019-07-01 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-07-25 -layout: default -tags: -- groovy -- reverse-string -title: Reverse String in Groovy -title1: Reverse String -title2: in Groovy ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Groovy](/languages/groovy) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```groovy -class ReverseString { - static void main(String... args) { - if(args?.length >= 1 && args[0]?.length() >= 1) { - println args[0]?.reverse() - } - } -} - -``` - -{% endraw %} - -Reverse String in [Groovy](/languages/groovy) was written by: - -- robin -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/haskell/index.md b/docs/projects/reverse-string/haskell/index.md deleted file mode 100644 index 87cce7304d..0000000000 --- a/docs/projects/reverse-string/haskell/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Panagiotis Georgiadis -- rzuckerm -date: 2018-10-17 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- haskell -- reverse-string -title: Reverse String in Haskell -title1: Reverse String -title2: in Haskell ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment - -main :: IO () -main = do - args <- getArgs - if null args then - putStrLn "" - else - putStrLn $ reverse $ head args - -``` - -{% endraw %} - -Reverse String in [Haskell](/languages/haskell) was written by: - -- Panagiotis Georgiadis -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/index.md b/docs/projects/reverse-string/index.md deleted file mode 100644 index aa4efc4844..0000000000 --- a/docs/projects/reverse-string/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -date: 2018-04-12 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-05-20 -layout: default -tags: -- reverse-string -title: Reverse String -title1: Reverse -title2: String ---- - - - -Welcome to the Reverse String page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -While Hello World is simple, it often does not show off many interesting -features of a language. Fortunately, this repository shares more samples than -Hello World. One of these more complex programs is known as Reverse a String. - -In this repository, the algorithm must reverse ASCII strings. Do **NOT** -worry about reversing a string in the general case. For instance, if a string -contains surrogate pairs, it's okay if the solution corrupts the string during reversal. - - -## Requirements - -Despite the explicit name, there are some rules in place for consistency. -When writing a Reverse a String program, the following rules should apply: - -1. The implementation must be executable -2. The string to be reversed must come from the command line -3. The program must verify the strings existence on the command line -4. The user must not import libraries to obfuscate the string manipulation - -In other words, the program should get a string from the command line and -reverse it using language utilities only. Acceptable language utilities include -language features and built-in libraries. - -External dependencies are unacceptable. Remember, the goal is to show off language -features and utilities. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Reverse String. - -### Reverse String Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| No Input | | "" | -| Empty Input | "" | "" | -| Ascii String | "Hello, World" | "dlroW ,olleH" | - - -## Articles - -There are 61 articles: - -- [Reverse String in ALGOL 60](/projects/reverse-string/algol60) -- [Reverse String in ALGOL 68](/projects/reverse-string/algol68) -- [Reverse String in AWK](/projects/reverse-string/awk) -- [Reverse String in Bash](/projects/reverse-string/bash) -- [Reverse String in Beef](/projects/reverse-string/beef) -- [Reverse String in Brainfuck](/projects/reverse-string/brainfuck) -- [Reverse String in C](/projects/reverse-string/c) -- [Reverse String in C#](/projects/reverse-string/c-sharp) -- [Reverse String in C++](/projects/reverse-string/c-plus-plus) -- [Reverse String in COBOL](/projects/reverse-string/cobol) -- [Reverse String in Clojure](/projects/reverse-string/clojure) -- [Reverse String in CoffeeScript](/projects/reverse-string/coffeescript) -- [Reverse String in Commodore BASIC](/projects/reverse-string/commodore-basic) -- [Reverse String in Dart](/projects/reverse-string/dart) -- [Reverse String in Dg](/projects/reverse-string/dg) -- [Reverse String in Elvish](/projects/reverse-string/elvish) -- [Reverse String in Erlang](/projects/reverse-string/erlang) -- [Reverse String in Euphoria](/projects/reverse-string/euphoria) -- [Reverse String in F#](/projects/reverse-string/f-sharp) -- [Reverse String in Fortran](/projects/reverse-string/fortran) -- [Reverse String in Go](/projects/reverse-string/go) -- [Reverse String in Groovy](/projects/reverse-string/groovy) -- [Reverse String in Haskell](/projects/reverse-string/haskell) -- [Reverse String in Java](/projects/reverse-string/java) -- [Reverse String in JavaScript](/projects/reverse-string/javascript) -- [Reverse String in Julia](/projects/reverse-string/julia) -- [Reverse String in Kotlin](/projects/reverse-string/kotlin) -- [Reverse String in Lisp](/projects/reverse-string/lisp) -- [Reverse String in Lua](/projects/reverse-string/lua) -- [Reverse String in Mathematica](/projects/reverse-string/mathematica) -- [Reverse String in MoonScript](/projects/reverse-string/moonscript) -- [Reverse String in Never](/projects/reverse-string/never) -- [Reverse String in Nim](/projects/reverse-string/nim) -- [Reverse String in Nit](/projects/reverse-string/nit) -- [Reverse String in OCaml](/projects/reverse-string/ocaml) -- [Reverse String in Objective-C](/projects/reverse-string/objective-c) -- [Reverse String in Octave](/projects/reverse-string/octave) -- [Reverse String in Odin](/projects/reverse-string/odin) -- [Reverse String in PHP](/projects/reverse-string/php) -- [Reverse String in Pascal](/projects/reverse-string/pascal) -- [Reverse String in Perl](/projects/reverse-string/perl) -- [Reverse String in PicoLisp](/projects/reverse-string/picolisp) -- [Reverse String in PowerShell](/projects/reverse-string/powershell) -- [Reverse String in Python](/projects/reverse-string/python) -- [Reverse String in R](/projects/reverse-string/r) -- [Reverse String in Rexx](/projects/reverse-string/rexx) -- [Reverse String in Ruby](/projects/reverse-string/ruby) -- [Reverse String in Rust](/projects/reverse-string/rust) -- [Reverse String in Scala](/projects/reverse-string/scala) -- [Reverse String in Scheme](/projects/reverse-string/scheme) -- [Reverse String in Swift](/projects/reverse-string/swift) -- [Reverse String in TI-BASIC](/projects/reverse-string/ti-basic) -- [Reverse String in Tcl](/projects/reverse-string/tcl) -- [Reverse String in TypeScript](/projects/reverse-string/typescript) -- [Reverse String in Unicat](/projects/reverse-string/unicat) -- [Reverse String in V](/projects/reverse-string/v) -- [Reverse String in Vimscript](/projects/reverse-string/vimscript) -- [Reverse String in Visual Basic](/projects/reverse-string/visual-basic) -- [Reverse String in Wren](/projects/reverse-string/wren) -- [Reverse String in m4](/projects/reverse-string/m4) -- [Reverse String in x86-64](/projects/reverse-string/x86-64) - -*** - - \ No newline at end of file diff --git a/docs/projects/reverse-string/java/index.md b/docs/projects/reverse-string/java/index.md deleted file mode 100644 index a76f211c7d..0000000000 --- a/docs/projects/reverse-string/java/index.md +++ /dev/null @@ -1,359 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-13 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- java -- reverse-string -title: Reverse String in Java -title1: Reverse String -title2: in Java ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class ReverseString { - public static void main(String args[]) { - if (args.length > 0) { - StringBuilder builder = new StringBuilder(args[0]); - String reversed = builder.reverse().toString(); - System.out.println(reversed); - } - } -} - -``` - -{% endraw %} - -Reverse String in [Java](/languages/java) was written by: - -- Jeremy Griffith -- Jeremy Grifski - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's dig right into the complete solution of Reverse a String in Java. - -If you previously read [this article](https://therenegadecoder.com/code/reverse-a-string-in-java/), you may remember the following snippet: - -```java -public class ReverseString { - - public static String reverse(String toReverse) { - char[] characters = toReverse.toCharArray(); - int start = 0; - int end = characters.length - 1; - char temp; - while(end > start){ - temp = characters[start]; - characters[start] = characters[end]; - characters[end] = temp; - end--; - start++; - } - return new String(characters); - } - - public static void main(String args[]) { - if (args.length > 0) { - System.out.println(reverse(args[0])); - } - } -} -``` - -As it turns out, the snippet above works but has a couple pitfalls. The major -pitfall being that it doesn't work for special character sets such as Chinese. -However, I plan to keep it's explanation for the sake of showing off the language. - -At any rate, let's dive in! - -### The General Solution - -As we can see, the general solution leverages the `StringBuilder` library to -reverse a String in Java. Originally, I was against this idea because it really -hides some of the cool features of Java. However, this method is far superior to -the one I shared before as it works for every string you throw at it. - -Anyway, let's dig into it. - -#### The Class Declaration - -Like any Java program, we're stuck creating a class before we can do anything: - -```java -public class ReverseString { - // Insert code here -} -``` - -As an added restriction, we're also stuck using the same name for the file: -`ReverseString.java`. - -#### The Main Method Declaration - -Again, if we want a executable program in Java, we'll need to create a `main` method: - -```java -public static void main(String args[]) { - // Insert code here -} -``` - -The main method structure is always the same. - -First, we declare a public static method which basically means anyone with -access to the class can run this method without creating an instance of the -class. Of course, no one does this with `main` methods, but you get the idea. - -Next, we declare a return type of `void`. In some languages, we might return an -integer, but in Java we return nothing. That's just the convention. - -Finally, we use the `main` method name and declare a `String` array as the input. -The input array will be how we access our command line arguments. - -#### The Main Method Core - -Up to this point, everything has been exactly the same in both solution. In -other words, if you don't like the way something is worded so far, check down -below for another explanation. - -Next, we'll take a look at the inside of the `main` method: - -```java -if (args.length > 0) { - StringBuilder builder = new StringBuilder(args[0]); - String reversed = builder.reverse().toString(); - System.out.println(reversed); -} -``` - -All we're really doing here is checking that we have command line arguments. If -we do, we attempt to reverse them and print them to the user, that simple! - -Of course, instead of reversing the string using the character array, we -leverage the `StringBuilder` library which handles surrogates for us. In other -words, we don't have to worry about corrupting `String`s. - -However, that's a rather high-level explanation. If we look closer, we create a -`StringBuilder` using the first command line argument. Then, we call the `reverse` -method of `StringBuilder` which reverses the `String`. At that point, we convert our -`StringBuilder` back into a String and return it. Done! - -### The Incomplete Solution - -If you previously read this article, you know that I implemented the string -reversal by hand. In other words, I used a loop to swap characters in the -character array. Unfortunately, that solution is incomplete, but I think it shows -off a lot of cool features of Java. So, I'm keeping the code breakdown below. - -#### The Class Declaration - -As with any program in Java, our first step is to create a class: - -```java -public class ReverseString { - // Insert code here -} -``` - -In this case, I created a public class with the name `ReverseString`. Consequently, -the file must also share that name. - -#### The Main Method Declaration - -Within the class, I've declared two methods. The first method I want to focus on -is the `main` method toward the bottom. This method is where the program drops in -when we run it: - -```java -public static void main(String args[]) { - // Insert code here -} -``` - -As we can see, the main method is declared as public and static which means -anyone can access it without an instance of the `ReverseString` class. In addition, -the `main` method has a return type of void. In other words, the method doesn't -return anything. - -In terms of parameters, the `main` method in Java is required to accept an array of -strings. This array contains each of the command line arguments. However, unlike -Python, the first argument is not reserved for the file name. In fact, it's possible -that the array of arguments is empty. - -#### The Main Method Code - -Inside the `main` method is where the magic happens: - -```java -if (args.length > 0) { - System.out.println(reverse(args[0])); -} -``` - -Here, we can see an `if` statement and a print statement. According to the -conditional logic, we only execute the print statement if the list of arguments -is not empty. We do this by checking that the length of the list of arguments -is greater than zero. - -In the case where we have an argument, we run our print statement. At that point, -we have to make a call to reverse, our reverse a string method. Notice that we -pass the first argument always. All other arguments are ignored. - -#### The Reverse Method Declaration - -To get a better idea what the main method is doing, we need to dig into the -reverse method declaration. - -The reverse method is very similar to our main method in that it is also public -and static. That means that we could call the reverse method without an instance -of the `ReverseString` class: - -```java -ReverseString.reverse("Hello, World!") // returns "!dlroW ,olleH" -``` - -The advantage here is we're able to call reverse directly in the `main` method. - -Unlike the `main` method, the `reverse` method returns a `String`. That probably makes -sense since we want the `reverse` method to give us a reversed `String`. - -As a result, the `reverse` method also takes a `String` as input. In other words, the -`reverse` method takes in a `String` and outputs the reverse of that `String` as seen -in the snippet above. - -#### The String to Character Array Transformation - -Now, when I wrote this solution, I specifically avoided the `StringBuilder` library -because it completely masks the `String` reversal: - -```java -new StringBuilder(toReverse).reverse().toString() -``` - -Notice how we could have easily just wrapped our string in a `StringBuilder`, -called the `reverse` method, and converted it back to a `String`. Of course, I think -that defeats the purpose of this series. - -Instead, we start by converting our input `String` to a character array: - -```java -// i.e., ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'] -char[] characters = toReverse.toCharArray(); -``` - -A character array is simply a set of characters which we can freely manipulate. -Normally, we can't manipulate characters in a String because Strings are -immutable in Java. That means that any changes to a `String` results in the -creation of a new `String`. - -#### The Local Variables - -Before we can actually start reversing this character array, we define and -declare a few variables: - -```java -int start = 0; -int end = characters.length - 1; -char temp; -``` - -As we can probably imagine, `start` and `end` refer to the indices at the start and -end of the character array. The `temp` variable will be used to track swaps. -We'll see that play out later. - -#### The Loop Structure - -Okay, so now we're going to perform the String manipulation. To do so, we need -to create a loop: - -```java -while(end > start) { - // Insert code here -} -``` - -Our loop condition is pretty simple. All we do is monitor the `start` and `end` -variables. If at any point `start` crosses `end`, we break out of the loop. As we -can probably imagine, we will be manipulating `start` and `end` inside the loop. - -#### The Loop Internals - -Inside the loop, we pretty much just swap the characters at the `start` and `end` -indices and move those pointers inward by one: - -```java -temp = characters[start]; -characters[start] = characters[end]; -characters[end] = temp; -end--; -start++; -``` - -To do this, we leverage the `temp` variable to hold the start character. Then, we -overwrite the start character with the end character. At that point, we overwrite -the end character with the start character that we stored in `temp`. - -When we've completed the character swap, we decrement the end pointer and increment -the start pointer. This allows us to slowly reverse each pair of characters -until we reach the middle of the `String`. - -#### The Return Statement - -Finally, we convert our character array to a `String`, and we return it: - -```java -return new String(characters); -``` - -At a high level, we take a string from the command line, reverse it, and output -it to the user. That's it! - - -## How to Run the Solution - -If we're looking to run this program, perhaps the first thing we should do is -[download the solution from GitHub](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/j/java/ReverseString.java). Then, we'll need to get the latest version of -Java. At that point, all we have to do is run the following from the command line: - -```console -javac ReverseString.java -java ReverseString "Hello, World!" -``` - -The first line compiles the code while the second line runs the binary. In this -case, we're trying to reverse "Hello, World!" - -Alternatively, we can run the Reverse a String in Java solution using an [online -Java compiler](https://www.onlinegdb.com/online_java_compiler). Just copy the solution into the developing pane, add a string to -the command line arguments, and hit run. diff --git a/docs/projects/reverse-string/javascript/index.md b/docs/projects/reverse-string/javascript/index.md deleted file mode 100644 index a05763afba..0000000000 --- a/docs/projects/reverse-string/javascript/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Pascal Spiesz -- rzuckerm -- Trever Shick -date: 2018-05-06 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- javascript -- reverse-string -title: Reverse String in JavaScript -title1: Reverse String -title2: in JavaScript ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const reverse = s => s.split('').reverse().join(''); - -if (process.argv.length > 2) { - console.log(reverse(process.argv[2])); -} - -``` - -{% endraw %} - -Reverse String in [JavaScript](/languages/javascript) was written by: - -- rzuckerm -- Trever Shick - -This article was written by: - -- Jeremy Grifski -- Pascal Spiesz -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's look at the code in detail. - -```java -const reverse = s => s.split('').reverse().join(''); -``` - -First there is a function declaration `reverse` which takes one parameter `s`. -The `reverse` function returns a method chain of the `s` parameter. It assumes that the parameter is of type string. A string in JavaScript offers numerous methods, like `.toLowerCase()`, which would mutate a string to all lowercase letters. - -Another method of the `String` object is the `split` method which you can see above. -`split()` takes two optional parameters, a seperator and a limit. In the `reverse` function it is used with an empty string `''` as a seperator. This has the effect of splitting the string at _every_ character. The return value of the `split` method is, and this makes the beauty of this solution, an array, which has it's own methods built in. - -If you call the `reverse` function above, for example with `'hello'`, the `split` method would return `['h', 'e', 'l', 'l', 'o']`. Since this is an array you can immediately use one of the various array methods available in JavaScript. Luckily the language helps us a lot here, since it already has a method `.reverse()` to reverse an array. - -Now we are at the second chained method and our hypothetical output would look like this `['o', 'l', 'l', 'e', 'h']`. We are just one step ahead of our solution. - -All we need to do now is to somehow get back to a string. One of the array methods JavaScript offers us is the `.join()` method. It, kind of, is the opposite of the `split` method as it brings an array back together, based on an optional `seperator` parameter, and returns a string. Like the `split` method an empty string as a parameter means that it will execute on every value in the array. Since we have single characters as values it will simply concatenate them together to our string. - -Now, let's look at the rest of the code: - -```java -if (process.argv.length > 2) { - console.log(reverse(process.argv[2])); -} -``` - -`process.argv` contains the command-line arguments. We make sure there are enough. If so, we call our `reverse` function with -the first one (`process.argv[2]`, since the first two, `process.argv[0]` and `process.argv[1]` can be ignored). Then, -`console.log` displays the reversed string returned from the `reverse` method. - -Now our solution is complete. - - -## How to Run the Solution - -To run this example you can simply open the dev tools of your browser (F12) in most cases and navigate to the `console` tab. -There you can paste in the code snippet from above. - -Alternatively you can paste the code into an [online Javascript interpreter](https://onecompiler.com/javascript). diff --git a/docs/projects/reverse-string/julia/index.md b/docs/projects/reverse-string/julia/index.md deleted file mode 100644 index c5479deda0..0000000000 --- a/docs/projects/reverse-string/julia/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- rzuckerm -- smjalageri -date: 2022-10-02 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- julia -- reverse-string -title: Reverse String in Julia -title1: Reverse String -title2: in Julia ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -#!/usr/bin/julia -# Reverse the Input String -# Function to reverse the input string -function reverse_string(n) - println(reverse(n)) -end - -if (length(ARGS) > 0) - reverse_string(ARGS[1]) -end - -``` - -{% endraw %} - -Reverse String in [Julia](/languages/julia) was written by: - -- rzuckerm -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/kotlin/index.md b/docs/projects/reverse-string/kotlin/index.md deleted file mode 100644 index bf920761f9..0000000000 --- a/docs/projects/reverse-string/kotlin/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Barry Rowe -- rzuckerm -date: 2018-10-20 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- kotlin -- reverse-string -title: Reverse String in Kotlin -title1: Reverse String -title2: in Kotlin ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -fun main(args: Array){ - // Get input, or use default value - val targetValue = when (args.size > 0 && !args[0].isNullOrBlank()) { - true -> args[0] - false -> "" - } - - // Kotlin provides a simple `reversed()` function in the standard - // library for all String/CharSequence objects - println(targetValue.reversed()) -} -``` - -{% endraw %} - -Reverse String in [Kotlin](/languages/kotlin) was written by: - -- Barry Rowe -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/lisp/index.md b/docs/projects/reverse-string/lisp/index.md deleted file mode 100644 index 0b4383ca2b..0000000000 --- a/docs/projects/reverse-string/lisp/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Parker Johansen -- rzuckerm -date: 2020-10-11 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- lisp -- reverse-string -title: Reverse String in Lisp -title1: Reverse String -title2: in Lisp ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Lisp](/languages/lisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lisp -(defparameter input (cadr *posix-argv*)) -(cond - ((null input) ()) - (t (write-line (reverse input))) -) - -``` - -{% endraw %} - -Reverse String in [Lisp](/languages/lisp) was written by: - -- Parker Johansen -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/lua/index.md b/docs/projects/reverse-string/lua/index.md deleted file mode 100644 index 41ecf2716b..0000000000 --- a/docs/projects/reverse-string/lua/index.md +++ /dev/null @@ -1,222 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Matt Wiley -- rzuckerm -date: 2018-09-19 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- lua -- reverse-string -title: Reverse String in Lua -title1: Reverse -title2: String in Lua ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -if #arg > 0 then - print(string.reverse(arg[1])) -end - -``` - -{% endraw %} - -Reverse String in [Lua](/languages/lua) was written by: - -- Jeremy Grifski -- Matt Wiley - -This article was written by: - -- Jeremy Grifski -- Matt Wiley -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's look at the code in detail. - -It's pretty simple, right? (It is for sure, but this snippet hides some Lua quirkiness which I've taken some time to call out in the caveats section at the end of the article.) - -Let's quickly step through the logic and see what's going on. - -### The Basics - -Lua is a scripting language, and like almost all scripting languages it is interpreted rather than compiled. The full explanation of what that means is out of scope here, but suffice it to say that Lua has much less rigor in how it is executed than a compiled language might. That's evident from the get go. - -The code block above is not a snippet (well it is, but bear with us here), it is the complete script file. We can save this file as `reverse-string.lua` as is and run it with the Lua interpreter. Dead simple. - -### The Code Itself - -Let's roll through the code in line-by-line fashion. - -Ready? Ok. - -#### Line #1 - -```lua -if #arg > 0 then -``` - -The first thing we see looks pretty obvious. We have an `if` which we see as a control flow concept in most languages. It is followed by some comparison logic which should resolve to a value of either true or false, and the comparison logic is closed by the keyword `then`. The comparison logic is using a special operator -- the `#`. This `#` operator is the length operator and it is attempting\* to give us the number of arguments that the user has passed to the script. In this case we're checking that the caller has provided at least 1 string input to the script at the command line. If we were to read this in English it would read: - -``` -If the number of args is greater than 0, then ... -``` - -#### Line #2 - -```lua - print(string.reverse(arg[1])) -``` - -This is what we're here for! As with most languages, especially scripting languages, these sorts of common operations are baked in. Since we have a built-in utility that let's us do exactly what we're looking to do we can get right to it without having to mess around with special data structures or manual string manipulation. Instead, we get straight to the point. So much so that we can read the code as though it were practically English text. - -``` -Print the string held in the variable 'arg[1]' in reverse to standard output. -``` - -At this point you should see your input displayed back to you, but, ya know, in reverse. - -**Note:** There's a lot hiding the `string.reverse(...)` syntax where Lua's object-oriented programming is concerned, and unfortunately it is out of scope for this article. If you're interested you should read more about it [here](https://www.lua.org/pil/16.html). - -#### Line #3 - -```lua -end -``` - -The `end` keyword in Lua closes blocks of code. In this case it closes the `if` (or `if/then`) block. - -After this the interpreter reads the last new line character and an EOF (end-of-file) character, and execution of our script is complete. - -### Conclusion - -It's hard for string reversal to get much simpler than this. Lua as a language has some strange boundaries but it can be really powerful. - -If you're on a Mac and you're looking for something to play around with that can give you concrete experience with Lua scripting checkout [Hammerspoon](https://www.hammerspoon.org/). It's a Lua-based automation tool for OSX and macOS with some fun integrations for common apps. Check it out! - -## Caveats, Notes and Trivia - -### \* So about that `#` ... - -Right out of the gate we're running into some Lua quirkiness. It's hiding in the `#` unary operator that's hanging out in front of that `arg` variable. So, before we get into the quirk you should know something about Lua: just about everything that's not a number or text is held in a data structure called a table - `arg` is no different. It is a table that holds all of the arguments passed along to the currently running script. - -The `#` operator is called the 'length operator', but it's a bit of misnomer. Here's why (and you can read about it in the docs [here](http://www.lua.org/manual/5.2/manual.html#3.4.6)), the operator is ONLY strictly defined for strings, and in the case of strings it actually only counts bytes - not characters. So it would seem that counts on Unicode strings would be, uh, let's say inaccurate. All other values can be overridden to use any length calculation the author of the script provides, and on the face of it this is a pretty interesting feature. That is unless the author doesn't provide a function for calculating length and let's Lua just do Lua things. - -Lua, when left to its default behavior for table length calculation, doesn't calculate anything at all. Before I explain, let's get on the same page about tables. - -In Lua, tables are alike to dictionaries in Python or objects in Javascript. The syntax is a little different, but the concept is very similar in that you get a set of key-value pairs. - -We can define a table in few different ways (and you can read more about this [here](https://www.lua.org/pil/3.6.html)): - -```lua -myTable = {a=1, b=2, c=3} -``` - -This is the same as: - -```lua -myTable={} -myTable.a=1 -myTable.b=2 -myTable.c=3 -``` - -And if we were define a simple list of strings: - -```lua -myThings = {'dog', 'cat', 'bird'} -``` - -what we're actually getting is - -```lua -myThings[1]='dog' -myThings[2]='cat' -myThings[3]='bird' -``` - -We're getting an implicit table with numbers for keys. And, this is special when it comes to the default behavior of the `#` operator. It is a table where the keys are a valid sequence, and when Lua sees a sequence in the keys it will report the highest value in the sequence as the length. In this case, 3. So for this EXACT version of a table the default length calculation is correct. - -It gets weirder. Hang on. - -Lua is (very atypically) a 1-indexed language. Meaning it starts counting at 1, where most other programming languages start counting at 0. So a "valid" sequence only includes the counting numbers {1...n}. **Zero is not included in the sequence.** This means that when we have our script or command-line arguments table: - -```lua -arg[0]='my-script.lua' -- the filename of the script being run currently -arg[1]='fibonacci' -- the user input -``` - -The `#` operator reports a table length of 1 when there are actually two pairs in the table. - -How about another (even weirder) example... - -If we were to stuff a table like so: - -```lua -a={'one', 'two', 'three'} -a['matt']='wiley' -a[5]='five' -``` - -We're actually getting something like this: - -```lua -a[1]='one' -a[2]='two' -a[3]='three' -a['matt']='wiley' -a[5]='five' -``` - -And when we call `#a` we would get back 3. The docs I've read aren't very clear on why this is the case in Lua. I would expect that the length operator returned some indicator that it just couldn't do its job, but instead it appears to find the first contiguous sequence (in this case {1,2,3}) and report the last key in the sequence as the length. - -I know. I don't get it either. That's just Lua. - -So, for reading simple lists (or rather even explicitly validly-sequenced tables), the `#` operator works well. For all other use cases: Double check that return value. Weird bugs abound. Better yet, read more about how to leverage other mechanisms of the Lua language to better manage your tables. - -For command-line argument, though, this works just fine. - - -## How to Run the Solution - -First, make sure you have Lua installed on your local machine. You can read about how to do that here: [Getting started with Lua](https://www.lua.org/start.html). - -Once you have Lua installed, you can download the `reverse-string.lua` file from this repo ([here](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/l/lua/reverse-string.lua)). - -Save that file wherever you like, then open a terminal or command prompt to that directory. - -There you should be able to run the following: - -```sh -lua reverse-string.lua fibonacci -``` - -And see the following output: - -```sh -iccanobif -``` diff --git a/docs/projects/reverse-string/m4/index.md b/docs/projects/reverse-string/m4/index.md deleted file mode 100644 index fd6f1392b2..0000000000 --- a/docs/projects/reverse-string/m4/index.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-13 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-08-13 -layout: default -tags: -- m4 -- reverse-string -title: Reverse String in m4 -title1: Reverse -title2: String in m4 ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -dnl Commas are intepreted as argument separators, so need to change them to something that -dnl won't appear in the argument and then change them back -define(`escape', `translit(``$1'', `,', `«')') -define(`unescape', `translit(``$1'', `«', `,')') - -dnl reverse(str) -define(`reverse', `unescape(_reverse(escape(`$1')))') -define(`_reverse', `ifelse(len(`$1'), 0, , `_reverse(substr(`$1', 1))`'substr(`$1', 0, 1)')') -divert(0)dnl -ifelse(ARGC, 0, , `reverse(ARGV1)') - -``` - -{% endraw %} - -Reverse String in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/mathematica/index.md b/docs/projects/reverse-string/mathematica/index.md deleted file mode 100644 index 95cb4a8999..0000000000 --- a/docs/projects/reverse-string/mathematica/index.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-16 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-01-16 -layout: default -tags: -- mathematica -- reverse-string -title: Reverse String in Mathematica -title1: Reverse String -title2: in Mathematica ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual function operating on Mathematica strings is just the built-in StringReverse. An outer function provides the 'user interface': *) - -stringReverseMain = Function[{s}, - Catch[ - StringReverse[ - If[ - StringQ[s] \[And] \[Not] StringMatchQ[s, ""], - s, - Throw["Usage: please provide a string"]]]]]; - - -(* Valid Tests *) - -Print /@ stringReverseMain /@ { - "Hello, World" - }; - - -(* Invalid Tests *) - -stringReverseMain[""] - -``` - -{% endraw %} - -Reverse String in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/moonscript/index.md b/docs/projects/reverse-string/moonscript/index.md deleted file mode 100644 index c659563a56..0000000000 --- a/docs/projects/reverse-string/moonscript/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- dannymccarragher -date: 2024-11-12 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2024-11-12 -layout: default -tags: -- moonscript -- reverse-string -title: Reverse String in MoonScript -title1: Reverse String -title2: in MoonScript ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [MoonScript](/languages/moonscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```moonscript --- Function to reverse a string -reverse_string = (str) -> - if str == '' then return '' - - result = '' - - for i = #str, 1, -1 - result = result .. str\sub(i, i) - - return result - --- Main executable section - -if not arg or #arg == 0 - print '' -else - input_str = arg[1] - reversed_str = reverse_string(input_str) - print reversed_str - - -``` - -{% endraw %} - -Reverse String in [MoonScript](/languages/moonscript) was written by: - -- dannymccarragher - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/never/index.md b/docs/projects/reverse-string/never/index.md deleted file mode 100644 index 45cecc3d32..0000000000 --- a/docs/projects/reverse-string/never/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Ron Zuckerman -- rzuckerm -- smaludzi -date: 2018-09-20 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-09-05 -layout: default -tags: -- never -- reverse-string -title: Reverse String in Never -title1: Reverse String -title2: in Never ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Never](/languages/never) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```never -func reverse(s: string) -> string -{ - let n = length(s); - (n > 0) ? s[n - 1 .. 0] : "" -} - -func main(argv[argc]: string) -> int -{ - let s = (argc > 0) ? argv[0] : ""; - prints(reverse(s) + "\n"); - 0 -} - -``` - -{% endraw %} - -Reverse String in [Never](/languages/never) was written by: - -- Ron Zuckerman -- rzuckerm -- smaludzi - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/nim/index.md b/docs/projects/reverse-string/nim/index.md deleted file mode 100644 index 50a60b4875..0000000000 --- a/docs/projects/reverse-string/nim/index.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -authors: -- Michael Olson -- rzuckerm -date: 2019-10-22 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- nim -- reverse-string -title: Reverse String in Nim -title1: Reverse -title2: String in Nim ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Nim](/languages/nim) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nim -# For reversing a string passed in as a parameter -import os -import strutils - -var text: string -try: - text = paramStr(1) -except IndexError: - quit(0) - -var reversed_text: string -for i in countdown(len(text)-1, 0): - reversed_text = reversed_text & text[i] - -echo reversed_text - - -``` - -{% endraw %} - -Reverse String in [Nim](/languages/nim) was written by: - -- Michael Olson -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/nit/index.md b/docs/projects/reverse-string/nit/index.md deleted file mode 100644 index e32f3e29f6..0000000000 --- a/docs/projects/reverse-string/nit/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- liliann19 -date: 2025-10-30 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-10-30 -layout: default -tags: -- nit -- reverse-string -title: Reverse String in Nit -title1: Reverse -title2: String in Nit ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Nit](/languages/nit) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```nit -if args.length > 0 then - var word = args[0] - var reversed = "" - var i = word.length - 1 - while i >= 0 do - reversed += word.chars[i].to_s - i -= 1 - end - printn reversed -end -``` - -{% endraw %} - -Reverse String in [Nit](/languages/nit) was written by: - -- liliann19 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/objective-c/index.md b/docs/projects/reverse-string/objective-c/index.md deleted file mode 100644 index 1fe236fff8..0000000000 --- a/docs/projects/reverse-string/objective-c/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Tim Lange -- Ștefan-Iulian Alecu -date: 2019-10-14 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-04-30 -layout: default -tags: -- objective-c -- reverse-string -title: Reverse String in Objective-C -title1: Reverse String -title2: in Objective-C ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Objective-C](/languages/objective-c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```objective-c -#import - -@interface NSString (Reversal) -@property(nonatomic, readonly) NSString* reversed; -@end - -@implementation NSString (Reversal) - -- (NSString*)reversed { - NSUInteger len = self.length; - if (len < 2) return self; - - unichar buffer[len]; - [self getCharacters:buffer range:NSMakeRange(0, len)]; - - NSUInteger i = 0; - NSUInteger j = len - 1; - - while (i < j) { - unichar tmp = buffer[i]; - buffer[i++] = buffer[j]; - buffer[j--] = tmp; - } - - return [NSString stringWithCharacters:buffer length:len]; -} - -@end - -int main(int argc, const char* argv[]) { - @autoreleasepool { - NSString* input = argc > 1 ? @(argv[1]) : nil; - NSString* output = input.reversed; - puts(output.UTF8String); - } - return 0; -} - -``` - -{% endraw %} - -Reverse String in [Objective-C](/languages/objective-c) was written by: - -- Tim Lange -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/ocaml/index.md b/docs/projects/reverse-string/ocaml/index.md deleted file mode 100644 index a6b055b37a..0000000000 --- a/docs/projects/reverse-string/ocaml/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- alope107 -date: 2026-05-20 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-05-20 -layout: default -tags: -- ocaml -- reverse-string -title: Reverse String in OCaml -title1: Reverse String -title2: in OCaml ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [OCaml](/languages/ocaml) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ocaml -let reverse s = - let len = String.length s in - String.init len (fun i -> s.[len - i - 1]) - -let () = - print_endline - (match Sys.argv with [||] | [| _ |] -> "" | args -> reverse args.(1)) -(* Any additional arguments are ignored, following the example of other samples in this repo *) - -``` - -{% endraw %} - -Reverse String in [OCaml](/languages/ocaml) was written by: - -- alope107 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/octave/index.md b/docs/projects/reverse-string/octave/index.md deleted file mode 100644 index 457c5242ff..0000000000 --- a/docs/projects/reverse-string/octave/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- octave -- reverse-string -title: Reverse String in Octave -title1: Reverse String -title2: in Octave ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function reverse_string() - arg_list = argv(); - nargin = length(arg_list); - if nargin ~= 0 - disp(fliplr(arg_list{1})); - end -end - -``` - -{% endraw %} - -Reverse String in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/odin/index.md b/docs/projects/reverse-string/odin/index.md deleted file mode 100644 index 3aa738df12..0000000000 --- a/docs/projects/reverse-string/odin/index.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -authors: -- nallovint -date: 2024-07-25 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2024-07-25 -layout: default -tags: -- odin -- reverse-string -title: Reverse String in Odin -title1: Reverse String -title2: in Odin ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Odin](/languages/odin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```odin -package main - -import "core:fmt" -import "core:strings" -import "core:os" - -reverse_string :: proc(str : string) { - sb := strings.builder_make(0, len(str)) - #reverse for ch in str { - strings.write_rune(&sb, ch) - } - fmt.println(strings.to_string(sb)) -} - -main :: proc() { - if len(os.args) < 2 { - return - } - reverse_string(os.args[1]) -} - -``` - -{% endraw %} - -Reverse String in [Odin](/languages/odin) was written by: - -- nallovint - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/pascal/index.md b/docs/projects/reverse-string/pascal/index.md deleted file mode 100644 index b19bb80b26..0000000000 --- a/docs/projects/reverse-string/pascal/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- rzuckerm -- smjalageri -date: 2020-10-19 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- pascal -- reverse-string -title: Reverse String in Pascal -title1: Reverse String -title2: in Pascal ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program reversestring(input, output, stdErr); -(*Accept a String from Command Line, Reverse it & Print it*) -var - i, j: Integer; - buf, result: String; -begin - buf := paramStr(1); - setlength(result,length(buf)); - i:=1; - j:=length(buf); - while (i<=j) do - begin - result[i]:=buf[j-i+1]; - inc(i); - end; - writeln(result); -end. - -``` - -{% endraw %} - -Reverse String in [Pascal](/languages/pascal) was written by: - -- rzuckerm -- smjalageri - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/perl/index.md b/docs/projects/reverse-string/perl/index.md deleted file mode 100644 index 9f3907a791..0000000000 --- a/docs/projects/reverse-string/perl/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- Ștefan-Iulian Alecu -date: 2018-08-22 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- perl -- reverse-string -title: Reverse String in Perl -title1: Reverse String -title2: in Perl ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -my ($str) = @ARGV; -say scalar reverse $str if defined $str; - -``` - -{% endraw %} - -Reverse String in [Perl](/languages/perl) was written by: - -- Christoph Böhmwalder -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/php/index.md b/docs/projects/reverse-string/php/index.md deleted file mode 100644 index e37ccd2ec2..0000000000 --- a/docs/projects/reverse-string/php/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- rzuckerm -- samgan-khan -date: 2019-07-15 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-03-19 -layout: default -tags: -- php -- reverse-string -title: Reverse String in PHP -title1: Reverse -title2: String in PHP ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - 1) { - $input = $argv[1]; - echo strrev($input); -} - -``` - -{% endraw %} - -Reverse String in [PHP](/languages/php) was written by: - -- rzuckerm -- samgan-khan - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/picolisp/index.md b/docs/projects/reverse-string/picolisp/index.md deleted file mode 100644 index d3b38012e8..0000000000 --- a/docs/projects/reverse-string/picolisp/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-05-15 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- picolisp -- reverse-string -title: Reverse String in PicoLisp -title1: Reverse String -title2: in PicoLisp ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [PicoLisp](/languages/picolisp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```picolisp -(let Str (argv A) - (prinl - (pack - (reverse - (chop A))))) -(bye) - -``` - -{% endraw %} - -Reverse String in [PicoLisp](/languages/picolisp) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/powershell/index.md b/docs/projects/reverse-string/powershell/index.md deleted file mode 100644 index a366237a97..0000000000 --- a/docs/projects/reverse-string/powershell/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Devin Leaman -- Jeremy Grifski -- rzuckerm -date: 2018-05-28 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- powershell -- reverse-string -title: Reverse String in PowerShell -title1: Reverse String -title2: in PowerShell ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -<# -.SYNOPSIS - A simple script for reversing a String. - -.DESCRIPTION - A simple script for reversing a String in PowerShell in order to show some -features of the language. - -.PARAMETER Str - The string to reverse. - -.EXAMPLE - .\ReverseString.ps1 -Str 'Hello, World' - -.EXAMPLE - .\ReverseString.ps1 "Les Misérables" - -.EXAMPLE - .\ReverseString.ps1 "字樣樣品" - -.NOTES - This script does *not* support emoji as PowerShell only has full support for -emoji within the ISE. -#> -param -( - [Parameter(Mandatory = $false, Position = 0)] - [string]$Str -) - -$StringBuilder = New-Object -TypeName System.Text.StringBuilder($Str.Length) - -for ($x = ($Str.Length - 1); $x -ge 0; $x--) { - [void]$StringBuilder.Append($Str.Chars($x)) -} - -Write-Host $StringBuilder.ToString() - -``` - -{% endraw %} - -Reverse String in [PowerShell](/languages/powershell) was written by: - -- Devin Leaman -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/python/index.md b/docs/projects/reverse-string/python/index.md deleted file mode 100644 index 5f6c9a4e9b..0000000000 --- a/docs/projects/reverse-string/python/index.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -authors: -- Jeremy Griffith -- Jeremy Grifski -- rzuckerm -date: 2018-04-12 -featured-image: reverse-string-in-python.jpg -last-modified: 2023-05-15 -layout: default -tags: -- python -- reverse-string -title: Reverse String in Python -title1: Reverse String -title2: in Python ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - -if len(sys.argv) > 1: - print(sys.argv[1][::-1]) - -``` - -{% endraw %} - -Reverse String in [Python](/languages/python) was written by: - -- Jeremy Griffith - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's start by looking at the complete algorithm to reverse a string in Python. - -As we can see, we can write a script to reverse a string in about three lines -of code. In the following sections, we'll take a look at a breakdown of each of -these lines. - -### The Python `sys` Library - -In the first line of code, we'll notice that we're importing the built-in `sys` -library: - -```python -import sys -``` - -If you're unfamiliar with this library, basically it contains functions for -interacting directly with the interpreter during runtime. - -In our case, we're leveraging the library to access the command line. From the -command line, we can get our string that we're going to reverse. - -### The Conditional - -After we've imported our sys library, this script runs a bit of a sanity check: - -```python -if len(sys.argv) > 1: -``` - -If we recall from the previous section, we found out that `sys` gives us access to -the command line. We can get the array of command line arguments using `argv`. -According to Python documentation, `argv` is the list of command line arguments. - -With that in mind, it's clear that we're just verifying its length. But, why -aren't we just checking to see if the list is empty? That would probably be -more efficient and more explicit. Well, as it turns out, the interpreter stores -the script name as the first argument, so `argv` will always contain at least one -element. - -If we put all that information together, we'll notice that we only branch if the -list of command line arguments contains more than one item. If it does, we know -the user has passed us some string. - -### The Slice & Print - -Our last line is a bit terse, but we can handle it: - -```python -print(sys.argv[1][::-1]) -``` - -The first thing to note is the `print` function. We'll probably remember that -from our Hello World experience, so no need to dig into that much deeper. - -Inside the `print` function, we have quite a bit of syntax. First, we access our -command line arguments again using `sys.argv`. However, this time we're trying to -access one of the items using an index of one. Like many languages, Python list -indices start from zero, so clearly we're trying to access our string for reversal. - -After that, we'll notice another piece of interesting syntax: `[::-1]`. It looks -sort of like list access, but it has colons and a negative value. As it turns -out, that syntax is called a slice. Typically, slices are used to get a subset -of an iterable. For instance, if I wanted the first four characters of a string, -I could do the following: - -```python -myString = "Hello, World!" -print(myString[:4]) # Prints "Hell" -``` - -Okay, maybe that's not a family friendly example, but you get the idea. - -Now, with a single colon, we can slice between any two indices. With a second -colon, we can declare the step. For example, maybe we want every other character -in a string: - -```python -myString = "Hello, World!" -print(myString[::2]) # Prints "Hlo ol!" -``` - -As an added wrinkle, we can step backwards through the string using a negative -value. That's exactly how we reverse the string in our example. - -So, let's put it all together. We get our string off the command line, take a -slice of it backwards, and print the result. How cool is that? - - -## How to Run the Solution - -To run the Reverse a String in Python program, grab a copy of the [Python file from GitHub][1]. -After that, get the [latest version of Python][2]. Now, all you have to -do is run the following from the command line: - -```console -python reverse-string.py "Hello, World!" -``` - -Alternatively, you can always copy the source code into an [online Python interpreter][3]. -Just make sure you pass some input to your script before you run it. - -[1]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/reverse_string.py -[2]: https://www.python.org/downloads/ -[3]: https://www.online-python.com/ diff --git a/docs/projects/reverse-string/r/index.md b/docs/projects/reverse-string/r/index.md deleted file mode 100644 index 3aeea61ebc..0000000000 --- a/docs/projects/reverse-string/r/index.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -authors: -- Veena ManikPrabhu -date: 2020-10-19 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2020-10-19 -layout: default -tags: -- r -- reverse-string -title: Reverse String in R -title1: Reverse -title2: String in R ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [R](/languages/r) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```r -args<- commandArgs(TRUE) -if(length(args) > 0 ){ - if (args[1] != ""){ - splits <- strsplit(args, "")[[1]] - reversed <- rev(splits) - reversed <-as.character(rev(splits)) - j <- paste(reversed, collapse = '') - cat(noquote(j)) - } -} - -``` - -{% endraw %} - -Reverse String in [R](/languages/r) was written by: - -- Veena ManikPrabhu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/rexx/index.md b/docs/projects/reverse-string/rexx/index.md deleted file mode 100644 index d4e228d326..0000000000 --- a/docs/projects/reverse-string/rexx/index.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -authors: -- Emily Menken -date: 2025-02-17 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-02-17 -layout: default -tags: -- reverse-string -- rexx -title: Reverse String in Rexx -title1: Reverse String -title2: in Rexx ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Rexx](/languages/rexx) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rexx -/* Reverse-String */ - -parse arg inputString -if inputString = "" then exit /* exits right away if there is no input! */ - -say reverseString(inputString) -exit - -reverseString: -parse arg str -length = length(str) -reversed = "" - -do i = length to 1 by -1 -reversed = reversed || substr(str, i, 1) -end - -return reversed -/* Req: Hello, World Expected Res: dlroW ,olleH */ - -``` - -{% endraw %} - -Reverse String in [Rexx](/languages/rexx) was written by: - -- Emily Menken - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/ruby/index.md b/docs/projects/reverse-string/ruby/index.md deleted file mode 100644 index a91f41fd6c..0000000000 --- a/docs/projects/reverse-string/ruby/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- Jeremy Grifski -- rzuckerm -- Ștefan-Iulian Alecu -date: 2018-12-24 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- reverse-string -- ruby -title: Reverse String in Ruby -title1: Reverse String -title2: in Ruby ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -puts ARGV.first.reverse if ARGV.first - -``` - -{% endraw %} - -Reverse String in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Right away, we begin by checking to see if the user gave us a string in the -form of a command line argument: - -```ruby -if ARGV.length >= 1 -``` - -If not, we exit the program - -Otherwise, we store the command line argument that the user passed into a string: - -```ruby -else - string = ARGV[0] - - puts string.reverse -end -``` - -Then, we reverse the string using the built-in method of the string class and -print the result onto the screen. - -As we can see, our solution is very brief. That's because we're using a -high-level language that offers many different tools, so we can concentrate on -building our application instead of worrying about implementation details. - - -## How to Run the Solution - -If you have Ruby installed on your machine, you can run the following command: - -```console -ruby reverse-string.rb SomeStringHere -``` - -Alternatively, websites like [REPL][1] allow you to run code from several programming -languages in your browser. Feel free to leverage one of those! - -[1]: https://replit.com/languages/ruby diff --git a/docs/projects/reverse-string/rust/index.md b/docs/projects/reverse-string/rust/index.md deleted file mode 100644 index df1dacfac5..0000000000 --- a/docs/projects/reverse-string/rust/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Sebastian Veitleder -date: 2018-07-04 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2018-07-04 -layout: default -tags: -- reverse-string -- rust -title: Reverse String in Rust -title1: Reverse String -title2: in Rust ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env; - -fn main() { - let mut strings: Vec = env::args().collect(); - strings.remove(0); //Removes path to executable from argument vector. - for string in &strings { - println!("{}", string.chars().rev().collect::()); - } -} - -``` - -{% endraw %} - -Reverse String in [Rust](/languages/rust) was written by: - -- Sebastian Veitleder - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/scala/index.md b/docs/projects/reverse-string/scala/index.md deleted file mode 100644 index be4d0fcda6..0000000000 --- a/docs/projects/reverse-string/scala/index.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2026-04-11 -layout: default -tags: -- reverse-string -- scala -title: Reverse String in Scala -title1: Reverse String -title2: in Scala ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Scala](/languages/scala) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scala -object ReverseString: - def main(args: Array[String]): Unit = - args.headOption match - case Some(str) => println(str.reverse) - case None => println("") -``` - -{% endraw %} - -Reverse String in [Scala](/languages/scala) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/scheme/index.md b/docs/projects/reverse-string/scheme/index.md deleted file mode 100644 index 928214ac94..0000000000 --- a/docs/projects/reverse-string/scheme/index.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -authors: -- awoerner92 -- Francisco Peters -- Jeremy Grifski -- rzuckerm -date: 2018-05-07 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- reverse-string -- scheme -title: Reverse String in Scheme -title1: Reverse String -title2: in Scheme ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Scheme](/languages/scheme) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```scheme -(define (reverse-string x) - (list->string (reverse (string->list x)))) - -(if (> (length (command-line)) 1) - (display (reverse-string (list-ref (command-line) 1))) -) - -``` - -{% endraw %} - -Reverse String in [Scheme](/languages/scheme) was written by: - -- Francisco Peters -- Jeremy Grifski -- rzuckerm - -This article was written by: - -- awoerner92 -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -As you can see, we can write a script to reverse a string in five lines of code (not counting the blank line). -In the following sections, we'll take a look at a breakdown of each of these lines. - -### The Function Definition - -```scheme -(define (reverse-string x) -``` - -The keyword *define* binds a function's definition to the specified name. This -keyword is followed by the name of the function and the function's argument. In -this particular case, the argument *x* is the string we want to reverse. - -### The Function Body - -```scheme -(list->string (reverse (string->list x)))) -``` - -The whole magic happens in the second line. We will go through it step by step -from the inside out, since this makes understanding it easier. - -The most inner pair of parentheses calls the conversion of our string *x* to a -list. Then, this list is reversed by calling the function *reverse* which is part -of the standard library. Finally, the reversed list is converted back to a string. -This is also the return value of the function *reverse-string*. - -### Check if Enough Command-Line Arguments - -```scheme -(if (> (length (command-line)) 1) - ... -) -``` - -Let's look at this starting from the inner pair of parentheses. -*command-line* is a list containing the command-line arguments. The first value -is the name of the script. The rest are the user-specified arguments. The *length* -method returns the number of command-line arguments. The `>` takes two arguments -and indicates a "true" value if the first argument is greater than the second. -The *if* statement will only execute the code in the outermost parentheses -for a "true" value. Therefore, we only do something if the number of command-line -arguments is greater than 1. Otherwise, the program exits. - -### The Display - -```scheme -(display (reverse-string (list-ref (command-line) 1))) -``` - -The first thing you see there, is the *display* function. You'll probably remember -it from our Hello World experience, so have a look there, if you need a quick -refresher of what it does. - -The argument to this function is the *reverse-string* function defined above. It -receives the second command-line argument (the string to reverse), -which is accessed with the function *list-ref*. *list-ref* takes two arguments: -the list and an index. In this case, the list is the command-line and the index -is `1`, which is the string to reverse. Finally, `display` outputs to reversed -string. - -If you replace `(list-ref (command-line) 1)` with a string, the program prints that string -reversed. To show you an example, the output of -`(display (reverse-string "Hello"))` is *olleH*. - - -## How to Run the Solution - -The quickest way is probably to try use an [online Scheme interpreter][1]. Just copy -the code above, drop it into the editor, fill in some input and hit run. - -As an alternative, you can download [CHICKEN Scheme][2] and a copy of the solution -file from Github. Assuming CHICKEN Scheme is on your path, you can run the -script from a command line with the following command: - -```console -csi -s reverse-string.scm -``` - -This will run the Scheme file which will print out whatever you enter on the -command line. - -[1]: https://www.jdoodle.com/execute-scheme-online/ -[2]: https://call-cc.org/ diff --git a/docs/projects/reverse-string/swift/index.md b/docs/projects/reverse-string/swift/index.md deleted file mode 100644 index f86681b16c..0000000000 --- a/docs/projects/reverse-string/swift/index.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Marty A/V -- rzuckerm -date: 2018-05-10 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- reverse-string -- swift -title: Reverse String in Swift -title1: Reverse String -title2: in Swift ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -guard CommandLine.argc > 1 else { - exit(0) -} - -let usersString = CommandLine.arguments[1] -let reversedCollection = usersString.reversed() -let reversedString = String(reversedCollection) - -print(reversedString) - -``` - -{% endraw %} - -Reverse String in [Swift](/languages/swift) was written by: - -- Marty A/V - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -As we can see, reversing a string in Swift is pretty short and sweet. At this -point, let's dig into the code a bit. - -### Foundation - -On line 1 of our sample code, we import [Foundation][1]: - -```swift -import Foundation -``` - -`Foundation` is a framework that contains many basic data types. This framework -also bridges between Swift types, such as `String`, and Objective-C types, such -as [NSString][2]. When you import almost any of Apple's Swift frameworks, you are -implicitly importing Foundation along with them. - -### Guard - -The guard statement on line 3 is one of Swift's many syntax features which favor -safety and human readability: - -```swift -guard CommandLine.argc > 1 else { - exit(0) -} -``` - -A [guard statement][3] is a conditional that only fires off if something isn't true. -This is good for highlighting error conditions, and prevents code from becoming -littered with nested if-else statements. It is especially powerful when dealing -with Swift's Optionals. - -### CommandLine - -`Commandline.arguments` is a built-in way to access user input: - -```swift -let usersString = CommandLine.arguments[1] -``` - -Because `CommandLine.arguments` is a `String` array, not an `Optional`, we check its -length, rather than look for `nil`, in order to see if the user has passed us any -input. In Swift, only `Optional`s can contain `nil`. - -Furthermore, `CommandLine.arguments` is always initialized with at least one thing -inside it: the path of the particular file the code is stored in. Therefore, to -access user input, we check if the array contains more than one `String`. Then we -call the `String` at the second index; the first index will always contain the path. - -Finally, `CommandLine` has a special property, `.argc`, which allows us to know how -many `String`s are inside `Commandline.arguments`. We could also call `.length` on -`Commandline.arguments` to access this information. This is the usual way we access -the number of things in an array, but here we use `.argc` to highlight a unique -feature of working with `CommandLine`. - -### String - -When we reverse a `String` in many languages, we may opt for the manual way, by -looping over each character. Instead, we can reverse the string directly through -a builtin call: - -```swift -let reversedCollection = usersString.reversed() -``` - -Swift has an unusual approach to `String`s. Swift stores all characters in `String`s -as Unicode, even if they are within the ASCII character set. Therefore, we don't -need to do anything funky to cover all our edge cases: Swift can innately handle -accented characters, Cyrillic, kanji, and so on. - -While this allows Swift to seamlessly handle emoji and languages that use -non-English characters, it can make working with `String`s a bit more complicated. - -Swift's `String` API has changed frequently from version to version, as Apple -continually tries to balance universal language support with ease of use. In -early versions, Swift `String`s were more like Javascript's `String` implementation, -where `String`s were not quite arrays, but you could still call a specific -character by indexing into it with an integer value. - -As of Swift 4, `String`s are composed of a special kind of character collection, -quite distinct from arrays. Indexing into a `String` is done via special methods -and indexing objects specific to the task. This makes looping over all of the -characters in a `String` a more difficult task than in other languages. - -Thankfully, we do not have to resort to this to reverse a String , we can simply -call the `.reversed()` method (or `.reverse()`, in earlier Swift versions). - -### Reversed() - -The `.reversed()` method does not mutate the original `String`, nor does it return a -new `String`. Instead, it works over the character collection making up our `String`, -and we get back an instance of `ReversedCollection`, an incompatible type. This -forces us to be more precise about what we intend to do with our return values. -Later, we use our `ReversedCollection` to make a new `String` object: - -```swift -let reversedString = String(reversedCollection) -``` - -Fortunately, we can perform a quick cast to get our reversed string. - -### Print - -Finally, on line 11, we come to a nice, straight-forward print statement: - -```swift -print(reversedString) -``` - -Unlike other languages, we don't need to specify the console. The compiler -implicitly knows. Apple also offers a logging system, for more robust results -when debugging. - -[1]: https://developer.apple.com/documentation/foundation -[2]: https://developer.apple.com/documentation/foundation/nsstring -[3]: https://docs.swift.org/swift-book/documentation/the-swift-programming-language/statements/#Guard-Statement - - -## How to Run the Solution - -The most common way for programmers to run Swift code is via [Apple's XCode IDE][4]. -It's free and available on the Mac App Store. You can paste this [code snippet][5] -directly into an XCode file and run it. - -You should use an [online Swift compiler][6] if your machine can't handle XCode, or -you just don't want to download it (it's quite big). This web compiler is -up-to-date with Swift 5 (at the time of this writing). Note that Swift updates yearly, -so many web compilers are out of date and unable to run this code. - -[4]: https://developer.apple.com/xcode/ -[5]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/s/swift/reverse-string.swift -[6]: https://www.jdoodle.com/execute-swift-online/ diff --git a/docs/projects/reverse-string/tcl/index.md b/docs/projects/reverse-string/tcl/index.md deleted file mode 100644 index 2465319277..0000000000 --- a/docs/projects/reverse-string/tcl/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- reverse-string -- tcl -title: Reverse String in Tcl -title1: Reverse -title2: String in Tcl ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 - -if {$argc != 1} { exit } - -set input [lindex $argv 0] -if {$input eq ""} { exit } - -puts [join [lreverse [split $input ""]] ""] - - -``` - -{% endraw %} - -Reverse String in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/ti-basic/index.md b/docs/projects/reverse-string/ti-basic/index.md deleted file mode 100644 index 9ad0a2d95b..0000000000 --- a/docs/projects/reverse-string/ti-basic/index.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-01 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-02-01 -layout: default -tags: -- reverse-string -- ti-basic -title: Reverse String in TI-BASIC -title1: Reverse String -title2: in TI-BASIC ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -""->Str2 -For(N,length(Str1),1,-1) - Str2+sub(Str1,N,1)->Str2 -End -Disp Str2 - -``` - -{% endraw %} - -Reverse String in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/typescript/index.md b/docs/projects/reverse-string/typescript/index.md deleted file mode 100644 index 1eeed9ae10..0000000000 --- a/docs/projects/reverse-string/typescript/index.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -authors: -- Ray -- rzuckerm -date: 2019-10-03 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- reverse-string -- typescript -title: Reverse String in TypeScript -title1: Reverse String -title2: in TypeScript ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -let myString: string = (process.argv.length >= 3) ? process.argv[2] : ""; - -const reverse = (str: string) => str.split("").reverse().join(""); - -console.log(reverse(myString)); - -``` - -{% endraw %} - -Reverse String in [TypeScript](/languages/typescript) was written by: - -- Ray -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/unicat/index.md b/docs/projects/reverse-string/unicat/index.md deleted file mode 100644 index 77a374be74..0000000000 --- a/docs/projects/reverse-string/unicat/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-08-28 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-08-28 -layout: default -tags: -- reverse-string -- unicat -title: Reverse String in Unicat -title1: Reverse String -title2: in Unicat ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Unicat](/languages/unicat) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```unicat -# Find end of input by finding null-termination -0o00 😺😼😹😺🙀🙀 Memory 10 (0o12) through N+11 = input (N characters), newline, null -0o01 😻😹😸🙀🙀😹😺🙀🙀 Memory 0 = 0o12 (10 = '\n') -0o02 😻😹😹🙀🙀😹😺🙀🙀 Memory 1 = 0o12 (10, input pointer) -0o03 😻😹😺🙀🙀😹🙀🙀 Memory 2 = 1 -0o04 😻😹😻🙀🙀😸🙀🙀 Memory 3 = 0 -0o05 😿🙀😸😻🙀🙀😹🙀🙀 Memory 3 += Memory 1 (input pointer) -0o06 😼😾😻🙀🙀 Memory 3 = pointer(Memory 3) (contents of input pointer) -0o07 😽😿😻🙀🙀😹😸🙀🙀 If Memory 3 > 0, jump to 0o11 (0o10 + 1) -0o10 😻😹😹🙀😿😹😺🙀🙀 Jump to 0o13 (0o12 + 1) -0o11 😿🙀😸😹🙀🙀😺🙀🙀 Memory 1 += Memory 2 (1) (increment input pointer) -0o12 😻😹😹🙀😿😻🙀🙀 Jump to 0o04 (0o03 + 1) - -# Null-terminate before input -0o13 😻😹😹😹🙀🙀😸😸🙀🙀 Memory 9 (0o11) = 0 - -# Strip trailing newline (if present) -0o14 😻😹😻🙀🙀😹🙀😿 Memory 3 = -1 -0o15 😿🙀😸😻🙀🙀😹🙀🙀 Memory 3 += Memory 1 (input pointer - 1, previous character) -0o16 😼😾😻🙀🙀 Memory 3 = pointer(Memory 3) (previous character) -0o17 😿🙀😺😻🙀🙀😸🙀🙀 Memory 3 -= Memory 0 (contents of input pointer - '\n') -0o20 😽😿😻🙀🙀😺😼🙀🙀 If Memory 3 > 0, jump to 0o25 (0o24 + 1) (if contents of input pointer > '\n') -0o21 😻😹😼🙀🙀😹🙀😿 Memory 4 = -1 -0o22 😿🙀🙀😻🙀🙀😼🙀🙀 Memory 3 *= Memory 4 -0o23 😽😿😻🙀🙀😺😼🙀🙀 If Memory 3 > 0, jump to 0o25 (0o24 + 1) (if '\n' > contents of input pointer) -0o24 😿🙀😺😹🙀🙀😺🙀🙀 Memory 1 -= Memory 2 (1) (decrement input pointer) - -# Output reversed string starting before newline (if present) until beginning -# null-termination is found, then output a newline -0o25 😿🙀😺😹🙀🙀😺🙀🙀 Memory 1 -= Memory 2 (1) (decrement input pointer) -0o26 😻😹😻🙀🙀😸🙀🙀 Memory 3 = 0 -0o27 😿🙀😸😻🙀🙀😹🙀🙀 Memory 3 += Memory 1 (input pointer) -0o30 😼😾😻🙀🙀 Memory 3 = pointer(Memory 3) (contents of input pointer) -0o31 😽😿😻🙀🙀😻😻🙀🙀 If Memory 3 > 0, jump to 0o34 (0o33 + 1) -0o32 😽😼😸🙀🙀 Output Memory 0 ('\n') -0o33 🙀🙀 Exit -0o34 😽😼😻🙀🙀 Output Memory 3 (contents of input pointer) -0o35 😻😹😹🙀😿😺😼🙀🙀 Jump to 0o25 (0o24 + 1) - -``` - -{% endraw %} - -Reverse String in [Unicat](/languages/unicat) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/v/index.md b/docs/projects/reverse-string/v/index.md deleted file mode 100644 index 274ca718c4..0000000000 --- a/docs/projects/reverse-string/v/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Zia -date: 2024-12-15 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2024-12-15 -layout: default -tags: -- reverse-string -- v -title: Reverse String in V -title1: Reverse -title2: String in V ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [V](/languages/v) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```v -module main - -import os - -fn main() { - if os.args.len == 2 { - println(os.args[1].reverse()) - } -} - -``` - -{% endraw %} - -Reverse String in [V](/languages/v) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/vimscript/index.md b/docs/projects/reverse-string/vimscript/index.md deleted file mode 100644 index 261c6581c3..0000000000 --- a/docs/projects/reverse-string/vimscript/index.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -authors: -- Christoph Böhmwalder -- rzuckerm -date: 2018-08-27 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-12-21 -layout: default -tags: -- reverse-string -- vimscript -title: Reverse String in Vimscript -title1: Reverse String -title2: in Vimscript ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Vimscript](/languages/vimscript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```vimscript -func! Reverse(str) - return join(reverse(split(a:str, '\zs')), '') -endfunc - -func! Main(...) - echo Reverse(a:0 > 0 ? a:1 : '') -endfunc - -``` - -{% endraw %} - -Reverse String in [Vimscript](/languages/vimscript) was written by: - -- Christoph Böhmwalder -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/visual-basic/index.md b/docs/projects/reverse-string/visual-basic/index.md deleted file mode 100644 index 06ea37426e..0000000000 --- a/docs/projects/reverse-string/visual-basic/index.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -authors: -- AaronLenoir -- Andrew Reid -- Jeremy Grifski -- rzuckerm -date: 2018-05-04 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2023-05-16 -layout: default -tags: -- reverse-string -- visual-basic -title: Reverse String in Visual Basic -title1: Reverse String -title2: in Visual Basic ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module ReverseString - Public Sub Main(args() As String) - Dim input = String.Empty - If args IsNot Nothing Then - input = String.Join(" ", args) - End If - - System.Console.WriteLine(ReverseString(input)) - End Sub - - Public Function ReverseString(ByVal input As String) As String - Dim chars() As Char = input.ToCharArray() - Array.Reverse(chars) - Return New String(chars) - End Function -End Module - -``` - -{% endraw %} - -Reverse String in [Visual Basic](/languages/visual-basic) was written by: - -- AaronLenoir -- Andrew Reid -- rzuckerm - -This article was written by: - -- Andrew Reid -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of May 16 2023 12:29:09. The solution was first committed on May 04 2018 23:43:40. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Let's start by looking at the complete algorithm to reverse a string in Visual Basic. - -As we can see, VB.NET is a structured language. In other words, there's a very -strong focus on code blocks and control flow structures. - -Our first code block is the module declaration. In this case, we've declared a -public module called `ReverseString`. If other libraries needed access to this module, -they could simply import it by name. - -### The `Main()` Function - -Next, we have our typical main function declaration. Of course, in VB.NET, we -call them subroutines rather than functions, as indicated by the `Sub` keyword. - -The first thing we do in our `Main` function is create a variable named `input` to store the value to be reversed. - -```vb -Public Sub Main(args() As String) - Dim input = String.Empty -``` - -We then need to populate the `input` variable from the value entered at the command prompt. We can use an array of command line arguments using `args()` as the paramater in `Main()` -As input with spaces will be treated as multiple arguments in the `args()` array we need to build them into the single string `input`. - -```vb -If args IsNot Nothing Then - input = String.Join(" ", args) -End If -``` - -We first check that there are arguments to join, and if there are join them with the `String.Join()` function, which takes an array of `args` and joins them together with a space `" "` between them, thereby recreating what was entered at the command line. - - -Finally, we output to the console with the `System.Console.Writeline` function. - -```vb -System.Console.WriteLine(ReverseString(input)) -``` - -Here we call the `ReverseString()` function with `input` as our argument. We will see below how `ReverseString()` operates and returns to us the reversed string. The reversed string is then passed into the `WriteLine` function and it is output to the console. - -### The `ReverseString()` function - -Let's take a look at how this function reverses a string. - -```vb -Public Function ReverseString(ByVal input As String) As String - Dim chars() As Char = input.ToCharArray() - Array.Reverse(chars) - Return New String(chars) -End Function -``` - -We take in the value to be reversed into a local variable named `input`. -In order to reverse it we need to convert the string variable `input` into a character array named `chars()`. - -```vb -'i.e.: ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!'] -Dim chars() As Char = input.ToCharArray() -``` - -The character array `chars` can be reversed using the the `Array.Reverse()` function - -```vb -'i.e.: ['!', 'd', 'l', 'r', 'o', ',W, ' ', ',', 'o', 'l', 'l', 'e', 'H'] -Array.Reverse(chars) -``` - -Finally, the character array `chars` is converted/combined into a string and returned. - -```vb -Return New String(chars) -``` - -This function executes correctly with any ASCII string. I also executes with an empty string as input. - - -## How to Run the Solution - -With our solution implemented, we should probably give it a run. Perhaps the easiest -way to run the solution is to [copy it][1] into an [online VB.NET compiler][2]. - -Alternatively, we can run the solution using Microsoft's very own [Visual Studio][3]. -Of course, I'm not sure of it's support on platforms beyond Windows. Don't forget -to grab a copy of the [Reverse String in Visual Basic .NET][1] solution. - -[1]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/v/visual-basic/reverse-string.vb -[2]: https://www.onlinegdb.com/online_vb_compiler -[3]: https://visualstudio.microsoft.com/downloads/ diff --git a/docs/projects/reverse-string/wren/index.md b/docs/projects/reverse-string/wren/index.md deleted file mode 100644 index 2140d7ea95..0000000000 --- a/docs/projects/reverse-string/wren/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-21 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2025-01-21 -layout: default -tags: -- reverse-string -- wren -title: Reverse String in Wren -title1: Reverse String -title2: in Wren ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [Wren](/languages/wren) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```wren -import "os" for Process - -var args = Process.arguments - -if (args.count < 1) { - args.add("") -} - -var rev = "" - -for (c in args[0]) { - rev = c + rev -} - -System.print(rev) - -``` - -{% endraw %} - -Reverse String in [Wren](/languages/wren) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/reverse-string/x86-64/index.md b/docs/projects/reverse-string/x86-64/index.md deleted file mode 100644 index ad31431c3c..0000000000 --- a/docs/projects/reverse-string/x86-64/index.md +++ /dev/null @@ -1,217 +0,0 @@ ---- -authors: -- RMarx1456 -date: 2024-11-10 -featured-image: reverse-string-in-every-language.jpg -last-modified: 2024-11-10 -layout: default -tags: -- reverse-string -- x86-64 -title: Reverse String in x86-64 -title1: Reverse String -title2: in x86-64 ---- - - - -Welcome to the [Reverse String](/projects/reverse-string) in [x86-64](/languages/x86-64) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```x86-64 -;I/0 -%DEFINE SYS_WRITE 1 -%DEFINE STDOUT 1 - -;Memory -%DEFINE SYS_MMAP 9 -;PROTS (RDX) -%DEFINE PROT_READ 0x01 -%DEFINE PROT_WRITE 0x02 -;FLAGS (R10) -%DEFINE MAP_PRIVATE 0x02 -%DEFINE MAP_ANONYMOUS 0x20 - -%DEFINE SYS_MUNMAP 11 - - -;Process -%DEFINE SYS_EXIT 60 - -section .data - -section .text - - -global strlen -strlen: -; ---------------------------------------------------------------------------- -; Function: strlen -; Description: -; Finds the length of the string. Will count until it hits a zero byte. Could be vectorized or optimized in another way but will be left this way for simplicity. -; Parameters: -; RDI - (char*) String pointer. -; RSI - () Unused. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (int) String length. -; ---------------------------------------------------------------------------- - - MOV RCX, 0 ;RCX will be our counter. - - .loop: - CMP BYTE [RDI+RCX], 0 ;Compare character to zero - JE .done - INC RCX ;Doesn't disturb any flags - JNZ .loop ;Short jump back to the .loop label - .done: - MOV RAX, RCX - RET - -global reverseString -reverseString: -; ---------------------------------------------------------------------------- -; Function: strlen -; Description: -; Reverses a string and returns the pointer to it. Could be vectorized or optimized another way but will be left this way for simplicity. -; Parameters: -; RDI - (char*) String pointer. -; RSI - (int) String length. -; RDX - () Unused. -; R10 - () Unused. -; R8 - () Unused. -; R9 - () Unused. -; Returns: -; RAX - (char*) Pointer to reversed string. -; ---------------------------------------------------------------------------- - %DEFINE reverseString.STACK_INIT 16 - PUSH RBP - MOV RBP, RSP - SUB RSP, reverseString.STACK_INIT - - MOV [RBP-8], RDI ;Move the string pointer to the stack. - MOV [RBP-16], RSI ;Move the string length to the stack. - - MOV RAX, SYS_MMAP - MOV RDI, 0 ;Let the OS decide which address to use. - ;RSI will hold how many bytes to allocate, but that's already initialized so we won't add it. - MOV RDX, PROT_WRITE | PROT_READ ;We'll allow the memory to be read and written to. - MOV R10, MAP_PRIVATE | MAP_ANONYMOUS ;We won't allow other processes to touch this memory, and it will not be associated with a file. - MOV R8, 0 ;No file descriptor. - MOV R9, 0 ;No offset. - SYSCALL - MOV RBX, RAX ;RBX (base register) will hold the start of our new string for later. - MOV RDI, RAX ;RDI (destination register) will hold our new string pointer. - ;Add string length to RDI and then subrtract by one so we can start at end of address. - ADD RDI, [RBP-16] - DEC RDI - MOV RSI, [RBP-8] ;RSI (source register) will hold the old string address. - MOV RCX, 0 ;RCX (counter register) will hold the loop counter. - .loop: - MOV AL, [RSI+RCX] ;Move char from location RSI+RCX to AL. - MOV [RDI], AL ;Move char from AL to location pointer to at RDI+RCX. - DEC RDI ;Move pointer foward by one byte. - INC RCX ;Move counter forward by one. - CMP RCX, [RBP-16] ;Check if RCX hasn't hit the pointer at RSI yet. - JL .loop - - MOV RAX, RBX ;Move our new string into RAX - ADD RSP, reverseString.STACK_INIT - MOV RSP, RBP - POP RBP - RET - -global _start -_start: - %DEFINE _start.STACK_INIT 16 ;Defining this so we aren't placing a literal every time we need to empty the stack at the end. - ;Setting up stack frame. Prolog. - PUSH RBP - MOV RBP, RSP - ;Allocating space on the stack for variables - SUB RSP, _start.STACK_INIT ;16 bytes allocated - MOV QWORD [RBP-8], 0 ;Length of text, 8 bytes. - MOV QWORD [RBP-16], 0 ;New String PTR, 8 bytes. - ;Jump to sections based on argc - CMP QWORD [RBP+8], 1 - JE noInput - CMP QWORD [RBP+8], 2 - JE input - - noInput: - ;Epilog - ADD RSP, _start.STACK_INIT - MOV RSP, RBP - POP RBP - - ;Exit - MOV RAX, SYS_EXIT - XOR RDI, RDI - SYSCALL - - input: - MOV RDI, [RBP+24] ;MOV arg1 to RDI. - CALL strlen ;Call our string length function. - MOV [RBP-8], RAX ;Move string length result into RSP-8. - - MOV RDI, [RBP+24] - MOV RSI, RAX - CALL reverseString - MOV [RBP-16], RAX ;Moving return pointer into RBP-16. - MOV RSI, RAX ;Moving new string pointer to RSI for SYS_WRITE. - - MOV RAX, SYS_WRITE - MOV RDI, STDOUT - ;RSI already handled earlier. - MOV RDX, [RBP-8] ;Moving string length into RDX. - SYSCALL - ;Deallocating memory. - MOV RAX, SYS_MUNMAP - MOV RDI, [RBP-16] ;Move string pointer into RDI to be unmapped. - MOV RSI, [RBP-8] ;Move amount of memory to be unmapped in bytes. - SYSCALL - - ;Epilog - ADD RSP, _start.STACK_INIT - MOV RSP, RBP - POP RBP - - ;Exit - MOV RAX, SYS_EXIT - XOR RDI, RDI - SYSCALL - - - - -``` - -{% endraw %} - -Reverse String in [x86-64](/languages/x86-64) was written by: - -- RMarx1456 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/algol60/index.md b/docs/projects/roman-numeral/algol60/index.md deleted file mode 100644 index 1b93be502d..0000000000 --- a/docs/projects/roman-numeral/algol60/index.md +++ /dev/null @@ -1,193 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-03 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-04-03 -layout: default -tags: -- algol60 -- roman-numeral -title: Roman Numeral in ALGOL 60 -title1: Roman Numeral -title2: in ALGOL 60 ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please provide a string of roman numerals\n"); - stop - end usage; - - procedure error; - begin - outstring(1, "Error: invalid string of roman numerals\n"); - stop; - end error; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - comment Convert Roman letter to value or 0 if invalid; - integer procedure romanVal(ch); - value ch; - integer ch; - begin - integer val; - - comment - I (73) -> 1 - V (86) -> 5 - X (88) -> 10 - L (76) -> 50 - C (67) -> 100 - D (68) -> 500 - M (77) -> 1000 - else -1; - val := 0; - if ch = 73 then val := 1 - else if ch = 86 then val := 5 - else if ch = 88 then val := 10 - else if ch = 76 then val := 50 - else if ch = 67 then val := 100 - else if ch = 68 then val := 500 - else if ch = 77 then val := 1000; - - romanVal := val - end romanVal; - - comment Convert Roman numeral string to value or -1 if invalid; - integer procedure romanNumeral(s, len); - value len; - integer array s; - integer len; - begin - integer i, val, prevVal, total; - - total := 0; - prevVal := -1; - i := 1; - romanloop: - if i <= len & total >= 0 then - begin - comment Get value of current letter. If not found, indicate invalid and exit; - val := romanVal(s[i]); - if val < 1 then total := -1 - else - begin - comment Add value to total; - total := total + val; - - comment If there is a previous value and value is greater than previous value, - subtract two times previous value from total to compensate for addition of - previous value -- e.g., if previous value was 100 (C) and current value is - 1000 (M), the total currently equals 1100, but we want it to be 900 - (1100 - 2*100). Also, reset the current value so that there is no previous - value; - if prevVal > 0 & val > prevVal then - begin - total := total - 2 * prevVal; - val := -1 - end; - - comment Store current value to previous value; - prevVal := val; - - i := i + 1; - goto romanloop - end - end; - - romanNumeral := total - end romanNumeral; - - integer argc, len, result; - integer array s[1:256]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get string as integer array; - len := inCharArray(s, 256); - - comment Convert Roman numeral string to value and output; - result := romanNumeral(s, len); - - comment Output error if value is negative, else exit with error; - if result < 0 then error; - outinteger(1, result); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Roman Numeral in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/algol68/index.md b/docs/projects/roman-numeral/algol68/index.md deleted file mode 100644 index 27a3c1f2bc..0000000000 --- a/docs/projects/roman-numeral/algol68/index.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-01 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2023-02-01 -layout: default -tags: -- algol68 -- roman-numeral -title: Roman Numeral in ALGOL 68 -title1: Roman Numeral -title2: in ALGOL 68 ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC usage = VOID: printf(($gl$, "Usage: please provide a string of roman numerals")); -PROC error = VOID: printf(($gl$, "Error: invalid string of roman numerals")); - -# Roman numeral table # -MODE ROMAN = STRUCT(CHAR letter, INT value); -[]ROMAN romans = ( - ("M", 1000), - ("D", 500), - ("C", 100), - ("L", 50), - ("X", 10), - ("V", 5), - ("I", 1) -); - -# Get value of Roman letter # -PROC get roman = (CHAR letter) INT: -( - INT value := 0; - FOR k TO UPB romans - WHILE value < 1 - DO - IF (letter OF romans[k]) = letter - THEN - value := value OF romans[k] - FI - OD; - - value -); - -# Convert Roman numeral to a value # -PROC roman number = (STRING s) INT: -( - INT total := 0; - INT prev value := -1; # No previous value # - FOR k TO UPB s - WHILE total >= 0 - DO - # Get value of current letter. If not found, indicate invalid and exit # - INT value := get roman(s[k]); - IF value < 1 - THEN - total := -1 - ELSE - # Add value to total # - total +:= value; - - # If there is a previous value and value is greater than previous value, # - # subtract two times previous value from total to compensate for addition of # - # previous value -- e.g., if previous value was 100 (C) and current value is # - # 1000 (M), the total currently equals 1100, but we want it to be 900 (1100 - 2*100). # - # Also, reset the current value so that there is no previous value # - IF prev value > 0 AND value > prev value - THEN - total -:= 2 * prev value; - value := -1 - FI; - - # Store current value to previous value # - prev value := value - FI - OD; - - total -); - -# If too few arguments, exit # -IF argc < 4 -THEN - usage; - stop -FI; - -# Convert Roman numeral to value # -STRING s := argv(4); -INT value := roman number(s); - -# Display if valid, else show error message # -IF value >= 0 -THEN - printf(($gl$, whole(value, 0))) -ELSE - error -FI - -``` - -{% endraw %} - -Roman Numeral in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/awk/index.md b/docs/projects/roman-numeral/awk/index.md deleted file mode 100644 index 9d4c50c86a..0000000000 --- a/docs/projects/roman-numeral/awk/index.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-22 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2025-04-22 -layout: default -tags: -- awk -- roman-numeral -title: Roman Numeral in AWK -title1: Roman Numeral -title2: in AWK ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a string of roman numerals" - exit(1) -} - -function error() { - print "Error: invalid string of roman numerals" - exit(1) -} - -function init_roman() { - roman["I"] = 1 - roman["V"] = 5 - roman["X"] = 10 - roman["L"] = 50 - roman["C"] = 100 - roman["D"] = 500 - roman["M"] = 1000 -} - -function roman_numeral(s, c, total, prev_value, value) { - total = 0 - prev_value = -1 # No previous value - for (i = 1; total >= 0 && i <= length(s); i++) { - # Get value of current letter. If not found, error - c = substr(s, i, 1) - value = (c in roman) ? roman[c] : 0 - if (value < 1) { - total = -1 - } else { - # Add value to total value - total += value - - # If there is a previous value and value is greater than previous value, - # subtract two times previous value from total to compensate for addition of - # previous value -- e.g., if previous value was 100 (C) and current value is - # 1000 (M), the total currently equals 1100, but we want it to be 900 (1100 - 2*100). - # Also, reset the current value so that there is no previous value - if (prev_value > 0 && value > prev_value) { - total -= 2 * prev_value - value = -1 - } - - # Store current value to previous value - prev_value = value - } - } - - return total -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - init_roman() - result = roman_numeral(ARGV[1]) - if (result >= 0) { - print result - } else { - error() - } -} - -``` - -{% endraw %} - -Roman Numeral in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/beef/index.md b/docs/projects/roman-numeral/beef/index.md deleted file mode 100644 index c2345fe7f7..0000000000 --- a/docs/projects/roman-numeral/beef/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-22 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- roman-numeral -title: Roman Numeral in Beef -title1: Roman Numeral -title2: in Beef ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace RomanNumeral; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a string of roman numerals"); - Environment.Exit(0); - } - - public static void Error() - { - Console.WriteLine("Error: invalid string of roman numerals"); - Environment.Exit(0); - } - - public static Result RomanNumeral(StringView str) - { - int total = 0; - int prevDigit = 0; - for (char8 ch in str) - { - int digit = 0; - switch (ch) - { - case 'I': digit = 1; - case 'V': digit = 5; - case 'X': digit = 10; - case 'L': digit = 50; - case 'C': digit = 100; - case 'D': digit = 500; - case 'M': digit = 1000; - default: return .Err; - } - - total += digit; - - // If there is a previous digit and digit is greater than previous digit, - // subtract two times previous digit from total to compensate for addition of - // previous digit - if (prevDigit > 0 && digit > prevDigit) - { - total -= 2 * prevDigit; - prevDigit = 0; - } - - prevDigit = digit; - } - - return .Ok(total); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - switch (RomanNumeral(args[0])) - { - case .Ok(let result): - Console.WriteLine(result); - case .Err: - Error(); - } - - return 0; - } -} -``` - -{% endraw %} - -Roman Numeral in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/c-plus-plus/index.md b/docs/projects/roman-numeral/c-plus-plus/index.md deleted file mode 100644 index 6ae5a08047..0000000000 --- a/docs/projects/roman-numeral/c-plus-plus/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Sailok Chinta -- Ștefan-Iulian Alecu -date: 2019-10-21 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- roman-numeral -title: Roman Numeral in C++ -title1: Roman Numeral -title2: in C++ ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please provide a string of roman numerals\n"; - std::exit(1); -} - -[[noreturn]] void error() { - std::cerr << "Error: invalid string of roman numerals\n"; - std::exit(1); -} - -constexpr int value(char c) { - switch (c) { - case 'I': - return 1; - case 'V': - return 5; - case 'X': - return 10; - case 'L': - return 50; - case 'C': - return 100; - case 'D': - return 500; - case 'M': - return 1000; - default: - return -1; - } -} - -constexpr bool is_valid(char c) { return value(c) != -1; } - -int main(int argc, char* argv[]) { - if (argc < 2) usage(); - - std::string_view s = argv[1]; - - if (s.empty()) { - std::cout << 0 << '\n'; - return 0; - } - - if (!std::ranges::all_of(s, is_valid)) error(); - - int result = 0; - - for (std::size_t i = 0; i < s.size(); ++i) { - int curr = value(s[i]); - - if (i + 1 < s.size()) { - int next = value(s[i + 1]); - - if (curr < next) { - result += next - curr; - ++i; - continue; - } - } - - result += curr; - } - - std::cout << result << '\n'; -} -``` - -{% endraw %} - -Roman Numeral in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Sailok Chinta -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/c-sharp/index.md b/docs/projects/roman-numeral/c-sharp/index.md deleted file mode 100644 index 5aa832ffc2..0000000000 --- a/docs/projects/roman-numeral/c-sharp/index.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-10-21 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- roman-numeral -title: Roman Numeral in C# -title1: Roman Numeral -title2: in C# ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var input]) - return ExitWith("Usage: please provide a string of roman numerals"); - -if (!TryRomanToInt(input.AsSpan().Trim(), out int value)) - return ExitWith("Error: invalid string of roman numerals"); - -Console.WriteLine(value); -return 0; - -static bool TryRomanToInt(ReadOnlySpan roman, out int result) -{ - result = 0; - if (roman.Length == 0) - return true; - - int prev = 0; - - for (int i = roman.Length - 1; i >= 0; i--) - { - if (!TryGetValue(roman[i], out int current)) - return false; - - if (current < prev) - result -= current; - else - result += current; - - prev = current; - } - - return true; -} - -static bool TryGetValue(char c, out int value) -{ - value = char.ToUpper(c) switch - { - 'I' => 1, - 'V' => 5, - 'X' => 10, - 'L' => 50, - 'C' => 100, - 'D' => 500, - 'M' => 1000, - _ => 0 - }; - - return value != 0; -} - -static int ExitWith(string message) -{ - Console.WriteLine(message); - return 1; -} -``` - -{% endraw %} - -Roman Numeral in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/c/index.md b/docs/projects/roman-numeral/c/index.md deleted file mode 100644 index a8c8b18850..0000000000 --- a/docs/projects/roman-numeral/c/index.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -authors: -- Jeremy Grifski -- LezendarySandwich -- rzuckerm -- shubhragupta-code -- Ștefan-Iulian Alecu -date: 2019-10-20 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- roman-numeral -title: Roman Numeral in C -title1: Roman Numeral -title2: in C ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -int val[150]; - -int main(int argc, char **argv) -{ - if (argv[1] == NULL) - { - printf("Usage: please provide a string of roman numerals"); - return 0; - } - if (strlen(argv[1]) == 0) - { - printf("0"); - return 0; - } - - int len = strlen(argv[1]); - val['I'] = 1; - val['V'] = 5; - val['X'] = 10; - val['L'] = 50; - val['C'] = 100; - val['D'] = 500; - val['M'] = 1000; - long long ans = 0; - - for (int i = 1; i < len; ++i) - { - if (!val[argv[1][i]]) - { - printf("Error: invalid string of roman numerals"); - return 0; - } - if (val[argv[1][i]] > val[argv[1][i - 1]]) - ans -= 2 * val[argv[1][i - 1]]; - ans += val[argv[1][i]]; - } - if (!val[argv[1][0]]) - { - printf("Error: invalid string of roman numerals"); - return 0; - } - printf("%lld", ans + val[argv[1][0]]); -} -``` - -{% endraw %} - -Roman Numeral in [C](/languages/c) was written by: - -- LezendarySandwich -- Ștefan-Iulian Alecu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- shubhragupta-code - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -**Note**: The solution shown above is the current solution in the Sample Programs repository as of Apr 15 2026 00:50:56. The solution was first committed on Oct 20 2019 11:59:04. The documentation was last updated on May 15 2023 15:51:23. As a result, documentation below may be outdated. - -## How to Implement the Solution - -Let's understand this code block by block in the order of execution. - -### Main Function - -```c -#include -#include -#include - -int val[150]; -``` - -In the first three lines, we are including header files using [include directive][1] to utilize some functions defined in header files later in the program. -Here, Standard Input/Output header file(*\*) is called to use **printf()** function and *\* to use **strlen()** function. **[strlen()][2]** returns the length of string and **[printf()][3]** prints formatted string as output. -We are also declaring a variable of length 150. - -Now let's move on the `main` function. - -```c -int main(int argc,char **argv) -{ - ... -} -``` - -In C, we declare a function using general form: - -``` -return_type function_name(parameter){ - ... -} -``` - -So, we are declaring main function with return_type integer and **argc** and **argv** as parameters to access command line arguments. -**argc** and **argv** are variables which `main` function will get when run in command-line. **argc** stores argument count while **argv** stores array of strings that are arguments. This should be kept in mind that all command-line arguments are stored as strings. - -**argv[0]** represents first argument which always is equal to name of our program. If we type the following command in terminal: - -```console -./roman-numeral IV -``` - -Here, ```./roman-numeral``` represents **argv[0]** and ```IV``` represents **argv[1]**. - -### Control Flow - -```c -if(argv[1]==NULL){ - printf("Usage: please provide a string of roman numerals"); - return 0; -} -``` - -First if condition checks if the argument provided is a null string or not. If so, it prints correct usage pattern and returns with exit code of 0. - -```c -if(strlen(argv[1])==0){ - printf("0"); - return 0; -} -``` -Now, if length of the argument provided is 0, then it prints **0** and returns with value 0. - -```c -int len=strlen(argv[1]); -val['I']=1; -val['V']=5; -val['X']=10; -val['L']=50; -val['C']=100; -val['D']=500; -val['M']=1000; -long long ans=0; -``` - -This blocks initialize a integer variable with the length of string provided by the argument. It also initializes the array. Since, in C we directly do not have dictionaries, here we have utilised the power of ASCII values. "I" has an [ASCII][4] value of 73. So, at **val[73] = 1**. Remaining values also get assigned in the similar fashion. Next 'long long' datatype variable **ans** is initialized with value of 0. - -```c -for(int i=1;ival[argv[1][i-1]])ans-=2*val[argv[1][i-1]]; - ans+=val[argv[1][i]]; -} -``` - -Now, in this `for` loop, first `if` conditions check if the each letter in the alphabet is a Roman Numeral. If it is not, it prints Error and exits the main function with exit code 0. Else, it proceeds with the rest of the function. -If a smaller value appears before a larger one, the smaller value is subtracted 2 times from the **ans**. Then, each value is added in the **ans**. - -```c -if(!val[argv[1][0]]){ - printf("Error: invalid string of roman numerals"); - return 0; -} -printf("%lld",ans+val[argv[1][0]]); -``` - -Since in the above `for` loop, we have not considered the value of **argv[1][0]**, we check if it is correct Roman Numeral and prints error message if it is not. -Lastly, we print **ans + val[argv[1][0]]** using the format specifier **%lld** for long long datatype. - -[1]: https://en.wikipedia.org/wiki/Include_directive -[2]: https://man7.org/linux/man-pages/man3/strlen.3.html -[3]: https://man7.org/linux/man-pages/man3/printf.3.html -[4]: https://en.wikipedia.org/wiki/ASCII - - -## How to Run the Solution - -```console -gcc -o roman-numeral roman-numeral.c -./roman-numeral -``` -Another handy option is to compile and run using online C Compiler such as [OnlineGDB][5], [Repl][6] - -[5]: https://www.onlinegdb.com/ -[6]: https://replit.com/languages/c diff --git a/docs/projects/roman-numeral/cobol/index.md b/docs/projects/roman-numeral/cobol/index.md deleted file mode 100644 index a177312e20..0000000000 --- a/docs/projects/roman-numeral/cobol/index.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- roman-numeral -title: Roman Numeral in COBOL -title1: Roman Numeral -title2: in COBOL ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. roman-numeral. - -data division. -working-storage section. -01 arg-count pic 9(4) comp. -01 roman-input pic x(100). -01 input-len pic 9(4) comp. -01 total-decimal pic 9(9) comp value 0. - -01 roman-map-area pic x(35) - value "M1000D0500C0100L0050X0010V0005I0001". - -01 roman-table redefines roman-map-area - occurs 7 times indexed by r-idx. - 05 r-char pic x. - 05 r-val pic 9(4). - -01 i pic 9(4) comp. -01 current-n pic 9(4) comp. -01 next-n pic 9(4) comp. -01 search-char pic x. -01 search-result pic 9(4) comp. -01 display-num pic z(8)9. - -procedure division. -main. - accept arg-count from argument-number - if arg-count = 0 - display "Usage: please provide a string of roman numerals" - stop run - end-if - - accept roman-input from argument-value - if roman-input = spaces - display "0" stop run - end-if - - compute input-len = function length(function trim(roman-input)) - - perform varying i from 1 by 1 until i > input-len - - *> Get current value - move roman-input(i:1) to search-char - perform find-val - move search-result to current-n - - if current-n = 0 - display "Error: invalid string of roman numerals" stop run - end-if - - *> Peek at next value - if i < input-len - move roman-input(i + 1:1) to search-char - perform find-val - move search-result to next-n - else - move 0 to next-n - end-if - - if current-n < next-n - subtract current-n from total-decimal - else - add current-n to total-decimal - end-if - end-perform - - move total-decimal to display-num - display function trim(display-num) - goback. - -find-val. - move 0 to search-result - - perform varying r-idx from 1 by 1 until r-idx > 7 - if r-char(r-idx) = search-char - move r-val(r-idx) to search-result - exit perform - end-if - end-perform. - -``` - -{% endraw %} - -Roman Numeral in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/commodore-basic/index.md b/docs/projects/roman-numeral/commodore-basic/index.md deleted file mode 100644 index f32af000d0..0000000000 --- a/docs/projects/roman-numeral/commodore-basic/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-28 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2023-09-28 -layout: default -tags: -- commodore-basic -- roman-numeral -title: Roman Numeral in Commodore BASIC -title1: Roman Numeral in -title2: Commodore BASIC ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Read input string -10 GOSUB 1000 -20 IF S$ = "" AND C = 255 THEN GOTO 240: REM no input -30 V = 0 -40 PD = 0 -50 K = 1 -60 IF K > LEN(S$) THEN GOTO 220 -70 L$ = MID$(S$, K, 1) -80 K = K + 1 -90 D = 0 -100 IF L$ = "M" THEN D = 1000 -110 IF L$ = "D" THEN D = 500 -120 IF L$ = "C" THEN D = 100 -130 IF L$ = "L" THEN D = 50 -140 IF L$ = "X" THEN D = 10 -150 IF L$ = "V" THEN D = 5 -160 IF L$ = "I" THEN D = 1 -170 IF D = 0 THEN GOTO 260: REM Invalid letter -180 V = V + D -185 REM Subtract if the previous digit valid and smaller -190 IF PD > 0 AND PD < D THEN V = V - 2 * PD: D = 0 -200 PD = D -210 GOTO 60 -220 PRINT MID$(STR$(V), 2) -230 END -240 PRINT "Usage: please provide a string of roman numerals" -250 END -260 PRINT "Error: invalid string of roman numerals" -270 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 13 OR C = 255 THEN RETURN: REM end of value or input -1050 S$ = S$ + A$ -1060 GOTO 1020 - -``` - -{% endraw %} - -Roman Numeral in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/dart/index.md b/docs/projects/roman-numeral/dart/index.md deleted file mode 100644 index 56f47de07f..0000000000 --- a/docs/projects/roman-numeral/dart/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Reilly Howell -date: 2019-10-20 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2019-10-21 -layout: default -tags: -- dart -- roman-numeral -title: Roman Numeral in Dart -title1: Roman Numeral -title2: in Dart ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -void main(List args) { - try{ - Map numerals = numeral_map(); - List values = [0]; - for(int i=0; ivalues[i-1]) ? sum-values[i-1] : sum+values[i-1]; - } - print(sum); - } - on RangeError{ - print("Usage: please provide a string of roman numerals"); - } - on NoSuchMethodError{ - print("Error: invalid string of roman numerals"); - } -} - -Map numeral_map(){ - var numerals = new Map(); - numerals['I'] = 1; - numerals['V'] = 5; - numerals['X'] = 10; - numerals['L'] = 50; - numerals['C'] = 100; - numerals['D'] = 500; - numerals['M'] = 1000; - return numerals; -} -``` - -{% endraw %} - -Roman Numeral in [Dart](/languages/dart) was written by: - -- Reilly Howell - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/euphoria/index.md b/docs/projects/roman-numeral/euphoria/index.md deleted file mode 100644 index 20a4d9ab7a..0000000000 --- a/docs/projects/roman-numeral/euphoria/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-25 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2023-02-25 -layout: default -tags: -- euphoria -- roman-numeral -title: Roman Numeral in Euphoria -title1: Roman Numeral -title2: in Euphoria ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e - -procedure usage() - puts(STDOUT, "Usage: please provide a string of roman numerals\n") - abort(0) -end procedure - -procedure error() - puts(STDOUT, "Error: invalid string of roman numerals\n") - abort(0) -end procedure - --- Roman numeral table -sequence romans = { - {'M', 1000}, - {'D', 500}, - {'C', 100}, - {'L', 50}, - {'X', 10}, - {'V', 5}, - {'I', 1} -} - --- Indices for roman numeral table -enum ROMAN_LETTER, ROMAN_VALUE - --- Get value of Roman letter -function get_roman(integer letter) - for k = 1 to length(romans) - do - if letter = romans[k][ROMAN_LETTER] - then - return romans[k][ROMAN_VALUE] - end if - end for - - return 0 -end function - --- Convert Roman numeral to a value -function roman_number(sequence s) - integer total = 0 - integer prev_value = -1 -- No previous value - for k = 1 to length(s) - do - -- Get value of current letter. If not found, indicate invalid and exit - integer value = get_roman(s[k]) - if value < 1 - then - return -1 - end if - - -- Add value to total - total += value - - -- If there is a previous value and value is greater than previous value, - -- subtract two times previous value from total to compensate for addition of - -- previous value -- e.g., if previous value was 100 (C) and current value is - -- 1000 (M), the total currently equals 1100, but we want it to be 900 (1100 - 2*100). - -- Also, reset the current value so that there is no previous value - if prev_value > 0 and value > prev_value - then - total -= 2 * prev_value - value = -1 - end if - - -- Store current value to previous value - prev_value = value - end for - - return total -end function - --- If too few arguments, exit -sequence argv = command_line() -if length(argv) < 4 -then - usage() -end if - --- Convert Roman numeral to value -sequence s = argv[4] -integer value = roman_number(s) -if value >= 0 -then - printf(STDOUT, "%d\n", {value}) -else - error() -end if - -``` - -{% endraw %} - -Roman Numeral in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/f-sharp/index.md b/docs/projects/roman-numeral/f-sharp/index.md deleted file mode 100644 index 38c9a74ccc..0000000000 --- a/docs/projects/roman-numeral/f-sharp/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- roman-numeral -title: Roman Numeral in F# -title1: Roman Numeral -title2: in F# ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Roman = - - let private value = - function - | 'I' -> Some 1 - | 'V' -> Some 5 - | 'X' -> Some 10 - | 'L' -> Some 50 - | 'C' -> Some 100 - | 'D' -> Some 500 - | 'M' -> Some 1000 - | _ -> None - - let parse (chars: char[]) = - let rec loop i acc = - if i >= chars.Length then acc - else - match value chars[i] with - | None -> acc // unreachable - | Some v -> - if i + 1 < chars.Length then - match value chars[i + 1] with - | Some v2 when v < v2 -> - loop (i + 2) (acc + v2 - v) - | _ -> - loop (i + 1) (acc + v) - else - loop (i + 1) (acc + v) - - loop 0 0 - - -module Helpers = - - let private isRomanChar c = - match c with - | 'I' | 'V' | 'X' | 'L' | 'C' | 'D' | 'M' -> true - | _ -> false - - let parseArgs = function - | [| s |] when s = "" -> Ok [||] - | [| s |] when s |> Seq.forall isRomanChar -> Ok (s.ToCharArray()) - | [| _ |] -> Error "Error: invalid string of roman numerals" - | _ -> Error "Usage: please provide a string of roman numerals" - - let handleResult = - function - | Ok chars -> - Roman.parse chars |> printfn "%d" - 0 - | Error msg -> - printfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Helpers.handleResult -``` - -{% endraw %} - -Roman Numeral in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/go/index.md b/docs/projects/roman-numeral/go/index.md deleted file mode 100644 index ce2815f2e9..0000000000 --- a/docs/projects/roman-numeral/go/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- clarkimusmax -- Parker Johansen -date: 2018-10-25 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2019-04-01 -layout: default -tags: -- go -- roman-numeral -title: Roman Numeral in Go -title1: Roman Numeral -title2: in Go ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import "fmt" -import "os" - -func exitWithError(msg string) { - fmt.Println(msg) - os.Exit(1) -} - -func toRoman(input string) (total int) { - var i = 0 - var temp1 int - var temp2 int - - var numerals = map[string]int{ - "I": 1, - "V": 5, - "X": 10, - "L": 50, - "C": 100, - "D": 500, - "M": 1000, - } - - //While i is within bounds of input - for i < len(input) { - //Get the current value - temp1 = numerals[string(input[i])] - if temp1 == 0 { - exitWithError("Error: invalid string of roman numerals") - } - - //If we still have input left to compare, check if we need to - // subtract from the next value - if len(input) > i+1 { - //Get the next value - temp2 = numerals[string(input[i+1])] - if temp2 == 0 { - exitWithError("Error: invalid string of roman numerals") - } - - //If the current value is >= next, use it's mapped value - if temp1 >= temp2 { - total += temp1 - i++ - //Otherwise, adjust for the subtraction and skip next - } else { - total += temp2 - temp1 - i += 2 - } - //Otherwise, just add the current value to the total - } else { - total += temp1 - i++ - } - } - return -} - -func main() { - //Args or die - if len(os.Args) != 2 { - exitWithError("Usage: please provide a string of roman numerals") - } - - roman := toRoman(os.Args[1]) - fmt.Printf("%d\n", roman) -} - -``` - -{% endraw %} - -Roman Numeral in [Go](/languages/go) was written by: - -- clarkimusmax -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/haskell/index.md b/docs/projects/roman-numeral/haskell/index.md deleted file mode 100644 index fca3d76ee4..0000000000 --- a/docs/projects/roman-numeral/haskell/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-10-21 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2019-04-01 -layout: default -tags: -- haskell -- roman-numeral -title: Roman Numeral in Haskell -title1: Roman Numeral -title2: in Haskell ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import System.Environment -import System.Exit (exitWith, ExitCode(ExitFailure)) - -asDec :: Char -> Int -asDec 'I' = 1 -asDec 'V' = 5 -asDec 'X' = 10 -asDec 'L' = 50 -asDec 'C' = 100 -asDec 'D' = 500 -asDec 'M' = 1000 -asDec _ = -1 - -romanToDecimal :: String -> Maybe Int -romanToDecimal roman = go roman 0 - where go :: String -> Int -> Maybe Int - go [] totals = Just totals - go [a] totals = Just $ totals + (asDec a) - go (a1:a2:as) totals - | (asDec a1) < 1 || (asDec a2) < 1 = Nothing - | (asDec a1) < (asDec a2) = go (a2:as) (totals - (asDec a1)) - | otherwise = go (a2:as) (totals + (asDec a1)) - - -main :: IO () -main = do - args <- getArgs - let roman = head args - if null args then do - putStrLn "Usage: please provide a string of roman numerals" - exitWith $ ExitFailure 1 - else do - let intOut = romanToDecimal roman - case intOut of - Nothing -> do - putStrLn "Error: invalid string of roman numerals" - exitWith $ ExitFailure 1 - Just x -> putStrLn $ show $ x - -``` - -{% endraw %} - -Roman Numeral in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/index.md b/docs/projects/roman-numeral/index.md deleted file mode 100644 index ffafc20a81..0000000000 --- a/docs/projects/roman-numeral/index.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -date: 2018-10-07 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- roman-numeral -title: Roman Numeral -title1: Roman -title2: Numeral ---- - - - -Welcome to the Roman Numeral page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski - -## Description - -Roman numerals are the numbers that were used in ancient Rome, which employed -combinations of letters from the Latin alphabet (I, V, X, L, C, D and M). - -The following table shows the letter to decimal mapping: - -| Letter | Decimal | -| ------ | ------- | -| I | 1 | -| V | 5 | -| X | 10 | -| L | 50 | -| C | 100 | -| D | 500 | -| M | 1000 | - -Stringing together these digits yields a value that is the sum of their -respective mappings. However, there is a catch. Roman numerals must appears in -order of greatest to least. If a smaller value appears before a larger one, -the smaller value is subtracted from the total. - -As a result, a string like `XV` would evaluate to 15 while `XIV` would -evaluate to 14. - -Of course, there are other limitations, but we'll ignore those for simplicity. - - -## Requirements - -Create a file called Roman Numeral Conversion using whatever naming -convention is appropriate for the choice language. - -Using the table above, write a sample program which accepts a Roman numeral on -the command line and outputs its decimal value on standard output. Be careful -to appropriately handle invalid input such as `XT`. More on that in the testing -section. - -_Please_ make sure your program is executable. In other words, the solution -should be able to be called in the appropriate environment with a string -of roman numerals (i.e. `./roman-numeral-conversion XXVI`). - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Roman Numeral. -In order to keep things simple, we split up the testing as follows: - -- Roman Numeral Valid Tests -- Roman Numeral Invalid Tests - -### Roman Numeral Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Empty Input | "" | "0" | -| Single I | "I" | "1" | -| Single V | "V" | "5" | -| Single X | "X" | "10" | -| Single L | "L" | "50" | -| Single C | "C" | "100" | -| Single D | "D" | "500" | -| Single M | "M" | "1000" | -| Addition | "XXV" | "25" | -| Subtraction | "XIV" | "14" | - -### Roman Numeral Invalid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| No Input | | "Usage: please provide a string of roman numerals" | -| Invalid Input | "XT" | "Error: invalid string of roman numerals" | - - -## Articles - -There are 29 articles: - -- [Roman Numeral in ALGOL 60](/projects/roman-numeral/algol60) -- [Roman Numeral in ALGOL 68](/projects/roman-numeral/algol68) -- [Roman Numeral in AWK](/projects/roman-numeral/awk) -- [Roman Numeral in Beef](/projects/roman-numeral/beef) -- [Roman Numeral in C](/projects/roman-numeral/c) -- [Roman Numeral in C#](/projects/roman-numeral/c-sharp) -- [Roman Numeral in C++](/projects/roman-numeral/c-plus-plus) -- [Roman Numeral in COBOL](/projects/roman-numeral/cobol) -- [Roman Numeral in Commodore BASIC](/projects/roman-numeral/commodore-basic) -- [Roman Numeral in Dart](/projects/roman-numeral/dart) -- [Roman Numeral in Euphoria](/projects/roman-numeral/euphoria) -- [Roman Numeral in F#](/projects/roman-numeral/f-sharp) -- [Roman Numeral in Go](/projects/roman-numeral/go) -- [Roman Numeral in Haskell](/projects/roman-numeral/haskell) -- [Roman Numeral in Java](/projects/roman-numeral/java) -- [Roman Numeral in JavaScript](/projects/roman-numeral/javascript) -- [Roman Numeral in Lua](/projects/roman-numeral/lua) -- [Roman Numeral in Mathematica](/projects/roman-numeral/mathematica) -- [Roman Numeral in PHP](/projects/roman-numeral/php) -- [Roman Numeral in Pascal](/projects/roman-numeral/pascal) -- [Roman Numeral in PowerShell](/projects/roman-numeral/powershell) -- [Roman Numeral in Python](/projects/roman-numeral/python) -- [Roman Numeral in Ruby](/projects/roman-numeral/ruby) -- [Roman Numeral in Rust](/projects/roman-numeral/rust) -- [Roman Numeral in Swift](/projects/roman-numeral/swift) -- [Roman Numeral in Tcl](/projects/roman-numeral/tcl) -- [Roman Numeral in TypeScript](/projects/roman-numeral/typescript) -- [Roman Numeral in Visual Basic](/projects/roman-numeral/visual-basic) -- [Roman Numeral in m4](/projects/roman-numeral/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/roman-numeral/java/index.md b/docs/projects/roman-numeral/java/index.md deleted file mode 100644 index b14b7d5b21..0000000000 --- a/docs/projects/roman-numeral/java/index.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- java -- roman-numeral -title: Roman Numeral in Java -title1: Roman Numeral -title2: in Java ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class RomanNumeral { - private static final int[] ROMAN = new int[128]; - - static { - ROMAN['I'] = 1; - ROMAN['V'] = 5; - ROMAN['X'] = 10; - ROMAN['L'] = 50; - ROMAN['C'] = 100; - ROMAN['D'] = 500; - ROMAN['M'] = 1000; - } - - public static void main(String[] args) { - if (args.length == 0 || args[0] == null) { - System.out.println("Usage: please provide a string of roman numerals"); - System.exit(1); - } - - String s = args[0].toUpperCase(); - - int result = romanToInt(s); - if (result == -1) { - System.err.println("Error: invalid string of roman numerals"); - System.exit(1); - } - - System.out.println(result); - } - - private static int romanToInt(String input) { - if (input.isEmpty()) { - return 0; - } - - int total = 0; - int prev = 0; - - for (int i = input.length() - 1; i >= 0; i--) { - char c = input.charAt(i); - - if (c >= 128 || ROMAN[c] == 0) { - return -1; - } - - int cur = ROMAN[c]; - - if (cur < prev) { - total -= cur; - } else { - total += cur; - } - - prev = cur; - } - - return total; - } -} -``` - -{% endraw %} - -Roman Numeral in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/javascript/index.md b/docs/projects/roman-numeral/javascript/index.md deleted file mode 100644 index 9b548513ba..0000000000 --- a/docs/projects/roman-numeral/javascript/index.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -authors: -- Rani Kheir -date: 2019-10-11 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2019-10-12 -layout: default -tags: -- javascript -- roman-numeral -title: Roman Numeral in JavaScript -title1: Roman Numeral -title2: in JavaScript ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -// Roman Numeral Conversion -// jsfiddle link for a quick test drive: https://jsfiddle.net/Rani_Kheir/r8wpLagq/10/ - -let romanNumeralValues = { - "I": 1, - "V": 5, - "X": 10, - "L": 50, - "C": 100, - "D": 500, - "M": 1000 -}; - -function romanNumeralConversion(romanNumeral) { - - // Check for blank input - if (romanNumeral === undefined) { - return "Usage: please provide a string of roman numerals"; - } - - // Check for empty string - if (romanNumeral === "") { - return 0; - } - - // Split the string - let romanNumeralSplit = romanNumeral.split(""); - // Get unique characters - let unique = [... new Set(romanNumeralSplit)]; - - // Check for invalid characters - for (var i = 0; i < unique.length; i++) { - if (romanNumeralValues[unique[i]] === undefined) { - return "Error: invalid string of roman numerals"; - } - } - - // Calculating result (adding/subtracting) - // - // Note: next will be undefined for the last element, it'll - // still work though since 'any number' < undefined will - // be false ... hacky - but works! - // - // Note 2: This does not account for wrongly formatted - // Roman Numerals like IIIIIIIIIX - - let answer = 0; - - for (var i = 0; i < romanNumeralSplit.length; i++) { - var curr = romanNumeralValues[romanNumeralSplit[i]]; - var next = romanNumeralValues[romanNumeralSplit[i+1]]; - if (curr < next) - answer -= curr; - else - answer += curr; - } - - return answer; -} - - -// CLI use needs to have node.js installed -// Run like so: -// node roman-numeral.js I II III XXV XIV "" HI 700 - - -// Process arguments from CLI - -var args = process.argv.slice(2); - -if (args.length < 1) { - console.log(romanNumeralConversion()); -} else { - args.forEach(arg => console.log(romanNumeralConversion(arg))); -} - - -``` - -{% endraw %} - -Roman Numeral in [JavaScript](/languages/javascript) was written by: - -- Rani Kheir - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/lua/index.md b/docs/projects/roman-numeral/lua/index.md deleted file mode 100644 index 01dfc9c5bd..0000000000 --- a/docs/projects/roman-numeral/lua/index.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -authors: -- Jeremy Grifski -- jketterer -date: 2019-10-28 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- lua -- roman-numeral -title: Roman Numeral in Lua -title1: Roman Numeral -title2: in Lua ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -#!/bin/lua - --- Key value pairs for roman numerals -conversion_table = { - ['I']=1, - ['V']=5, - ['X']=10, - ['L']=50, - ['C']=100, - ['D']=500, - ['M']=1000 -} - --- Check if character is valid (in conversion table) -function validateCharacter(char) - for key,value in pairs(conversion_table) do - if char == key then - return true - end - end - return false -end - --- Convert roman numeral to decimal -function convertToDecimal(roman) - -- If numeral is a single character, simply return value - if #roman == 1 then - return conversion_table[roman] - end - - sum = 0 - - -- Iterate through entire number - for i = 1, #roman do - current = conversion_table[string.sub(roman, i, i)] - next = conversion_table[string.sub(roman, i+1, i+1)] - - -- Subtract values if first character is smaller, then skip next character - if (next ~= nil) and (current < next) then - sum = sum + (next - current) - break - -- Add character value to sum - else - sum = sum + current - end - end - - return sum -end - --- Get input from command line -input = arg[1] - --- Exit if no input given -if arg[1] == nil then - print('Usage: please provide a string of roman numerals') - return -end - --- Check each character for validity, exit if any are invalid -for i = 1, #input do - if validateCharacter(string.sub(input, i, i)) == false then - print('Error: invalid string of roman numerals') - return - end -end - --- Print converted value -print(convertToDecimal(input)) - -``` - -{% endraw %} - -Roman Numeral in [Lua](/languages/lua) was written by: - -- Jeremy Grifski -- jketterer - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/m4/index.md b/docs/projects/roman-numeral/m4/index.md deleted file mode 100644 index 24dfcfb73a..0000000000 --- a/docs/projects/roman-numeral/m4/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-16 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2025-08-16 -layout: default -tags: -- m4 -- roman-numeral -title: Roman Numeral in m4 -title1: Roman Numeral -title2: in m4 ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a string of roman numerals -m4exit(`1')') - -define(`show_error', -`Error: invalid string of roman numerals -m4exit(`1')') - -dnl is_valid_roman(str) -define(`is_valid_roman', `eval(regexp(`$1', `[^IVXLCDM]') < 0)') - -dnl roman_value(letter) -define(`roman_value', -`ifelse(`$1', `I', `1', - `$1', `V', `5', - `$1', `X', `10', - `$1', `L', `50', - `$1', `C', `100', - `$1', `D', `500', `1000')'dnl -) - -dnl roman_numeral(str) -define(`roman_numeral', -`ifelse(is_valid_roman(`$1'), 0, `-1', `_roman_numeral(`$1', `0', `-1')')'dnl -) - -dnl _roman_numeral(str, total, prev_value) -dnl for each character (ch) in str: -dnl value = roman_letter(ch) -dnl total = total + value -dnl if prev_value > 0 and value > prev_value: -dnl total = total - 2 * prev_value -dnl value = -1 -dnl prev_value = value -dnl Return total -define(`_roman_numeral', -`ifelse(len(`$1'), 0, `$2', -`define(`value', roman_value(substr(`$1', 0, 1)))dnl -ifelse(eval($3 > 0 && value > $3), 1, - `_roman_numeral(substr(`$1', 1), eval($2 + value - 2 * $3), `-1')', - `_roman_numeral(substr(`$1', 1), eval($2 + value), value)'dnl -)'dnl -)'dnl -) -divert(0)dnl -ifelse(eval(ARGC < 1), 1, `show_usage()')dnl -define(`result', roman_numeral(ARGV1))dnl -ifelse(eval(result < 0), 1, `show_error()', `result') - -``` - -{% endraw %} - -Roman Numeral in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/mathematica/index.md b/docs/projects/roman-numeral/mathematica/index.md deleted file mode 100644 index 78b5b35463..0000000000 --- a/docs/projects/roman-numeral/mathematica/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-16 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2023-01-16 -layout: default -tags: -- mathematica -- roman-numeral -title: Roman Numeral in Mathematica -title1: Roman Numeral -title2: in Mathematica ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual Roman numeral converter operating on Mathematica strings: *) - -romanNumerals = s \[Function] Fold[ - (* conversion operating on pairs of subsequent values*) - Function[{a, ii}, If[GreaterEqual @@ ii, a + First[ii], a - First[ii]]], - 0, - Partition[(* pairs of subsequent values*) - Append[ (* append zero so the last value still forms a pair *) - ReplaceAll[Characters[s], (* convert to list of decimal values *) - {"I" -> 1, "V" -> 5, "X" -> 10, "L" -> 50, "C" -> 100, "D" -> 500, "M" -> 1000}], - 0], - 2, 1]]; - -(* The outer function provides the 'user interface': *) - -romanNumeralsMain = s \[Function] - Catch[ - romanNumerals[ - If[ - StringQ[s] \[And] StringMatchQ[s, ("I" | "V" | "X" | "L" | "C" | "D" | "M") ...], - s, - Throw["Error: invalid string of roman numerals"]]]]; - - -(* Valid Tests *) - -Print /@ romanNumeralsMain /@ { - "", "I", "V", "X", "L", "C", "D", "M", "XXV", "XIV" - }; - - -(* Invalid Tests *) - -romanNumeralsMain["XT"] - -``` - -{% endraw %} - -Roman Numeral in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/pascal/index.md b/docs/projects/roman-numeral/pascal/index.md deleted file mode 100644 index 4fd7eae122..0000000000 --- a/docs/projects/roman-numeral/pascal/index.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-21 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2025-07-21 -layout: default -tags: -- pascal -- roman-numeral -title: Roman Numeral in Pascal -title1: Roman Numeral -title2: in Pascal ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program RomanNumeral; - -{$mode objfpc}{$H+} - -uses - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a string of roman numerals'); - Halt(1); -end; - -function RomanToInt(const S: string): int64; -const - RomanChars: array[0..6] of char = ('I', 'V', 'X', 'L', 'C', 'D', 'M'); - RomanValues: array[0..6] of integer = (1, 5, 10, 50, 100, 500, 1000); -var - Value: array[char] of integer; - i, len: integer; - ch: char; - Answer, PreviousValue, CurrentValue: int64; -begin - FillChar(Value, SizeOf(Value), 0); - - for i := Low(RomanChars) to High(RomanChars) do - Value[RomanChars[i]] := RomanValues[i]; - - Answer := 0; - PreviousValue := 0; - len := Length(S); - - if len = 0 then - Exit(0); - - for i := len downto 1 do - begin - ch := S[i]; - CurrentValue := Value[ch]; - if CurrentValue = 0 then - raise Exception.Create('Error: invalid string of roman numerals'); - - if CurrentValue < PreviousValue then - Dec(Answer, CurrentValue) - else - begin - Inc(Answer, CurrentValue); - PreviousValue := CurrentValue; - end; - end; - - Result := Answer; -end; - -var - Input: string; - Number: int64; -begin - if ParamCount <> 1 then - ShowUsage; - - Input := AnsiUpperCase(Trim(ParamStr(1))); - - try - Number := RomanToInt(Input); - Writeln(Number); - except - on E: Exception do - begin - Writeln(E.Message); - Halt(1); - end; - end; -end. - -``` - -{% endraw %} - -Roman Numeral in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/php/index.md b/docs/projects/roman-numeral/php/index.md deleted file mode 100644 index ae728c81e8..0000000000 --- a/docs/projects/roman-numeral/php/index.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Juan D Frias -- Parker Johansen -date: 2019-10-14 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- php -- roman-numeral -title: Roman Numeral in PHP -title1: Roman Numeral -title2: in PHP ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - 1, "V" => 5, "X" => 10, - "L" => 50, "C" => 100, "D" => 500, "M" => 1000); - - $total = 0; - $previous = 0; - - // parse from end to start of string - for ($i = strlen($romans) - 1; $i >= 0; --$i) { - - // check if the character is a roman numeral - $numeral = strtoupper($romans[$i]); - if (!array_key_exists($numeral, $roman_values)) { - throw new Exception("invalid string of roman numerals"); - } - - // convert to decimal and add/subtract from total. - $value = $roman_values[$numeral]; - if ($value >= $previous) { - $total += $value; - - } else { - $total -= $value; - } - - // keep track of last value - $previous = $value; - } - - return $total; -} - -try { - - // Check argument count - if ($argc < 2) { - echo "Usage: please provide a string of roman numerals\n"; - exit(1); - } - - // Convert the string - echo roman_to_decimal($argv[1]), "\n"; - exit(0); - -} catch (Exception $e) { - echo "Error: ", $e->getMessage(), "\n"; - exit(1); -} - -``` - -{% endraw %} - -Roman Numeral in [PHP](/languages/php) was written by: - -- Jeremy Grifski -- Juan D Frias -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/powershell/index.md b/docs/projects/roman-numeral/powershell/index.md deleted file mode 100644 index 188a8c39ae..0000000000 --- a/docs/projects/roman-numeral/powershell/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-04 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2025-07-04 -layout: default -tags: -- powershell -- roman-numeral -title: Roman Numeral in PowerShell -title1: Roman Numeral -title2: in PowerShell ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -$Romans = @{ - M = 1000 - D = 500 - C = 100 - L = 50 - X = 10 - V = 5 - I = 1 -} - -function Show-Usage() { - Write-Host 'Usage: please provide a string of roman numerals' - Exit 1 -} - -function Show-Error() { - Write-Host 'Error: invalid string of roman numerals' - Exit 1 -} - -function RomanNumeral([string]$Str) { - $total = 0 - $prevValue = 0 - foreach ($ch in $Str.ToCharArray()) { - $value = $Romans[[string]$ch] - if (-not $value) { - $total = -1 - break - } - - $total += $value - if ($prevValue -gt 0 -and $value -gt $prevValue) { - $total -= 2 * $prevValue - $prevValue = 0 - } else { - $prevValue = $value - } - } - - $total -} - -if ($args.Length -lt 1) { - Show-Usage -} - -$result = RomanNumeral $args[0] -if ($result -lt 0) { - Show-Error -} - -Write-Output $result - -``` - -{% endraw %} - -Roman Numeral in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/python/index.md b/docs/projects/roman-numeral/python/index.md deleted file mode 100644 index 4efc35f2f0..0000000000 --- a/docs/projects/roman-numeral/python/index.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -- prateeksharma21 -- rzuckerm -- Vikram Rayavarapu -date: 2018-10-07 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- python -- roman-numeral -title: Roman Numeral in Python -title1: Roman Numeral -title2: in Python ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -# This function returns value of each Roman symbol -def value(r): - return { - 'I': 1, - 'V': 5, - 'X': 10, - 'L': 50, - 'C': 100, - 'D': 500, - 'M': 1000 - }[r] - - -def roman_to_decimal(string): - res = 0 - i = 0 - - while i < len(string): - - # Getting value of symbol s[i] - s1 = value(string[i]) - - if i+1 < len(string): - - # Getting value of symbol s[i+1] - s2 = value(string[i + 1]) - - # Comparing both values - if s1 >= s2: - - # Value of current symbol is greater - # or equal to the next symbol - res += s1 - i += 1 - else: - - # Value of current symbol is less than - # to the next symbol - res = res + s2 - s1 - i += 2 - else: - res += s1 - i += 1 - - return res - - -def exit_with_error(msg): - print(msg) - sys.exit(1) - - -def main(args): - if len(args) < 1: - exit_with_error('Usage: please provide a string of roman numerals') - - try: - roman_numeral = sys.argv[1] - print(roman_to_decimal(roman_numeral)) - except KeyError: - exit_with_error('Error: invalid string of roman numerals') - - -if __name__ == '__main__': - main(sys.argv[1:]) - -``` - -{% endraw %} - -Roman Numeral in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Parker Johansen -- prateeksharma21 -- Vikram Rayavarapu - -This article was written by: - -- Jeremy Grifski -- rzuckerm -- Vikram Rayavarapu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -### The Main Function - -Breaking down this solution bottom up, - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -This bit of code checks to see if this is the `main` module run. If it is then it calls the `main` -function and passes user input to it. In this case the user input would be a string like `"XV"` (to convert from roman numeral to decimal number). - -```python -def main(args): - if len(args) < 1: - exit_with_error('Usage: please provide a string of roman numerals') - - try: - roman_numeral = sys.argv[1] - print(roman_to_decimal(roman_numeral)) - except KeyError: - exit_with_error('Error: invalid string of roman numerals') -``` - -This is the `main` function of this file. It parses the input, then calls our roman to decimal function -(and it also prints the results). It also deals with any errors raised. - -### Throw Errors - -```python -def exit_with_error(msg): - print(msg) - sys.exit(1) -``` - -This function prints a message and then exits the script with an error, `sys.exit(1)`. -If any non-zero value is returned then the program didn't complete properly. -This function is called if the user input isn't correct. - -### Roman Numeral to Decimal number in Python - -```python -def roman_to_decimal(string): - res = 0 - i = 0 - - while i < len(string): - - # Getting value of symbol s[i] - s1 = value(string[i]) - - if i+1 < len(string): - - # Getting value of symbol s[i+1] - s2 = value(string[i + 1]) - - # Comparing both values - if s1 >= s2: - - # Value of current symbol is greater - # or equal to the next symbol - res += s1 - i += 1 - else: - - # Value of current symbol is less than - # to the next symbol - res = res + s2 - s1 - i += 2 - else: - res += s1 - i += 1 - - return res -``` - -Finally we're at the brain of the entire program. This function takes an roman numeral as string -and returns in form of Decimal number (Integer type). This function `roman_to_decimal` call another function called `value`. That function can map the each digit of roman numeral to decimal equivalent: - -```python -# This function returns value of each Roman symbol -def value(r): - return { - 'I': 1, - 'V': 5, - 'X': 10, - 'L': 50, - 'C': 100, - 'D': 500, - 'M': 1000 - }[r] -``` - -For example, if `XV` is the input: - -* First take `res` as zero (`res = 0`) and `i` (useful for accesing characters of input string) as zero (`i = 0`) - -* While `i` less than length of input in roman numeral we keep on iterating loop. - -* We store respective value of first character of roman numeral (with `value` function) in `s1`. - -* Then we check that `i+1` is less than that of length of string or not. We use this because we need to get value of next character of roman numeral into `s2`. If `i+1` is greater than length of string then we take the `res` as `res + s1` (`res += s1`) and increment `i` by 1 and rerurns the result. - -* If the value of `s1` is greater than or equal to `s2`, then we update res as `res + s1` (`res += s1`) and increment `i` by 1. - -* else we update the value of `res` equal to `res + s2 - s1` (`res = res + s2 - s1`) and increment `i` by 2 (`i += 2`). - -* Finally we return the result in variable `res`. - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Roman Numeral in Python][1]. -After that, we should make sure we have the [latest Python interpreter][2]. -From there, we can run the following command in the terminal: - -`python roman_numeral.py "XIV"` - -Alternatively, we can copy the solution into an [online Python interpreter][3] and hit run then you need to modify `sys.argv[1]` to your inputs. - -[1]: https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/roman_numeral.py -[2]: https://www.python.org/downloads/ -[3]: https://www.online-python.com/ diff --git a/docs/projects/roman-numeral/ruby/index.md b/docs/projects/roman-numeral/ruby/index.md deleted file mode 100644 index 19e6f5b6fa..0000000000 --- a/docs/projects/roman-numeral/ruby/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- Allan Klaus -- Ștefan-Iulian Alecu -date: 2020-10-06 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- roman-numeral -- ruby -title: Roman Numeral in Ruby -title1: Roman Numeral -title2: in Ruby ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -ROMAN = { - "I" => 1, "V" => 5, "X" => 10, "L" => 50, - "C" => 100, "D" => 500, "M" => 1000 -}.freeze - -USAGE = "Usage: please provide a string of roman numerals" -ERROR = "Error: invalid string of roman numerals" - -def valid_roman?(s) - return false unless s.match?(/\A[IVXLCDM]+\z/) - - # no more than 3 repeats - return false if s.match?(/(.)\1{3,}/) - - # invalid repeatables - %w[V L D].each { |ch| return false if s.include?(ch * 2) } - - true -end - -def roman_to_int(s) - return USAGE if s.nil? - - s = s.upcase - return 0 if s.empty? - return ERROR unless valid_roman?(s) - - total = 0 - - s.chars.each_cons(2) do |a, b| - total += (ROMAN[a] < ROMAN[b]) ? -ROMAN[a] : ROMAN[a] - end - - total + ROMAN[s[-1]] -end - -puts roman_to_int(ARGV.first) - -``` - -{% endraw %} - -Roman Numeral in [Ruby](/languages/ruby) was written by: - -- Allan Klaus -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/rust/index.md b/docs/projects/roman-numeral/rust/index.md deleted file mode 100644 index 59795d5fc0..0000000000 --- a/docs/projects/roman-numeral/rust/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Noah Nichols -- rzuckerm -date: 2018-10-12 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2023-04-04 -layout: default -tags: -- roman-numeral -- rust -title: Roman Numeral in Rust -title1: Roman Numeral -title2: in Rust ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env; - -fn main() { - let args: Vec = env::args().collect(); - - if args.len() < 2 { - println!("Usage: please provide a string of roman numerals"); - } else { - let value: i64 = convert_roman_numeral(&args[1]); - if value < 0 { - println!("Error: invalid string of roman numerals"); - } else { - println!("{value}"); - } - } -} - -fn convert_char(c: char) -> i64 { - if c == 'I' { - return 1; - } else if c == 'V' { - return 5; - } else if c == 'X' { - return 10; - } else if c == 'L' { - return 50; - } else if c == 'C' { - return 100; - } else if c == 'D' { - return 500; - } else if c == 'M' { - return 1000; - } else { - return -1; - } -} - -fn convert_roman_numeral(s: &String) -> i64 { - let mut number: i64 = 0; - let mut prev_value: i64 = 0; - for c in s.as_bytes() { - let value = convert_char(*c as char); - if value < 0 { - number = value; - break; - } - number += value; - if prev_value > 0 && value > prev_value { - number -= 2*prev_value; - prev_value = 0; - } else { - prev_value = value; - } - } - - number -} - -``` - -{% endraw %} - -Roman Numeral in [Rust](/languages/rust) was written by: - -- Noah Nichols -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/swift/index.md b/docs/projects/roman-numeral/swift/index.md deleted file mode 100644 index 63b0786547..0000000000 --- a/docs/projects/roman-numeral/swift/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- roman-numeral -- swift -title: Roman Numeral in Swift -title1: Roman Numeral -title2: in Swift ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let romanValues: [Character: Int] = [ - "I": 1, - "V": 5, - "X": 10, - "L": 50, - "C": 100, - "D": 500, - "M": 1000, -] - -let usage = "Usage: please provide a string of roman numerals" -let error = "Error: invalid string of roman numerals" - -func romanToInt(_ s: String) -> Int? { - var total = 0 - var previous = 0 - - for char in s.uppercased().reversed() { - guard let value = romanValues[char] else { return nil } - - if value < previous { - total -= value - } else { - total += value - previous = value - } - } - - return total -} - -guard let input = CommandLine.arguments.dropFirst().first else { - print(usage) - exit(1) -} - -guard let result = romanToInt(input) else { - print(error) - exit(1) -} - -print(result) - -``` - -{% endraw %} - -Roman Numeral in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/tcl/index.md b/docs/projects/roman-numeral/tcl/index.md deleted file mode 100644 index c04873a028..0000000000 --- a/docs/projects/roman-numeral/tcl/index.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- roman-numeral -- tcl -title: Roman Numeral in Tcl -title1: Roman Numeral -title2: in Tcl ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 -package require math::roman - -proc usage {msg} { - puts $msg - exit 1 -} - -if {$argc != 1} { usage "Usage: please provide a string of roman numerals" } - -set input [string trim [lindex $argv 0]] - -if {$input eq ""} { - puts 0 - exit 0 -} - -if {[catch {math::roman::tointeger $input} err]} { - usage "Error: invalid string of roman numerals" -} else { - puts [math::roman::tointeger $input] -} - -``` - -{% endraw %} - -Roman Numeral in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/typescript/index.md b/docs/projects/roman-numeral/typescript/index.md deleted file mode 100644 index 01ba627cfe..0000000000 --- a/docs/projects/roman-numeral/typescript/index.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -authors: -- Antonino Bertulla -date: 2023-10-04 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2023-10-04 -layout: default -tags: -- roman-numeral -- typescript -title: Roman Numeral in TypeScript -title1: Roman Numeral -title2: in TypeScript ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -// Roman Numeral Conversion - -const romanNumeralValues = { - "I": 1, - "V": 5, - "X": 10, - "L": 50, - "C": 100, - "D": 500, - "M": 1000 -}; - -function romanNumeralConversion(str?: string) { - - // Check for blank input - if (str === undefined) { - return "Usage: please provide a string of roman numerals"; - } - - // Check for empty string - if (str === "") { - return 0; - } - - // Get valid characters - const validValues = Object.keys(romanNumeralValues) - - // Check for invalid characters - for (let i = 0; i < str.length; i++) { - const char = str.charAt(i) - if (char === undefined || validValues.indexOf(char) === -1) { - return "Error: invalid string of roman numerals"; - } - } - - // Calculating result (adding/subtracting) - // - // Note: next will be undefined for the last element, it'll - // still work though since 'any number' < undefined will - // be false ... hacky - but works! - // - // Note 2: This does not account for wrongly formatted - // Roman Numerals like IIIIIIIIIX - - let answer = 0; - for (let i = 0; i < str.length; i++) { - const curr = romanNumeralValues[str.charAt(i)]; - const next = romanNumeralValues[str.charAt(i+1)]; - if (curr < next) { - answer -= curr; - } else { - answer += curr; - } - } - - return answer; -} - - -// CLI use needs to have node.js installed -// Run like so: -// node roman-numeral.js IIIIIIXXVXIV - - -// Process arguments from CLI -const args = process.argv.slice(2); - -if (args.length < 1) { - console.error("Usage: please provide a string of roman numerals"); -} else { - console.info(romanNumeralConversion(args[0])) -} - - -``` - -{% endraw %} - -Roman Numeral in [TypeScript](/languages/typescript) was written by: - -- Antonino Bertulla - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/roman-numeral/visual-basic/index.md b/docs/projects/roman-numeral/visual-basic/index.md deleted file mode 100644 index e72aa530b4..0000000000 --- a/docs/projects/roman-numeral/visual-basic/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: roman-numeral-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- roman-numeral -- visual-basic -title: Roman Numeral in Visual Basic -title1: Roman Numeral -title2: in Visual Basic ---- - - - -Welcome to the [Roman Numeral](/projects/roman-numeral) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System -Imports System.Collections.Generic -Imports System.Linq - -Module RomanNumeral - - Private Function GetValue(c As Char) As Integer - Select Case c - Case "M"c : Return 1000 - Case "D"c : Return 500 - Case "C"c : Return 100 - Case "L"c : Return 50 - Case "X"c : Return 10 - Case "V"c : Return 5 - Case "I"c : Return 1 - Case Else - Throw New ArgumentException("Invalid Roman numeral character") - End Select - End Function - - Private Function RomanToDecimal(roman As String) As Integer - Dim total As Integer = 0 - Dim lastValue As Integer = 0 - - For i As Integer = roman.Length - 1 To 0 Step -1 - Dim currentValue As Integer = GetValue(roman(i)) - - If currentValue < lastValue Then - total -= currentValue - Else - total += currentValue - End If - - lastValue = currentValue - Next - - Return total - End Function - - Sub Main(args As String()) - If args.Length = 0 Then - Console.WriteLine("Usage: please provide a string of roman numerals") - Return - End If - - If args(0) = "" Then - Console.WriteLine(0) - Return - End If - - Try - Console.WriteLine(RomanToDecimal(args(0).ToUpperInvariant())) - Catch ex As ArgumentException - Console.WriteLine("Error: invalid string of roman numerals") - End Try - End Sub - -End Module -``` - -{% endraw %} - -Roman Numeral in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/algol60/index.md b/docs/projects/rot13/algol60/index.md deleted file mode 100644 index 011f998a13..0000000000 --- a/docs/projects/rot13/algol60/index.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-03 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-04-03 -layout: default -tags: -- algol60 -- rot13 -title: Rot13 in ALGOL 60 -title1: Rot13 in -title2: ALGOL 60 ---- - - - -Welcome to the [Rot13](/projects/rot13) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please provide a string to encrypt\n"); - stop - end usage; - - integer procedure inAsciiChar; - begin - integer ch; - - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - inchar( - 0, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ); - if ch >= 129 then ch := 0; - inAsciiChar := ch - end inAsciiChar; - - integer procedure inCharArray(s, maxLen); - value maxLen; - integer array s; - integer maxLen; - begin - integer len, ch; - - len := 0; - inloop: - ch := inAsciiChar; - if ch != 0 & len < maxLen then - begin - len := len + 1; - s[len] := ch; - goto inloop - end; - - inCharArray := len - end inCharArray; - - procedure outAsciiChar(ch); - value ch; - integer ch; - begin - comment For some reason '%' needs to be represented as '\x25'. - Also, extra single quote needed to close backtick in string; - outchar( - 1, - "\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f" - "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" - " !\"#$\x25&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNO" - "PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'", - ch - ) - end outAsciiChar; - - procedure outCharArray(s, len); - value len; - integer array s; - integer len; - begin - integer i; - for i := 1 step 1 until len do outAsciiChar(s[i]) - end outCharArray; - - procedure rot13(s, len); - value len; - integer array s; - integer len; - begin - integer i, ch; - - for i := 1 step 1 until len do - begin - comment - A (65) ... M (77) -> N (78) ... Z (90) - a (97) ... m (109) -> n (110) ... z (122) - N (78) ... Z (90) -> A (65) ... M (77) - n (110) ... z (122) -> a (97) ... m (109); - ch := s[i]; - if (ch >= 65 & ch <= 77) | (ch >= 97 & ch <= 109) then - s[i] := s[i] + 13 - else if (ch >= 78 & ch <= 90) | (ch >= 110 & ch <= 122) then - s[i] := s[i] - 13 - end - end capitialize; - - integer argc, len; - integer array s[1:256]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get string as integer array. Exit if empty; - len := inCharArray(s, 256); - if len < 1 then usage; - - comment Encrypt string with Rot13 and output string as integer array; - rot13(s, len); - outCharArray(s, len); - outstring(1, "\n") -end - -``` - -{% endraw %} - -Rot13 in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/algol68/index.md b/docs/projects/rot13/algol68/index.md deleted file mode 100644 index e3989455dd..0000000000 --- a/docs/projects/rot13/algol68/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-24 -featured-image: rot13-in-every-language.jpg -last-modified: 2023-02-01 -layout: default -tags: -- algol68 -- rot13 -title: Rot13 in ALGOL 68 -title1: Rot13 in -title2: ALGOL 68 ---- - - - -Welcome to the [Rot13](/projects/rot13) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -PROC usage = VOID: printf(($gl$, "Usage: please provide a string to encrypt")); - -PROC rot13 = (STRING s) STRING: -( - INT code; - STRING t; - FOR n TO UPB s - DO - # If A-M or a-m, convert to N-Z or n-z by adding 13 to ASCII code # - # Else, convert to A-M or a-m by subtracting 13 from ASCII code # - code := ABS s[n]; - IF isalpha(s[n]) - THEN - code +:= (tolower(s[n]) <= "m" | 13 | -13) - FI; - - t +:= REPR code - OD; - - t -); - -# Get 1st command-line argument. Exit if empty # -STRING s := argv(4); -IF UPB s = 0 -THEN - usage; - stop -FI; - -# Encrypt string with ROT13 and display # -s := rot13(s); -printf(($gl$, s)) - -``` - -{% endraw %} - -Rot13 in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/awk/index.md b/docs/projects/rot13/awk/index.md deleted file mode 100644 index e22b41f312..0000000000 --- a/docs/projects/rot13/awk/index.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-07 -featured-image: rot13-in-every-language.jpg -last-modified: 2025-04-16 -layout: default -tags: -- awk -- rot13 -title: Rot13 in AWK -title1: Rot13 -title2: in AWK ---- - - - -Welcome to the [Rot13](/projects/rot13) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a string to encrypt" - exit(1) -} - -function rot13(s, result, i, c, idx) { - result = "" - for (i = 1; i <= length(s); i++) { - c = substr(s, i, 1) - idx = index(input_table, c) - if (idx > 0) { - c = substr(output_table, idx, 1) - } - - result = result c - } - - return result -} - -BEGIN { - if (ARGC < 2 || !ARGV[1]) { - usage() - } - - input_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - output_table = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" - print rot13(ARGV[1]) -} - -``` - -{% endraw %} - -Rot13 in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/beef/index.md b/docs/projects/rot13/beef/index.md deleted file mode 100644 index 1f58a29ec1..0000000000 --- a/docs/projects/rot13/beef/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-01-22 -featured-image: rot13-in-every-language.jpg -last-modified: 2024-01-22 -layout: default -tags: -- beef -- rot13 -title: Rot13 in Beef -title1: Rot13 -title2: in Beef ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; - -namespace Rot13; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please provide a string to encrypt"); - Environment.Exit(0); - } - - public static void Rot13(StringView str, ref String result) - { - result.Clear(); - result.Reserve(str.Length); - for (char8 ch in str) - { - char8 chLower = ch.ToLower; - if (chLower >= 'a' && chLower <= 'm') - { - ch += 13; - } - else if (chLower >= 'n' && chLower <= 'z') - { - ch -= 13; - } - - result += ch; - } - } - - public static int Main(String[] args) - { - if (args.Count < 1 || args[0].Length < 1) - { - Usage(); - } - - String result = scope String(); - Rot13(args[0], ref result); - Console.WriteLine(result); - return 0; - } -} -``` - -{% endraw %} - -Rot13 in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/brainfuck/index.md b/docs/projects/rot13/brainfuck/index.md deleted file mode 100644 index 7bface2379..0000000000 --- a/docs/projects/rot13/brainfuck/index.md +++ /dev/null @@ -1,128 +0,0 @@ ---- -authors: -- Jatin Pandey -date: 2023-12-18 -featured-image: rot13-in-every-language.jpg -last-modified: 2023-12-18 -layout: default -tags: -- brainfuck -- rot13 -title: Rot13 in Brainfuck -title1: Rot13 in -title2: Brainfuck ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Brainfuck](/languages/brainfuck) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```brainfuck -+> -+[ - ,[ - <[-]> - [ - >+>+<<- - ]> - [<+>-] - +>>++++++++ - [<-------->-] - <- - [<[-]>>>+[<+<+>>-]<[>+<-]<[<++> - >>+[<+<->>-]<[>+<-]]>[<]< - ]>>[-]<<< - [[-]<[>>+>+<<<-]>>[<<+>>-]>>++++++++ - [ - <-------->- - ]<->>++++[<++++++++>-]<-< - [>>>+<<[>+>[-]<<-]>[<+>-]>[<<<<<+>>>>++++[<++++++++ - >-]>-]<<-<- - ]>[<<<<[-]>>>>[<<<<->>>>-]]<<++++[<<++++++++>>-]<<-[>>+>+<<<-]>> - [<<+>>-]+>>+++++[<----->-]<- - [<[-]>>>+[<+<->>-]<[>+<-]<[<++>>>+[<+<+>>-]<[>+<-]]>[<] - <]>>[-]<<<[[-]<<[>>+>+<<<-]>>[<<+>>-]+>------------[<[-]>>>+[<+<->>-]<[>+<-]<[< - ++>>>+[<+<+>>-]<[>+<-]]>[<]<]>>[-]<<<<<------------->>[[-]+++++[<<+++++>>-]<<+> - >]<[>++++[<<++++++++>>-]<-]>]<[-]++++++++[<++++++++>-]<+>]<.[-]+>>+< - ]>[[-]<]< -] -<[ - [-] - [Display error message - Source: https://copy.sh/brainfuck/text.html - ] - >[-]< - -[--->+<]>. - +[--->+<]>+. - ++[->+++<]>++. - ++++++. - --. - +++[->+++<]>++. - [-->+<]>+++. - [-->+++++++<]>. - ----. - -------. - ----. - --[--->+<]>--. - ++++[->+++<]>. - --[--->+<]>-. - [-->+++++++<]>. - ++. - ---. - +++++++. - [------>+<]>. - -----. - +. - --[--->+<]>-. - [->+++<]>+. - -[->+++<]>. - ---[->++++<]>-. - +. - --. - ---------. - +++++. - -------. - -[--->+<]>--. - ---[->++++<]>. - -----. - [--->+<]>-----. - +[->+++<]>++. - +++++++++. - -----------. - -[--->+<]>----. - +++++++. - ---------. - ++++. - [-] -] - -``` - -{% endraw %} - -Rot13 in [Brainfuck](/languages/brainfuck) was written by: - -- Jatin Pandey - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/c-plus-plus/index.md b/docs/projects/rot13/c-plus-plus/index.md deleted file mode 100644 index 7df0a0a6a5..0000000000 --- a/docs/projects/rot13/c-plus-plus/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Himanshu Raheja -- Ștefan-Iulian Alecu -date: 2023-10-19 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- rot13 -title: Rot13 in C++ -title1: Rot13 -title2: in C++ ---- - - - -Welcome to the [Rot13](/projects/rot13) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include - -[[noreturn]] void usage() { - std::cerr << "Usage: please provide a string to encrypt\n"; - std::exit(1); -} - -constexpr char rot13_char(char c) { - if (c >= 'a' && c <= 'z') { - return static_cast('a' + (c - 'a' + 13) % 26); - } - if (c >= 'A' && c <= 'Z') { - return static_cast('A' + (c - 'A' + 13) % 26); - } - return c; -} - -int main(int argc, char* argv[]) { - if (argc != 2 || std::string_view(argv[1]).empty()) usage(); - - std::string s = argv[1]; - std::ranges::transform(s, s.begin(), rot13_char); - std::cout << s << '\n'; -} -``` - -{% endraw %} - -Rot13 in [C++](/languages/c-plus-plus) was written by: - -- Himanshu Raheja -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/c-sharp/index.md b/docs/projects/rot13/c-sharp/index.md deleted file mode 100644 index fbada17bae..0000000000 --- a/docs/projects/rot13/c-sharp/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-30 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- rot13 -title: Rot13 in C# -title1: Rot13 -title2: in C# ---- - - - -Welcome to the [Rot13](/projects/rot13) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -if (args is not [var input] || string.IsNullOrEmpty(input)) - return ExitWithUsage(); - -Console.WriteLine(Rot13(input.AsSpan())); -return 0; - -static string Rot13(ReadOnlySpan input) -{ - char[] result = new char[input.Length]; - - for (int i = 0; i < input.Length; i++) - { - char c = input[i]; - result[i] = c switch - { - >= 'a' and <= 'z' => (char)('a' + (c - 'a' + 13) % 26), - >= 'A' and <= 'Z' => (char)('A' + (c - 'A' + 13) % 26), - _ => c, - }; - } - - return new string(result); -} - -static int ExitWithUsage() -{ - Console.WriteLine("Usage: please provide a string to encrypt"); - return 1; -} - -``` - -{% endraw %} - -Rot13 in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/c/index.md b/docs/projects/rot13/c/index.md deleted file mode 100644 index 364f85c6f2..0000000000 --- a/docs/projects/rot13/c/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Softizo -- Ștefan-Iulian Alecu -date: 2019-10-09 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- rot13 -title: Rot13 in C -title1: Rot13 -title2: in C ---- - - - -Welcome to the [Rot13](/projects/rot13) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -void rot13(char *str) -{ - for (int i = 0; str[i] != '\0'; i++) - { - char c = *(str + i); - if (('a' <= c && 'n' > c) || ('A' <= c && 'N' > c)) - *(str + i) += 13; - else if (('n' <= c && 'z' >= c) || ('N' <= c && 'Z' >= c)) - *(str + i) -= 13; - } -} - -int main(int argc, char *argv[]) -{ - if (argc == 2 && strlen(argv[1]) != 0 && !isdigit(*argv[1])) - { - rot13(argv[1]); - printf("%s\n", argv[1]); - } - else - { - printf("Usage: please provide a string to encrypt\n"); - } - - return 0; -} - -``` - -{% endraw %} - -Rot13 in [C](/languages/c) was written by: - -- Softizo -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/cobol/index.md b/docs/projects/rot13/cobol/index.md deleted file mode 100644 index b6ad8f99e2..0000000000 --- a/docs/projects/rot13/cobol/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- rot13 -title: Rot13 in COBOL -title1: Rot13 in -title2: COBOL ---- - - - -Welcome to the [Rot13](/projects/rot13) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. rot13. - -data division. -working-storage section. - -01 arg-count pic 9(4) comp. -01 input-text pic x(500). - -01 translation-keys. - 05 alpha-lower pic x(26) value "abcdefghijklmnopqrstuvwxyz". - 05 rot13-lower pic x(26) value "nopqrstuvwxyzabcdefghijklm". - 05 alpha-upper pic x(26) value "ABCDEFGHIJKLMNOPQRSTUVWXYZ". - 05 rot13-upper pic x(26) value "NOPQRSTUVWXYZABCDEFGHIJKLM". - -procedure division. - -main. - accept arg-count from argument-number - - if arg-count = 0 - perform show-usage - end-if - - accept input-text from argument-value - - if input-text = spaces - perform show-usage - end-if - - perform do-rot13 - goback. - -do-rot13. - inspect input-text - converting alpha-lower to rot13-lower - - inspect input-text - converting alpha-upper to rot13-upper - - display function trim(input-text). - -show-usage. - display "Usage: please provide a string to encrypt" - stop run. - -``` - -{% endraw %} - -Rot13 in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/commodore-basic/index.md b/docs/projects/rot13/commodore-basic/index.md deleted file mode 100644 index 6cce3e0661..0000000000 --- a/docs/projects/rot13/commodore-basic/index.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-09-16 -featured-image: rot13-in-every-language.jpg -last-modified: 2023-09-16 -layout: default -tags: -- commodore-basic -- rot13 -title: Rot13 in Commodore BASIC -title1: Rot13 in -title2: Commodore BASIC ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input string -10 GOSUB 1000 -20 IF S$ = "" THEN GOTO 130 -30 R$ = "" -40 FOR K = 1 TO LEN(S$) -50 A$ = MID$(S$, K, 1) -60 M% = 0 -65 REM Offset by 13 if A-M or a-m, 13 if N-Z or n-z, 0 otherwise -70 IF (A$ >= "A" AND A$ <= "M") OR (A$ >= "a" AND A$ <= "m") THEN M% = 13 -80 IF (A$ >= "N" AND A$ <= "Z") OR (A$ >= "n" AND A$ <= "z") THEN M% = -13 -90 R$ = R$ + CHR$(ASC(A$) + M%) -100 NEXT K -110 PRINT R$ -120 END -130 PRINT "Usage: please provide a string to encrypt" -140 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM S$ = string -1003 REM Initialize -1010 S$ = "" -1015 REM Append characters until end of input -1020 GET A$ -1030 C = ASC(A$) -1040 IF C = 13 OR C = 255 THEN RETURN: REM end of value or input -1050 S$ = S$ + A$ -1060 GOTO 1020 - -``` - -{% endraw %} - -Rot13 in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/dart/index.md b/docs/projects/rot13/dart/index.md deleted file mode 100644 index 93d7f17b1d..0000000000 --- a/docs/projects/rot13/dart/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- slashdoom -date: 2019-10-18 -featured-image: rot13-in-every-language.jpg -last-modified: 2019-10-18 -layout: default -tags: -- dart -- rot13 -title: Rot13 in Dart -title1: Rot13 -title2: in Dart ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Dart](/languages/dart) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```dart -import 'dart:io'; - -main(List args) { - if (args.isEmpty || args[0].isEmpty) { - print("Usage: please provide a string to encrypt"); - exit(1); - } else { - print( rot13(args[0]) ); - } -} - -String rot13(String input) { - int aLower = "a".codeUnitAt(0); - int aUpper = "A".codeUnitAt(0); - int nLower = "n".codeUnitAt(0); - int nUpper = "N".codeUnitAt(0); - int zLower = "z".codeUnitAt(0); - int zUpper = "Z".codeUnitAt(0); - - List coded = []; - - input.codeUnits.forEach((char) { - if ((char >= aLower && char < nLower) || - (char >= aUpper && char < nUpper)) { - coded.add(new String.fromCharCode(char + 13)); - } else if ((char >= nLower && char <= zLower) || - (char >= nUpper && char <= zUpper)) { - coded.add(new String.fromCharCode(char - 13)); - } else { - coded.add(new String.fromCharCode(char)); - } - }); - - return coded.join(); -} - -``` - -{% endraw %} - -Rot13 in [Dart](/languages/dart) was written by: - -- slashdoom - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/elvish/index.md b/docs/projects/rot13/elvish/index.md deleted file mode 100644 index f1dfa46278..0000000000 --- a/docs/projects/rot13/elvish/index.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -authors: -- Zia -date: 2025-01-10 -featured-image: rot13-in-every-language.jpg -last-modified: 2025-01-10 -layout: default -tags: -- elvish -- rot13 -title: Rot13 in Elvish -title1: Rot13 in -title2: Elvish ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Elvish](/languages/elvish) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```elvish -use str - -if (> 1 (count $args)) { - echo "Usage: please provide a string to encrypt" - exit 1 -} -if (== 0 (str:compare $args[0] '')) { - echo "Usage: please provide a string to encrypt" - exit 1 -} - -echo $@args | tr 'A-Za-z' 'N-ZA-Mn-za-m' - -``` - -{% endraw %} - -Rot13 in [Elvish](/languages/elvish) was written by: - -- Zia - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/euphoria/index.md b/docs/projects/rot13/euphoria/index.md deleted file mode 100644 index 8dc6b08c9e..0000000000 --- a/docs/projects/rot13/euphoria/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-17 -featured-image: rot13-in-every-language.jpg -last-modified: 2023-02-24 -layout: default -tags: -- euphoria -- rot13 -title: Rot13 in Euphoria -title1: Rot13 in -title2: Euphoria ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/utils.e - -function rot13(sequence s) - sequence t = "" - for n = 1 to length(s) - do - -- If A-M or a-m, convert to N-Z or n-z by adding 13 to ASCII code - -- Else, convert to A-M or a-m by subtracting 13 from ASCII code - integer offset = 0 - if t_alpha(s[n]) - then - offset = iif(lower(s[n]) <= 'm', 13, -13) - end if - - t &= s[n] + offset - end for - - return t -end function - -procedure usage() - puts(STDOUT, "Usage: please provide a string to encrypt\n") - abort(0) -end procedure - --- Parse 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Encrypt string with ROT13 and display -sequence s = argv[4] -sequence t = rot13(s) -printf(STDOUT, "%s\n", {t}) - -``` - -{% endraw %} - -Rot13 in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/f-sharp/index.md b/docs/projects/rot13/f-sharp/index.md deleted file mode 100644 index a5f8616e61..0000000000 --- a/docs/projects/rot13/f-sharp/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- rot13 -title: Rot13 in F# -title1: Rot13 -title2: in F# ---- - - - -Welcome to the [Rot13](/projects/rot13) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Rot13 = - let private rot13Char c = - let shift baseLetter = - char (((int c - int baseLetter + 13) % 26) + int baseLetter) - - if c >= 'a' && c <= 'z' then shift 'a' - elif c >= 'A' && c <= 'Z' then shift 'A' - else c - - let run = String.map rot13Char - -module Helpers = - let parseArgs = - function - | [| s |] when s <> "" -> Ok s - | _ -> Error "Usage: please provide a string to encrypt" - - let handleResult = - function - | Ok s -> - s |> Rot13.run |> printfn "%s" - 0 - | Error msg -> - printfn "%s" msg - 1 - -[] -let main argv = - argv |> Helpers.parseArgs |> Helpers.handleResult - -``` - -{% endraw %} - -Rot13 in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/go/index.md b/docs/projects/rot13/go/index.md deleted file mode 100644 index 5d9dd7095e..0000000000 --- a/docs/projects/rot13/go/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-03-17 -featured-image: rot13-in-every-language.jpg -last-modified: 2019-04-06 -layout: default -tags: -- go -- rot13 -title: Rot13 in Go -title1: Rot13 -title2: in Go ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strings" -) - -func rot13(str string) string { - return strings.Map(encryptRune, str) -} - -func encryptRune(r rune) rune { - if r >= 65 && r <= 90 { - return (((r - 65) + 13) % 26) + 65 - } else if r >= 97 && r <= 122 { - return (((r - 97) + 13) % 26) + 97 - } else { - return r - } -} - -func exitWithError() { - fmt.Println("Usage: please provide a string to encrypt") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - if len(os.Args[1]) <= 0 { - exitWithError() - } - - fmt.Println(rot13(os.Args[1])) -} - -``` - -{% endraw %} - -Rot13 in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/haskell/index.md b/docs/projects/rot13/haskell/index.md deleted file mode 100644 index 22454cf58d..0000000000 --- a/docs/projects/rot13/haskell/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-11-20 -featured-image: rot13-in-every-language.jpg -last-modified: 2019-04-07 -layout: default -tags: -- haskell -- rot13 -title: Rot13 in Haskell -title1: Rot13 in -title2: Haskell ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Data.Char -import System.Environment -import System.Exit (exitWith, ExitCode(ExitFailure)) - -rot13 :: String -> String -rot13 = map encryptChar - -encryptChar :: Char -> Char -encryptChar c - | ord c >= 65 && ord c <= 90 = toChar 65 $ addDigits $ toNum 65 c - | ord c >= 97 && ord c <= 122 = toChar 97 $ addDigits $ toNum 97 c - | otherwise = c - where toNum base c = (ord c) - base - toChar base n = chr $ n + base - addDigits n = (n + 13) `mod` 26 - - - -main :: IO () -main = do - args <- getArgs - if null args || (head args) == "" then do - putStrLn "Usage: please provide a string to encrypt" - exitWith $ ExitFailure 1 - else - putStrLn $ rot13 $ head args - -``` - -{% endraw %} - -Rot13 in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/index.md b/docs/projects/rot13/index.md deleted file mode 100644 index d5356418e9..0000000000 --- a/docs/projects/rot13/index.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -date: 2018-11-20 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- rot13 -title: Rot13 -title1: Rot13 -title2: '' ---- - - - -Welcome to the Rot13 page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Ron Zuckerman - -## Description - -ROT13 is a letter substitution cipher where every letter is replaced by the -letter 13 letters after it alphabetically and wrapping from `Z` to `A` if necessary: - - ABCDEFGHIJKLMNOPQRSTUVWXYZ -> NOPQRSTUVWXYZABCDEFGHIJKLM - -As a result, encrypted strings can be decrypted using the same algorithm: - - NOPQRSTUVWXYZABCDEFGHIJKLM -> ABCDEFGHIJKLMNOPQRSTUVWXYZ - - -## Requirements - -Write a sample program that takes a string of text as input. -It should then encrypt the inputted text using ROT13 and output the result to the console. - -```console -$ ./rot13.lang "the quick brown fox jumped over the lazy dog" -gur dhvpx oebja sbk whzcrq bire gur ynml qbt -``` - -The solution should handle both lower case and capital letters - -```console -$ ./rot13.lang "THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG" -GUR DHVPX OEBJA SBK WHZCRQ BIRE GUR YNML QBT -``` - -Any characters/symbols besides a-z and A-Z should be ignored. - -```console -$ ./rot13.lang "The quick brown fox jumped. Was it over the lazy dog?" -Gur dhvpx oebja sbk whzcrq. Jnf vg bire gur ynml qbt? -``` - -In addition, there should be some error handling for situations where the user -doesn't supply any input. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Rot13. -In order to keep things simple, we split up the testing as follows: - -- Rot13 Valid Tests -- Rot13 Invalid Tests - -### Rot13 Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input Lower Case | "the quick brown fox jumped over the lazy dog" | "gur dhvpx oebja sbk whzcrq bire gur ynml qbt" | -| Sample Input Upper Case | "THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG" | "GUR DHVPX OEBJA SBK WHZCRQ BIRE GUR YNML QBT" | -| Sample Input Punctuation | "The quick brown fox jumped. Was it over the lazy dog?" | "Gur dhvpx oebja sbk whzcrq. Jnf vg bire gur ynml qbt?" | - -### Rot13 Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | - -All of these tests should output the following: - -``` -Usage: please provide a string to encrypt -``` - - -## Articles - -There are 34 articles: - -- [Rot13 in ALGOL 60](/projects/rot13/algol60) -- [Rot13 in ALGOL 68](/projects/rot13/algol68) -- [Rot13 in AWK](/projects/rot13/awk) -- [Rot13 in Beef](/projects/rot13/beef) -- [Rot13 in Brainfuck](/projects/rot13/brainfuck) -- [Rot13 in C](/projects/rot13/c) -- [Rot13 in C#](/projects/rot13/c-sharp) -- [Rot13 in C++](/projects/rot13/c-plus-plus) -- [Rot13 in COBOL](/projects/rot13/cobol) -- [Rot13 in Commodore BASIC](/projects/rot13/commodore-basic) -- [Rot13 in Dart](/projects/rot13/dart) -- [Rot13 in Elvish](/projects/rot13/elvish) -- [Rot13 in Euphoria](/projects/rot13/euphoria) -- [Rot13 in F#](/projects/rot13/f-sharp) -- [Rot13 in Go](/projects/rot13/go) -- [Rot13 in Haskell](/projects/rot13/haskell) -- [Rot13 in Java](/projects/rot13/java) -- [Rot13 in JavaScript](/projects/rot13/javascript) -- [Rot13 in Kotlin](/projects/rot13/kotlin) -- [Rot13 in Lua](/projects/rot13/lua) -- [Rot13 in Mathematica](/projects/rot13/mathematica) -- [Rot13 in PHP](/projects/rot13/php) -- [Rot13 in Pascal](/projects/rot13/pascal) -- [Rot13 in Perl](/projects/rot13/perl) -- [Rot13 in PowerShell](/projects/rot13/powershell) -- [Rot13 in Python](/projects/rot13/python) -- [Rot13 in Ruby](/projects/rot13/ruby) -- [Rot13 in Rust](/projects/rot13/rust) -- [Rot13 in Swift](/projects/rot13/swift) -- [Rot13 in TI-BASIC](/projects/rot13/ti-basic) -- [Rot13 in Tcl](/projects/rot13/tcl) -- [Rot13 in TypeScript](/projects/rot13/typescript) -- [Rot13 in Visual Basic](/projects/rot13/visual-basic) -- [Rot13 in m4](/projects/rot13/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/rot13/java/index.md b/docs/projects/rot13/java/index.md deleted file mode 100644 index 5acb1045a9..0000000000 --- a/docs/projects/rot13/java/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- Jeremy Grifski -- jsonW0 -date: 2019-10-27 -featured-image: rot13-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- java -- rot13 -title: Rot13 in Java -title1: Rot13 -title2: in Java ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -public class Rot13 { - public static void main(String[] args) { - if (args.length < 1) { - System.out.println("Usage: please provide a string to encrypt"); - } else { - String code = args[0]; - String result = ""; - if (code.length() == 0) { - System.out.println("Usage: please provide a string to encrypt"); - } else { - String lower = "abcdefghijklmnopqrstuvwxyz"; - String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - for (int a = 0; a < code.length(); a++) { - String ch = code.substring(a, a + 1); - int l = lower.indexOf(ch); - int u = upper.indexOf(ch); - if (l != -1) { - result += lower.substring((l + 13) % 26, (l + 14) % 26 != 0 ? (l + 14) % 26 : l + 14); - } else if (u != -1) { - result += upper.substring((u + 13) % 26, (u + 14) % 26 != 0 ? (u + 14) % 26 : u + 14); - } else { - result += ch; - } - } - System.out.println(result); - } - } - } -} -``` - -{% endraw %} - -Rot13 in [Java](/languages/java) was written by: - -- Jeremy Grifski -- jsonW0 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/javascript/index.md b/docs/projects/rot13/javascript/index.md deleted file mode 100644 index f9f848619d..0000000000 --- a/docs/projects/rot13/javascript/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- mericleac -date: 2019-10-22 -featured-image: rot13-in-every-language.jpg -last-modified: 2019-10-22 -layout: default -tags: -- javascript -- rot13 -title: Rot13 in JavaScript -title1: Rot13 in -title2: JavaScript ---- - - - -Welcome to the [Rot13](/projects/rot13) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const lower = "abcdefghijklmnopqrstuvwxyz"; -const upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - -const rotateChar = (char) => { - if (lower.includes(char)) { - const newIdx = (lower.indexOf(char) + 13) % lower.length; - return lower[newIdx]; - } - if (upper.includes(char)) { - const newIdx = (upper.indexOf(char) + 13) % upper.length; - return upper[newIdx]; - } - return char; -} - -const rotate13 = (string) => { - const stringArray = string.split(""); - const rotatedBy13 = stringArray.map((char) => rotateChar(char)); - return rotatedBy13.join(""); -} - -const exit = () => { - console.log('Usage: please provide a string to encrypt'); - process.exit(); -} - -const main = (input) => { - try { - input.length > 0 ? console.log(rotate13(input)): exit(); - } catch { - exit(); - } -} - -main(process.argv[2]); - -``` - -{% endraw %} - -Rot13 in [JavaScript](/languages/javascript) was written by: - -- mericleac - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/kotlin/index.md b/docs/projects/rot13/kotlin/index.md deleted file mode 100644 index 4ac445d187..0000000000 --- a/docs/projects/rot13/kotlin/index.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -authors: -- Cristiano Lopes -- Jeremy Grifski -date: 2020-10-07 -featured-image: rot13-in-every-language.jpg -last-modified: 2020-10-09 -layout: default -tags: -- kotlin -- rot13 -title: Rot13 in Kotlin -title1: Rot13 in -title2: Kotlin ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -data class EncodingBounds(val lowerBound: Int, val upperBound: Int) - -fun encodingBoundsForCharValue(c: Char): EncodingBounds? { - val lowerCaseBounds = EncodingBounds('a'.toInt(), 'z'.toInt()) - val upperCaseBounds = EncodingBounds('A'.toInt(), 'Z'.toInt()) - return when (c) { - in 'a'..'z' -> lowerCaseBounds - in 'A'..'Z' -> upperCaseBounds - else -> null - } -} - -fun calculateRotatedChar(char: Char, rotation: Int, bounds: EncodingBounds): Char { - val rotatedCharVal = char.toInt() + rotation - val remainder = rotatedCharVal - (bounds.upperBound + 1) - return (if (rotatedCharVal > bounds.upperBound) bounds.lowerBound + remainder else rotatedCharVal).toChar() -} - -fun parseInput(args: Array): String? { - if (args.isEmpty()) { - return null - } - val text = args[0] - if (text.isEmpty()) { - return null - } - return text -} - -fun rot13Encode(text: String): String { - val rotation = 13 - - return text.map { c -> - val bounds = encodingBoundsForCharValue(c) - if (bounds == null) { - c.toString() - } else { - calculateRotatedChar(c, rotation, bounds).toString() - } - }.reduce { encodedText, encodedChar -> - encodedText + encodedChar - } - -} - -fun main(args: Array) { - val strToEncode = parseInput(args) - if (strToEncode == null) { - println("Usage: please provide a string to encrypt") - } else { - println(rot13Encode(strToEncode)) - } -} - -``` - -{% endraw %} - -Rot13 in [Kotlin](/languages/kotlin) was written by: - -- Cristiano Lopes -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/lua/index.md b/docs/projects/rot13/lua/index.md deleted file mode 100644 index c1dcd42974..0000000000 --- a/docs/projects/rot13/lua/index.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -authors: -- Alex Gustafsson -- Jeremy Grifski -date: 2019-10-18 -featured-image: rot13-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- lua -- rot13 -title: Rot13 in Lua -title1: Rot13 -title2: in Lua ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Lua](/languages/lua) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```lua -local function ascii_base(s) - return s:lower() == s and ('a'):byte() or ('A'):byte() -end - -function caesar_cipher(str, key) - return (str:gsub('%a', function(s) - local base = ascii_base(s) - return string.char(((s:byte() - base + key) % 26) + base) - end)) -end - -if (#arg < 1 or arg[1] == "") -then - print('Usage: please provide a string to encrypt') -else - io.write(caesar_cipher(arg[1], 13)) -end - -io.write("\n") - -``` - -{% endraw %} - -Rot13 in [Lua](/languages/lua) was written by: - -- Alex Gustafsson -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/m4/index.md b/docs/projects/rot13/m4/index.md deleted file mode 100644 index 75f5deeaa1..0000000000 --- a/docs/projects/rot13/m4/index.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-08-09 -featured-image: rot13-in-every-language.jpg -last-modified: 2025-08-09 -layout: default -tags: -- m4 -- rot13 -title: Rot13 in m4 -title1: Rot13 -title2: in m4 ---- - - - -Welcome to the [Rot13](/projects/rot13) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a string to encrypt -m4exit(`1')') - -define(`rot13', `translit(`$1', `A-MN-Za-mn-z', `N-ZA-Mn-za-m')') -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1), 1, `show_usage()', `rot13(ARGV1)') - -``` - -{% endraw %} - -Rot13 in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/mathematica/index.md b/docs/projects/rot13/mathematica/index.md deleted file mode 100644 index 298b531b5a..0000000000 --- a/docs/projects/rot13/mathematica/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-16 -featured-image: rot13-in-every-language.jpg -last-modified: 2023-01-16 -layout: default -tags: -- mathematica -- rot13 -title: Rot13 in Mathematica -title1: Rot13 in -title2: Mathematica ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* The actual rotation operating on Mathematica strings: *) - -rot13 = s \[Function] StringJoin @@ Function[{c}, - FromCharacterCode @ - Piecewise[(* operate piecewise on the domain of ASCII character codes *) - Append[{ - Mod[c + 13, 26, First@ToCharacterCode[StringTake[#, 1]]], - Between[c, ToCharacterCode[#]]} & /@ - {"az", "AZ"},(* specific character intervals to operate on *) - {c, True}] (* default does nothing *) - ]] /@ ToCharacterCode[s]; - -(* The outer function provides the 'user interface': *) - -rot13Main = s \[Function] - Catch[ - rot13[ - If[ - StringQ[s] \[And] \[Not] StringMatchQ[s, ""], - s, - Throw["Usage: please provide a string to encrypt"]]]]; - - -(* Valid Tests *) - -Print /@ rot13Main /@ { - "the quick brown fox jumped over the lazy dog", - "THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG", - "The quick brown fox jumped. Was it over the lazy dog?" - }; - - -(* Invalid Tests *) - -rot13Main[""] - -``` - -{% endraw %} - -Rot13 in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/pascal/index.md b/docs/projects/rot13/pascal/index.md deleted file mode 100644 index 1648b38c5a..0000000000 --- a/docs/projects/rot13/pascal/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-21 -featured-image: rot13-in-every-language.jpg -last-modified: 2025-07-21 -layout: default -tags: -- pascal -- rot13 -title: Rot13 in Pascal -title1: Rot13 in -title2: Pascal ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program Rot13; - -{$mode objfpc}{$H+} - -uses - SysUtils; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a string to encrypt'); - Halt(1); -end; - -function Rot13(const S: string): string; -var - ch: char; -begin - Result := ''; - for ch in S do - case ch of - 'A'..'Z': - Result += Chr(((Ord(ch) - Ord('A') + 13) mod 26) + Ord('A')); - 'a'..'z': - Result += Chr(((Ord(ch) - Ord('a') + 13) mod 26) + Ord('a')); - else - Result += ch; - end; -end; - -var - Input: string; -begin - if ParamCount <> 1 then - ShowUsage; - - Input := ParamStr(1); - if Input = '' then - ShowUsage; - - Writeln(Rot13(Input)); -end. - -``` - -{% endraw %} - -Rot13 in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/perl/index.md b/docs/projects/rot13/perl/index.md deleted file mode 100644 index 828138bd47..0000000000 --- a/docs/projects/rot13/perl/index.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -authors: -- Gijs Hendriksen -- Ștefan-Iulian Alecu -date: 2019-10-30 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- perl -- rot13 -title: Rot13 in Perl -title1: Rot13 -title2: in Perl ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -sub usage { - say "Usage: please provide a string to encrypt"; - exit; -} - -my ($str) = @ARGV; -usage() unless defined $str && length $str; - -$str =~ tr/A-Za-z/N-ZA-Mn-za-m/; -say $str; - -``` - -{% endraw %} - -Rot13 in [Perl](/languages/perl) was written by: - -- Gijs Hendriksen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/php/index.md b/docs/projects/rot13/php/index.md deleted file mode 100644 index 20fe5e0124..0000000000 --- a/docs/projects/rot13/php/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- Andy Alban -- Jeremy Grifski -date: 2019-10-13 -featured-image: rot13-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- php -- rot13 -title: Rot13 in PHP -title1: Rot13 -title2: in PHP ---- - - - -Welcome to the [Rot13](/projects/rot13) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Rot13](/projects/rot13) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please provide a string to encrypt" - Exit 1 -} - -function Get-Rot13([string]$Str) { - # -regex is case-insensitve - $Result = switch -regex ($Str.ToCharArray()) { - "[a-m]" { [char]([byte]$_ + 13) } # A-M, a-m -> N-Z, n-z - "[n-z]" { [char]([byte]$_ - 13) } # N-Z, n-z -> A-M, a-m - default { $_ } # Else, don't change - } - -join $Result -} - -if ($args.Length -lt 1 -or -not $args[0]) { - Show-Usage -} - -Write-Host (Get-Rot13($args[0])) - -``` - -{% endraw %} - -Rot13 in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/python/index.md b/docs/projects/rot13/python/index.md deleted file mode 100644 index 5d8bf86363..0000000000 --- a/docs/projects/rot13/python/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -date: 2018-12-23 -featured-image: rot13-in-every-language.jpg -last-modified: 2020-10-15 -layout: default -tags: -- python -- rot13 -title: Rot13 in Python -title1: Rot13 in -title2: Python ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys -from string import ascii_uppercase, ascii_lowercase - - -def rot_13(string): - return ''.join([encrypt_char(c) for c in string]) - - -def encrypt_char(c): - if c in ascii_uppercase: - ltrs = ascii_uppercase - elif c in ascii_lowercase: - ltrs = ascii_lowercase - else: - return c - new_index = (ltrs.index(c) + 13) % 26 - return ltrs[new_index] - - -def exit_with_error(): - print('Usage: please provide a string to encrypt') - sys.exit(1) - - -def main(args): - try: - string = args[0] - if len(string) <= 0: - exit_with_error() - print(rot_13(string)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Rot13 in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/ruby/index.md b/docs/projects/rot13/ruby/index.md deleted file mode 100644 index f9b1f0c5c3..0000000000 --- a/docs/projects/rot13/ruby/index.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- rot13 -- ruby -title: Rot13 in Ruby -title1: Rot13 -title2: in Ruby ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = "Usage: please provide a string to encrypt" - -def usage! - warn USAGE - exit 1 -end - -def rot13(str) - str.tr("A-Za-z", "N-ZA-Mn-za-m") -end - -input = ARGV.first -usage! if input.nil? || input.strip.empty? - -puts rot13(input) - -``` - -{% endraw %} - -Rot13 in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/rust/index.md b/docs/projects/rot13/rust/index.md deleted file mode 100644 index 60007c3aaf..0000000000 --- a/docs/projects/rot13/rust/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Vincent Caron -date: 2019-07-15 -featured-image: rot13-in-every-language.jpg -last-modified: 2022-05-16 -layout: default -tags: -- rot13 -- rust -title: Rot13 in Rust -title1: Rot13 -title2: in Rust ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env; - -fn rot13(input: String) -> String { - let mut output = String::new(); - - for character in input.chars() { - let offset; - - if character.is_ascii_lowercase() { - offset = 'a' as u8; - } - else if character.is_ascii_uppercase() { - offset = 'A' as u8; - } - else { - output.push(character); - continue; - } - - let mut rotated = character as u8; - rotated -= offset; - rotated += 13; - rotated %= 26; - rotated += offset; - - output.push(rotated as char); - } - - return output; -} - -fn main() { - let args: Vec = env::args().collect(); - if (args.len() == 1) { - println!("Usage: please provide a string to encrypt"); - return; - } - - let input = args[1].to_string(); - if (input.is_empty()) { - println!("Usage: please provide a string to encrypt"); - return; - } - - let output = rot13(input); - println!("{}", output); -} -``` - -{% endraw %} - -Rot13 in [Rust](/languages/rust) was written by: - -- Jeremy Grifski -- Vincent Caron - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/swift/index.md b/docs/projects/rot13/swift/index.md deleted file mode 100644 index 3d61c20681..0000000000 --- a/docs/projects/rot13/swift/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- rot13 -- swift -title: Rot13 in Swift -title1: Rot13 in -title2: Swift ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = "Usage: please provide a string to encrypt" - -extension StringProtocol { - var rot13: String { - String( - unicodeScalars.map { scalar in - switch scalar { - case "A"..."M", "a"..."m": - return Character(UnicodeScalar(scalar.value + 13)!) - case "N"..."Z", "n"..."z": - return Character(UnicodeScalar(scalar.value - 13)!) - default: - return Character(scalar) - } - } - ) - } -} - -guard - let input = CommandLine.arguments.dropFirst().first, - !input.isEmpty -else { - print(usage) - exit(1) -} - -print(input.rot13) - -``` - -{% endraw %} - -Rot13 in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/tcl/index.md b/docs/projects/rot13/tcl/index.md deleted file mode 100644 index 686c85514d..0000000000 --- a/docs/projects/rot13/tcl/index.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: rot13-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- rot13 -- tcl -title: Rot13 in Tcl -title1: Rot13 -title2: in Tcl ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl - -proc usage {} { - puts "Usage: please provide a string to encrypt" - exit 1 -} - -if {$argc != 1} { usage } -set input [lindex $argv 0] -if {$input eq ""} { usage } - -proc rot13 {text} { - set upper "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - set lower "abcdefghijklmnopqrstuvwxyz" - - set map {} - - for {set i 0} {$i < 26} {incr i} { - lappend map [string index $upper $i] [string index $upper [expr {($i+13)%26}]] - lappend map [string index $lower $i] [string index $lower [expr {($i+13)%26}]] - } - - return [string map $map $text] -} - -puts [rot13 $input] - - -``` - -{% endraw %} - -Rot13 in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/ti-basic/index.md b/docs/projects/rot13/ti-basic/index.md deleted file mode 100644 index c973fb8770..0000000000 --- a/docs/projects/rot13/ti-basic/index.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-02-01 -featured-image: rot13-in-every-language.jpg -last-modified: 2025-02-01 -layout: default -tags: -- rot13 -- ti-basic -title: Rot13 in TI-BASIC -title1: Rot13 in -title2: TI-BASIC ---- - - - -Welcome to the [Rot13](/projects/rot13) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"->Str2 -"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"->Str3 -length(Str1)->L -"Usage: please provide a string to encrypt"->Str4 -If L>0 Then - ""->Str4 - For(N,1,L) - sub(Str1,N,1)->Str5 - inString(Str2,Str5)->K - If K>0 Then Str4+sub(Str3,K,1)->Str4 - Else Str4+Str5->Str4 - End - End -End -Disp Str4 - -``` - -{% endraw %} - -Rot13 in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/typescript/index.md b/docs/projects/rot13/typescript/index.md deleted file mode 100644 index 0c3129dbe7..0000000000 --- a/docs/projects/rot13/typescript/index.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -authors: -- Ferrel John Fernando -date: 2024-10-09 -featured-image: rot13-in-every-language.jpg -last-modified: 2024-10-09 -layout: default -tags: -- rot13 -- typescript -title: Rot13 in TypeScript -title1: Rot13 in -title2: TypeScript ---- - - - -Welcome to the [Rot13](/projects/rot13) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function rot13(input: string): string { - if (!input) { - return "Usage: please provide a string to encrypt"; - } - - return input.split('').map(char => { - const code = char.charCodeAt(0); - // Check if the character is an uppercase letter - if (code >= 65 && code <= 90) { - return String.fromCharCode((code - 65 + 13) % 26 + 65); - } - // Check if the character is a lowercase letter - else if (code >= 97 && code <= 122) { - return String.fromCharCode((code - 97 + 13) % 26 + 97); - } - // If it's not a letter, return the character unchanged - return char; - }).join(''); -} - -const args = process.argv.slice(2); - -if (args.length !== 1) { - console.log("Usage: please provide a string to encrypt"); - process.exit(1); -} else { - const input = args[0]; - const result = rot13(input); - console.log(result); -} - -``` - -{% endraw %} - -Rot13 in [TypeScript](/languages/typescript) was written by: - -- Ferrel John Fernando - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/rot13/visual-basic/index.md b/docs/projects/rot13/visual-basic/index.md deleted file mode 100644 index 5d403fb2d9..0000000000 --- a/docs/projects/rot13/visual-basic/index.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: rot13-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- rot13 -- visual-basic -title: Rot13 in Visual Basic -title1: Rot13 in -title2: Visual Basic ---- - - - -Welcome to the [Rot13](/projects/rot13) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Imports System.Text - -Public Module Rot13 - - Private Sub ShowUsage() - Console.WriteLine("Usage: please provide a string to encrypt") - Environment.Exit(1) - End Sub - - - Private Function EncryptChar(c As Char) As Char - - If c >= "A"c AndAlso c <= "Z"c Then - Return ChrW(((AscW(c) - AscW("A"c) + 13) Mod 26) + AscW("A"c)) - End If - - If c >= "a"c AndAlso c <= "z"c Then - Return ChrW(((AscW(c) - AscW("a"c) + 13) Mod 26) + AscW("a"c)) - End If - - Return c - - End Function - - - Private Function Encrypt(input As String) As String - - Dim result As New StringBuilder(input.Length) - - For Each c As Char In input - result.Append(EncryptChar(c)) - Next - - Return result.ToString() - - End Function - - - Public Function Main(args As String()) As Integer - - If args Is Nothing OrElse args.Length = 0 OrElse String.IsNullOrEmpty(args(0)) Then - ShowUsage() - End If - - Console.WriteLine(Encrypt(args(0))) - - Return 0 - - End Function - -End Module -``` - -{% endraw %} - -Rot13 in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/algol60/index.md b/docs/projects/selection-sort/algol60/index.md deleted file mode 100644 index c663a655e7..0000000000 --- a/docs/projects/selection-sort/algol60/index.md +++ /dev/null @@ -1,268 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-17 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- selection-sort -title: Selection Sort in ALGOL 60 -title1: Selection Sort -title2: in ALGOL 60 ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please provide a list of at least two integers " - "to sort in the format \"1, 2, 3, 4, 5\"\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Output integer array; - procedure outIntegerArray(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i; - for i := 1 step 1 until arrLen do - begin - if i > 1 then outstring(1, ", "); - outIntegerNoSpace(arr[i]) - end; - - if arrLen > 0 then outstring(1, "\n") - end outIntegerArray; - - comment Source https://en.wikipedia.org/wiki/Selection_sort#Implementations; - procedure selectionSort(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i, j, jMin, temp; - - for i := 1 step 1 until arrLen - 1 do - begin - jMin := i; - for j := i + 1 step 1 until arrLen do - begin - if arr[j] < arr[jMin] then jMin := j - end; - - if jMin != i then - begin - temp := arr[jMin]; - arr[jMin] := arr[i]; - arr[i] := temp - end - end - end selectionSort; - - integer argc, arrLen; - integer array arr[1:100]; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get input from 1st argument. Exit if invalid; - arrLen := inIntegerArray(arr, 100); - if arrLen < 2 then usage; - - comment Selection sort input and output result; - selectionSort(arr, arrLen); - outIntegerArray(arr, arrLen) -end - -``` - -{% endraw %} - -Selection Sort in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/algol68/index.md b/docs/projects/selection-sort/algol68/index.md deleted file mode 100644 index 0a397b4b0f..0000000000 --- a/docs/projects/selection-sort/algol68/index.md +++ /dev/null @@ -1,209 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-01-29 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2023-02-01 -layout: default -tags: -- algol68 -- selection-sort -title: Selection Sort in ALGOL 68 -title1: Selection Sort -title2: in ALGOL 68 ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: ( - printf(($gl$, "Usage: please provide a list of at least two integers to sort in the format ""1, 2, 3, 4, 5""")) -); - -PROC selection sort = (REF []INT values) VOID: -( - COMMENT - Source: https://en.wikipedia.org/wiki/Selection_sort#Implementations - COMMENT - - INT n = UPB values; - INT temp; - INT min pos; - FOR i TO n - 1 - DO - min pos := i; - FOR j FROM i + 1 TO n - DO - IF values[j] < values[min pos] - THEN - min pos := j - FI - OD; - - IF min pos /= i - THEN - temp := values[i]; - values[i] := values[min pos]; - values[min pos] := temp - FI - OD -); - -PROC show list values = (REF []INT values) VOID: -( - INT n = UPB values; - FOR k TO n - DO - IF k > 1 - THEN - print(", ") - FI; - - print(whole(values[k], 0)) - OD; - - IF n > 0 - THEN - print(newline) - FI -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -IF NOT valid OF list result OR UPB values < 2 -THEN - usage; - stop -FI; - -# Do selection sort and show results # -selection sort(values); -show list values(values) - -``` - -{% endraw %} - -Selection Sort in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/awk/index.md b/docs/projects/selection-sort/awk/index.md deleted file mode 100644 index c486431932..0000000000 --- a/docs/projects/selection-sort/awk/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-21 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2025-04-21 -layout: default -tags: -- awk -- selection-sort -title: Selection Sort in AWK -title1: Selection -title2: Sort in AWK ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -# Source: https://en.wikipedia.org/wiki/Selection_sort#Implementations -function selection_sort(arr, arr_len, i, j, t, min_pos) { - for (i = 1; i < arr_len; i++) { - min_pos = i - for (j = i + 1; j <= arr_len; j++) { - if (arr[j] < arr[min_pos]) { - min_pos = j - } - } - - if (min_pos != i) { - t = arr[i] - arr[i] = arr[min_pos] - arr[min_pos] = t - } - } -} - -function show_array(arr, idx, s) { - s = "" - for (idx in arr) { - if (s) { - s = s ", " - } - s = s arr[idx] - } - - print s -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - str_to_array(ARGV[1], arr) - arr_len = length(arr) - if (!arr_len || arr_len < 2) { - usage() - } - - selection_sort(arr, arr_len) - show_array(arr) -} - -``` - -{% endraw %} - -Selection Sort in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/bash/index.md b/docs/projects/selection-sort/bash/index.md deleted file mode 100644 index 8e59acb92e..0000000000 --- a/docs/projects/selection-sort/bash/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- Jan-Hendrik Ewers -date: 2020-10-05 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2020-10-05 -layout: default -tags: -- bash -- selection-sort -title: Selection Sort in Bash -title1: Selection -title2: Sort in Bash ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Bash](/languages/bash) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```bash -#!/bin/bash -# By Jan-Hendrik Ewers (iwishiwasaneagle) -# 04/10/2020 - -function exit_with_err(){ - USAGE='Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - echo $USAGE - exit 1 -} - -N_check=$(echo "$@" | awk -F', ' '{ print NF-1 }') -if [ $N_check -lt 1 ]; then - exit_with_err -fi - -# Read args and spit on ',' -IFS=', ' read -r -a array <<< "$@" -N=${#array[@]} - -# Selection sort logic -for((i=0;i - -Welcome to the [Selection Sort](/projects/selection-sort) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace SelectionSort; - -class Program -{ - public static void Usage() - { - Console.WriteLine( - """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - ); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - // Reference: https://en.wikipedia.org/wiki/Selection_sort#Implementations - public static void SelectionSort(List arr) - where int : operator T <=> T - { - int nMinus1 = arr.Count - 1; - for (int i < nMinus1) - { - int jMin = i; - for (int j in (i + 1)...nMinus1) - { - if (arr[j] < arr[jMin]) - { - jMin = j; - } - } - - if (jMin != i) - { - Swap!(arr[i], arr[jMin]); - } - } - } - - public static void ShowList(List arr) - { - String line = scope .(); - for (T val in arr) - { - if (!line.IsEmpty) - { - line += ", "; - } - - line.AppendF("{}", val); - } - - Console.WriteLine(line); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - List arr = scope .(); - switch (ParseIntList(args[0], arr)) - { - case .Ok: - if (arr.Count < 2) - { - Usage(); - } - case .Err: - Usage(); - } - - SelectionSort(arr); - ShowList(arr); - return 0; - } -} - -``` - -{% endraw %} - -Selection Sort in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/c-plus-plus/index.md b/docs/projects/selection-sort/c-plus-plus/index.md deleted file mode 100644 index 5b5f0b102f..0000000000 --- a/docs/projects/selection-sort/c-plus-plus/index.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Parker Johansen -- Sailok Chinta -- Ștefan-Iulian Alecu -date: 2019-10-23 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- selection-sort -title: Selection Sort in C++ -title1: Selection -title2: Sort in C++ ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cerr - << R"(Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5")" - << '\n'; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size()) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.size() < 2 ? std::nullopt : std::make_optional(out); -} - -template - requires std::sortable> -void selection_sort(R&& r) { - auto first = ranges::begin(r); - auto last = ranges::end(r); - - for (auto it = first; it != last; ++it) { - auto min_it = ranges::min_element(it, last); - ranges::iter_swap(it, min_it); - } -} - -int main(int argc, char* argv[]) { - if (argc != 2) usage(); - - auto vec = parse_vec(argv[1]); - if (!vec) usage(); - - selection_sort(*vec); - - for (const char* sep = ""; int val : *vec) { - std::cout << std::exchange(sep, ", ") << val; - } - std::cout << "\n"; -} - -``` - -{% endraw %} - -Selection Sort in [C++](/languages/c-plus-plus) was written by: - -- Jeremy Grifski -- Parker Johansen -- Sailok Chinta -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/c-sharp/index.md b/docs/projects/selection-sort/c-sharp/index.md deleted file mode 100644 index 5778830332..0000000000 --- a/docs/projects/selection-sort/c-sharp/index.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -authors: -- Parker Johansen -- Ștefan-Iulian Alecu -date: 2018-12-30 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- selection-sort -title: Selection Sort in C# -title1: Selection -title2: Sort in C# ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Collections.Generic; -using System.Runtime.InteropServices; - -if (args is not [var input] || !TryParseList(input.AsSpan(), out var numbers)) - return ExitWithUsage(); - -SelectionSort(numbers); - -Console.WriteLine(string.Join(", ", numbers)); -return 0; - -static bool TryParseList(ReadOnlySpan span, out List numbers) -{ - numbers = new(span.Count(',') + 1); - - while (!span.IsEmpty) - { - int comma = span.IndexOf(','); - var token = comma >= 0 ? span[..comma] : span; - - span = comma >= 0 ? span[(comma + 1)..] : []; - - if (!int.TryParse(token, out int n)) - return false; - - numbers.Add(n); - } - - return numbers.Count > 1; -} - -static void SelectionSort(List list) -{ - if (list.Count < 2) - return; - - Span span = CollectionsMarshal.AsSpan(list); - - int n = span.Length; - - for (int i = 0; i < n - 1; i++) - { - int minIndex = i; - - for (int j = i + 1; j < n; j++) - { - if (span[j] < span[minIndex]) - minIndex = j; - } - - if (minIndex != i) - (span[i], span[minIndex]) = (span[minIndex], span[i]); - } -} - -static int ExitWithUsage() -{ - Console.WriteLine( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - ); - return 1; -} - -``` - -{% endraw %} - -Selection Sort in [C#](/languages/c-sharp) was written by: - -- Parker Johansen -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/c/index.md b/docs/projects/selection-sort/c/index.md deleted file mode 100644 index b64cb48ac0..0000000000 --- a/docs/projects/selection-sort/c/index.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -authors: -- vidit624 -- Ștefan-Iulian Alecu -date: 2020-10-02 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- selection-sort -title: Selection Sort in C -title1: Selection -title2: Sort in C ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -// Selection Sort In C Language - -#include -#include -#include -#include - -void selectionSort(long arr[], size_t n); // Function for Selection Sort -void swap(long *xp, long *yp); // Swap two numbers - -size_t parse_list(const char *orig_list, - long **arr) // used for parsing the input in array arr -{ - char *list; - char *token; - size_t num_elements = 0; - int i; - int curr_index = 0; - long temp_num; - - /* figure out the length of the list first */ - for (i = 0; orig_list[i]; i++) - if (orig_list[i] == ',') - num_elements++; - - /* if there are no commas, it's an invalid list */ - if (num_elements == 0) - { - *arr = NULL; - return 0; - } - - /* since there's one more number than there are commas, add one */ - num_elements++; - - /* alloc our array */ - *arr = malloc(num_elements * sizeof(long)); - - /* find the numbers */ - list = strdup(orig_list); - token = strtok(list, ","); - while (token != NULL) - { - errno = 0; - temp_num = strtol(token, NULL, 10); - if (errno != 0) - { - *arr = NULL; - return 0; - } - - (*arr)[curr_index++] = temp_num; - - token = strtok(NULL, ","); - } - - free(list); - - return num_elements; -} - -/* printing array in desired form */ -void printArray(long *arr, size_t num_elems) -{ - int i; - - for (i = 0; i < num_elems - 1; i++) - printf("%ld, ", arr[i]); - - printf("%ld\n", arr[num_elems - 1]); -} - -/* Error message if input is not in desired format */ -void errorMsg() -{ - fputs("Usage: please provide a list of at least two integers to sort in " - "the format \"1, 2, 3, 4, 5\"\n", - stderr); -} - -int main(int argc, char **argv) -{ - long *arr; - long num_elements; - - if (argc < 2) - { - errorMsg(); - return 1; - } - - num_elements = parse_list(argv[1], &arr); - if (num_elements == 0) - { - errorMsg(); - return 1; - } - - selectionSort(arr, num_elements); // call for complete array [0....n-1] - printArray(arr, num_elements); - - free(arr); -} - -void swap(long *xp, long *yp) -{ - int temp = *xp; - *xp = *yp; - *yp = temp; -} - -void selectionSort(long arr[], size_t n) -{ - int i, j, min_idx; - - // One by one move boundary of unsorted subarray - for (i = 0; i < n - 1; i++) - { - // Find the minimum element in unsorted array - min_idx = i; - for (j = i + 1; j < n; j++) - if (arr[j] < arr[min_idx]) - min_idx = j; - - // Swap the found minimum element with the first element - swap(&arr[min_idx], &arr[i]); - } -} -``` - -{% endraw %} - -Selection Sort in [C](/languages/c) was written by: - -- vidit624 -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/cobol/index.md b/docs/projects/selection-sort/cobol/index.md deleted file mode 100644 index e43bdcdd00..0000000000 --- a/docs/projects/selection-sort/cobol/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-21 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-04-21 -layout: default -tags: -- cobol -- selection-sort -title: Selection Sort in COBOL -title1: Selection -title2: Sort in COBOL ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. selection-sort. - -data division. -working-storage section. - -01 max-entries constant as 1000. - -01 argument-string pic x(32768). -01 current-token pic x(128). -01 scan-ptr binary-long. - -01 sort-table. - 05 list-size binary-long value 0. - 05 entry-value pic s9(9) occurs 0 to max-entries - depending on list-size. - -01 work-vars. - 05 i binary-long. - 05 j binary-long. - 05 min-index binary-long. - 05 temp pic s9(9). - -01 output-formatting. - 05 display-num pic ---------9. - 05 separator pic x(2) value ", ". - -procedure division. - -main. - perform validate-input - perform parse-input - perform execute-sort - perform display-results - goback. - -validate-input. - accept argument-string from argument-value - if argument-string = spaces - perform show-usage - end-if. - -parse-input. - move 1 to scan-ptr - - perform until scan-ptr > length of argument-string - - move spaces to current-token - - unstring argument-string delimited by "," - into current-token - with pointer scan-ptr - end-unstring - - if function trim(current-token) not = spaces - - if function test-numval(function trim(current-token)) <> 0 - perform show-usage - end-if - - add 1 to list-size - if list-size > max-entries - perform show-usage - end-if - - move function numval(current-token) - to entry-value(list-size) - end-if - - end-perform - - if list-size < 2 - perform show-usage - end-if. - -execute-sort. - perform varying i from 1 by 1 until i >= list-size - - move i to min-index - - compute j = i + 1 - perform varying j from j by 1 until j > list-size - if entry-value(j) < entry-value(min-index) - move j to min-index - end-if - end-perform - - if min-index not = i - move entry-value(i) to temp - move entry-value(min-index) to entry-value(i) - move temp to entry-value(min-index) - end-if - - end-perform. - -display-results. - perform varying i from 1 by 1 until i > list-size - if i > 1 - display separator with no advancing - end-if - - move entry-value(i) to display-num - display function trim(display-num) with no advancing - end-perform - - display space. - -show-usage. - display - 'Usage: please provide a list of at least two integers ' - 'to sort in the format "1, 2, 3, 4, 5"' - stop run. - -``` - -{% endraw %} - -Selection Sort in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/commodore-basic/index.md b/docs/projects/selection-sort/commodore-basic/index.md deleted file mode 100644 index cc61d8f34b..0000000000 --- a/docs/projects/selection-sort/commodore-basic/index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-08 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2023-10-15 -layout: default -tags: -- commodore-basic -- selection-sort -title: Selection Sort in Commodore BASIC -title1: Selection Sort in -title2: Commodore BASIC ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -20 GOSUB 2000: REM Get array -25 REM Error if invalid, not end of input/value, or less that 2 items -30 IF V = 0 OR C >= 0 OR NA < 2 THEN GOTO 200 -40 GOSUB 3000: REM Perform selection sort -50 GOSUB 3500: REM Show array -60 END -200 Q$ = CHR$(34): REM quote -210 PRINT "Usage: please provide a list of at least two integers to sort "; -220 PRINT "in the format "; Q$; "1, 2, 3, 4, 5"; Q$ -230 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -3000 REM Selection sort -3001 REM Source: https://en.wikipedia.org/wiki/Selection_sort#Implementations -3002 REM Inputs: -3003 REM - A contains array to sort -3004 REM - NA contains size of array -3005 REM Outputs: A contains sorted array -3010 IF NA < 2 THEN GOTO 3120 -3020 FOR I = 0 TO NA - 2 -3030 MP = I: REM MP = min position -3040 FOR J = I + 1 TO NA - 1 -3050 IF A(J) < A(MP) THEN MP = J -3060 NEXT J -3070 IF MP = I THEN GOTO 3110 -3080 T = A(I) -3090 A(I) = A(MP) -3100 A(MP) = T -3110 NEXT I -3120 RETURN -3500 REM Display array -3501 REM A contains array -3502 REM NA contains size of array -3510 IF NA < 1 THEN GOTO 3590 -3520 FOR I = 0 TO NA - 1 -3530 S$ = STR$(A(I)) -3540 IF A(I) >= 0 THEN S$ = MID$(S$, 2): REM strip leading space -3550 PRINT S$; -3560 IF I < (NA - 1) THEN PRINT ", "; -3570 NEXT I -3580 PRINT -3590 RETURN - -``` - -{% endraw %} - -Selection Sort in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/euphoria/index.md b/docs/projects/selection-sort/euphoria/index.md deleted file mode 100644 index 5aafe98ac0..0000000000 --- a/docs/projects/selection-sort/euphoria/index.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-19 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2023-02-26 -layout: default -tags: -- euphoria -- selection-sort -title: Selection Sort in Euphoria -title1: Selection Sort -title2: in Euphoria ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts( - STDOUT, - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"\n" - ) - abort(0) -end procedure - -procedure show_list_values(sequence values) - if length(values) > 0 - then - sequence format = repeat_pattern("%d, ", length(values)) - sequence s = sprintf(format[1..$-2], values) - printf(STDOUT, "%s\n", {s}) - end if -end procedure - -function selection_sort(sequence values) - -- Source: https://en.wikipedia.org/wiki/Selection_sort#Implementations - - integer n = length(values) - integer temp - integer min_pos - - for i = 1 to n - 1 - do - min_pos = i - for j = i + 1 to n - do - if values[j] < values[min_pos] - then - min_pos = j - end if - end for - - if min_pos != i - then - temp = values[i] - values[i] = values[min_pos] - values[min_pos] = temp - end if - end for - - return values -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int_list(argv[4]) -sequence values = result[PARSE_INT_LIST_VALUES] -if not result[PARSE_INT_LIST_VALID] or length(values) < 2 -then - usage() -end if - --- Do selection sort and show results -values = selection_sort(values) -show_list_values(values) - -``` - -{% endraw %} - -Selection Sort in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/f-sharp/index.md b/docs/projects/selection-sort/f-sharp/index.md deleted file mode 100644 index fbe193bcaf..0000000000 --- a/docs/projects/selection-sort/f-sharp/index.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- selection-sort -title: Selection Sort in F# -title1: Selection -title2: Sort in F# ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module SelectionSort = - let rec private selectMin = function - | [] -> failwith "empty list" - | [x] -> (x, []) - | x :: xs -> - let minRest, rest = - selectMin xs - - if x <= minRest then - (x, minRest :: rest) - else - (minRest, x :: rest) - - let rec private sort = function - | [] -> [] - | xs -> - let min, rest = selectMin xs - min :: sort rest - - let run numbers = - numbers |> sort |> List.map string |> String.concat ", " |> Ok - -module Result = - let toOption = - function - | Ok x -> Some x - | Error _ -> None - -module Helpers = - let private (|IntList|_|) (s: string) = - let ns = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) - |> Array.toList - |> List.map (fun p -> - match Int32.TryParse(p.Trim()) with - | true, n -> Ok n - | false, _ -> Error $"Invalid integer: '{p}'") - |> List.choose Result.toOption - - if ns.Length >= 2 then Some ns else None - - let parseArgs argv = - match argv with - | [| IntList numbers |] -> Ok numbers - | _ -> Error "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.bind SelectionSort.run - |> Helpers.handleResult - -``` - -{% endraw %} - -Selection Sort in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/go/index.md b/docs/projects/selection-sort/go/index.md deleted file mode 100644 index 79fe646ddb..0000000000 --- a/docs/projects/selection-sort/go/index.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2019-03-18 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2019-03-25 -layout: default -tags: -- go -- selection-sort -title: Selection Sort in Go -title1: Selection -title2: Sort in Go ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "encoding/json" - "fmt" - "math" - "os" - "regexp" - "strconv" - "strings" -) - -func selectionSort(unsorted []int, sorted ...int) []int { - if len(unsorted) <= 0 { - return sorted - } - if len(unsorted) == 1 { - return append(sorted, unsorted...) - } - - min := math.MaxInt32 - minI := -1 - for i, n := range unsorted { - if n < min { - min = n - minI = i - } - } - sorted = append(sorted, min) - unsorted = append(unsorted[:minI], unsorted[minI+1:]...) - return selectionSort(unsorted, sorted...) -} - -func strToSliceInt(strList string) []int { - list := regexp.MustCompile(", ?").Split(strList, -1) - if len(list) < 2 { - exitWithError() - } - var nums []int - for _, num := range list { - n, err := strconv.Atoi(num) - if err != nil { - exitWithError() - } - nums = append(nums, n) - } - return nums -} - -func sliceIntToString(list []int) (out string) { - bytes, _ := json.Marshal(list) - out = strings.Replace(string(bytes), ",", ", ", -1) - out = strings.Trim(out, "[]") - return -} - -func exitWithError() { - fmt.Println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") - os.Exit(1) -} - -func main() { - if len(os.Args) != 2 { - exitWithError() - } - - nums := strToSliceInt(os.Args[1]) - nums = selectionSort(nums) - fmt.Println(sliceIntToString(nums)) -} - -``` - -{% endraw %} - -Selection Sort in [Go](/languages/go) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/haskell/index.md b/docs/projects/selection-sort/haskell/index.md deleted file mode 100644 index 62b068d20f..0000000000 --- a/docs/projects/selection-sort/haskell/index.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -authors: -- Parker Johansen -date: 2018-12-02 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2019-03-26 -layout: default -tags: -- haskell -- selection-sort -title: Selection Sort in Haskell -title1: Selection Sort -title2: in Haskell ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Text.Read -import System.Environment -import System.Exit (exitWith, ExitCode(ExitFailure)) -import Data.List (delete, intercalate) - - -selection :: Ord a => [a] -> [a] -selection xs = selection' [] xs - where selection' :: Ord a => [a] -> [a] -> [a] - selection' ss [] = ss - selection' ss us = selection' (ss ++ [x]) (delete x us) - where x = minimum us - - -headMaybe :: [a] -> Maybe a -headMaybe [] = Nothing -headMaybe (x:xs) = Just x - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - --- Ensure that a list contains at least two elements -verifyListLength :: Ord a => [a] -> Maybe [a] -verifyListLength [] = Nothing -verifyListLength [x] = Nothing -verifyListLength (x:xs) = Just (x:xs) - -listToString :: [Int] -> String -listToString = intercalate ", " . map show - - -main :: IO () -main = do - args <- getArgs - let xs = headMaybe args >>= stringToListMaybe >>= verifyListLength - case xs of - Nothing -> do - putStrLn "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"" - exitWith $ ExitFailure 1 - Just xs -> putStrLn $ listToString $ selection xs - - -``` - -{% endraw %} - -Selection Sort in [Haskell](/languages/haskell) was written by: - -- Parker Johansen - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/index.md b/docs/projects/selection-sort/index.md deleted file mode 100644 index 38643776b3..0000000000 --- a/docs/projects/selection-sort/index.md +++ /dev/null @@ -1,222 +0,0 @@ ---- -date: 2018-12-01 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- selection-sort -title: Selection Sort -title1: Selection -title2: Sort ---- - - - -Welcome to the Selection Sort page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- Parker Johansen -- Ron Zuckerman - -## Description - -Selection sort is an algorithm that operates on two lists, one of sorted elements and one of unsorted. -With each pass, the algorithm finds the smallest item in the unsorted list and moves it -to the front of the sorted list. At the beginning the sorted list is empty, and the algorithm completes -when the unsorted list is empty (meaning that all elements have been moved to the sorted list). - -There is also a variant that uses a single list and moves the elements in place. In this variant, -the sorted elements are just placed at the front of the list rather than in a separate list, and -the algorithm starts each pass with the index of the first unsorted element in the list. - -### Performance - -The performance of sorting algorithms is generally defined in "Big O notation". -If you are not familiar with such notations, please refer to the relevant -article by [Rob Bell][1] or the [Wikipedia][2] entry listed in further readings below. - -| Cases | Big O Notatation | -| ------------ | ---------------- | -| Best case | O(n2) | -| Average case | O(n2) | -| Worst case | O(n2) | - -Selection sort always performs at O(n2). This is because the algorithm's -loops do not depend on the values of the items in the list. That means that even if -the list is already sorted, the full sorting process will still be performed. - -### Examples: Two lists - -In the examples below, each row is a single pass through all elements in the unsorted list. -The element in __bold__ is the one that will be moved to the sorted list after the pass. - -#### "4, 5, 3, 1, 2" - -| Sorted List | Unsorted List | -|-------------|-------------------------------| -| | 4 5 3 __1__ 2 | -| 1 | 4 5 3 __2__ | -| 1 2 | 4 5 __3__ | -| 1 2 3 | __4__ 5 | -| 1 2 3 4 | __5__ | -| 1 2 3 4 5 | | - -#### "3, 5, 4, 1, 2" - -| Sorted List | Unsorted List | -|-------------|-------------------------------| -| | 3 5 4 __1__ 2 | -| 1 | 3 5 4 __2__ | -| 1 2 | __3__ 5 4 | -| 1 2 3 | 5 __4__ | -| 1 2 3 4 | __5__ | -| 1 2 3 4 5 | | - - -### Examples: Single list - -In the examples below, each row is a single pass through all elements in the unsorted list. -The element in __bold__ is the one that will be moved to the end of the sorted section after the pass. - -#### "4, 5, 3, 1, 2" - -- 4 5 3 __1__ 2 -- 1 4 5 3 __2__ -- 1 2 4 5 __3__ -- 1 2 3 __4__ 5 -- 1 2 3 4 __5__ -- 1 2 3 4 5 - -#### "3, 5, 4, 1, 2" - -- 3 5 4 __1__ 2 -- 1 3 5 4 __2__ -- 1 2 __3__ 5 4 -- 1 2 3 5 __4__ -- 1 2 3 4 __5__ -- 1 2 3 4 5 - -[1]: https://robbell.io/2009/06/a-beginners-guide-to-big-o-notation -[2]: https://en.wikipedia.org/wiki/Big_O_notation - - -## Requirements - -Write a sample program that takes a list of numbers in the format "4, 5, 3, 1, 2". -It should then sort the numbers and output them: - -```console -$ ./selection-sort.lang "4, 5, 3, 1, 2" -1, 2, 3, 4, 5 -``` - -The solution should handle duplicate elements - -```console -$ ./selection-sort.lang "4, 5, 3, 1, 4, 2" -1, 2, 3, 4, 4, 5 -``` - -In addition, there should be some error handling for situations where the user -doesn't supply correct input. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Selection Sort. -In order to keep things simple, we split up the testing as follows: - -- Selection Sort Valid Tests -- Selection Sort Invalid Tests - -### Selection Sort Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Sample Input | "4, 5, 3, 1, 2" | "1, 2, 3, 4, 5" | -| Sample Input: With Duplicate | "4, 5, 3, 1, 4, 2" | "1, 2, 3, 4, 4, 5" | -| Sample Input: Already Sorted | "1, 2, 3, 4, 5" | "1, 2, 3, 4, 5" | -| Sample Input: Reverse Sorted | "9, 8, 7, 6, 5, 4, 3, 2, 1" | "1, 2, 3, 4, 5, 6, 7, 8, 9" | - -### Selection Sort Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Invalid Input: Not A List | "1" | -| Invalid Input: Wrong Format | "4 5 3" | - -All of these tests should output the following: - -``` -Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -``` - - -## Articles - -There are 32 articles: - -- [Selection Sort in ALGOL 60](/projects/selection-sort/algol60) -- [Selection Sort in ALGOL 68](/projects/selection-sort/algol68) -- [Selection Sort in AWK](/projects/selection-sort/awk) -- [Selection Sort in Bash](/projects/selection-sort/bash) -- [Selection Sort in Beef](/projects/selection-sort/beef) -- [Selection Sort in C](/projects/selection-sort/c) -- [Selection Sort in C#](/projects/selection-sort/c-sharp) -- [Selection Sort in C++](/projects/selection-sort/c-plus-plus) -- [Selection Sort in COBOL](/projects/selection-sort/cobol) -- [Selection Sort in Commodore BASIC](/projects/selection-sort/commodore-basic) -- [Selection Sort in Euphoria](/projects/selection-sort/euphoria) -- [Selection Sort in F#](/projects/selection-sort/f-sharp) -- [Selection Sort in Go](/projects/selection-sort/go) -- [Selection Sort in Haskell](/projects/selection-sort/haskell) -- [Selection Sort in Java](/projects/selection-sort/java) -- [Selection Sort in JavaScript](/projects/selection-sort/javascript) -- [Selection Sort in Julia](/projects/selection-sort/julia) -- [Selection Sort in Kotlin](/projects/selection-sort/kotlin) -- [Selection Sort in Mathematica](/projects/selection-sort/mathematica) -- [Selection Sort in Octave](/projects/selection-sort/octave) -- [Selection Sort in PHP](/projects/selection-sort/php) -- [Selection Sort in Pascal](/projects/selection-sort/pascal) -- [Selection Sort in Perl](/projects/selection-sort/perl) -- [Selection Sort in PowerShell](/projects/selection-sort/powershell) -- [Selection Sort in Python](/projects/selection-sort/python) -- [Selection Sort in Ruby](/projects/selection-sort/ruby) -- [Selection Sort in Rust](/projects/selection-sort/rust) -- [Selection Sort in Swift](/projects/selection-sort/swift) -- [Selection Sort in Tcl](/projects/selection-sort/tcl) -- [Selection Sort in TypeScript](/projects/selection-sort/typescript) -- [Selection Sort in Visual Basic](/projects/selection-sort/visual-basic) -- [Selection Sort in m4](/projects/selection-sort/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/selection-sort/java/index.md b/docs/projects/selection-sort/java/index.md deleted file mode 100644 index c74052033e..0000000000 --- a/docs/projects/selection-sort/java/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Jeremy Grifski -- Tim Lange -date: 2019-10-15 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2022-10-10 -layout: default -tags: -- java -- selection-sort -title: Selection Sort in Java -title1: Selection -title2: Sort in Java ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.ArrayList; - -public class SelectionSort { - - public static void main(String[] args) { - try { - ArrayList listOfNumbers = new ArrayList<>(); - String[] NumberArray = args[0].split(","); - for (String Number : NumberArray) { - listOfNumbers.add(Integer.parseInt(Number.trim())); - } - if (listOfNumbers.size() >= 2) { - StringBuilder output = new StringBuilder(); - ArrayList SortedList = sort(listOfNumbers); - - for (Integer Number : SortedList) { - if (SortedList.indexOf(Number) == 0) { - output.append(Number); - } else { - output.append(", ").append(Number); - } - } - System.out.println(output); - } else { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } - } catch (Exception e) { - System.out.println( - "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - } - } - - private static ArrayList sort(ArrayList list) { - for (int i = 0; i < list.size() - 1; i++) { - for (int j = i + 1; j < list.size(); j++) { - if (list.get(j) < list.get(i)) { - int memory = list.get(i); - list.set(i, list.get(j)); - list.set(j, memory); - } - } - } - return list; - } -} -``` - -{% endraw %} - -Selection Sort in [Java](/languages/java) was written by: - -- Jeremy Grifski -- Tim Lange - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/javascript/index.md b/docs/projects/selection-sort/javascript/index.md deleted file mode 100644 index c2397d8989..0000000000 --- a/docs/projects/selection-sort/javascript/index.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -authors: -- mericleac -- rzuckerm -date: 2019-10-16 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2025-05-04 -layout: default -tags: -- javascript -- selection-sort -title: Selection Sort in JavaScript -title1: Selection Sort -title2: in JavaScript ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const selectionSort = (list) => { - // Iterate through the list - for (let i = 0; i < list.length; i++) { - // Set a default of the first value - let min = list[i]; - let minIdx = i; - // Iterate through the rest of the list - for (let j = i; j < list.length; j++) { - if (list[j] < min) { - // We found a new minimum - min = list[j]; - minIdx = j; - } - } - // Swap the minimum with the current index - const temp = list[i]; - list[i] = min; - list[minIdx] = temp; - } - return list -}; - -const exit = () => { - console.log('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - process.exit(); -} - -const main = (input) => { - try { - const arr = input.split(", "); - arr.length <= 1 ? exit() : console.log(selectionSort(arr).join(", ")); - } catch { - exit(); - } -} - -main(process.argv[2]); - -``` - -{% endraw %} - -Selection Sort in [JavaScript](/languages/javascript) was written by: - -- mericleac -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/julia/index.md b/docs/projects/selection-sort/julia/index.md deleted file mode 100644 index 71017190a5..0000000000 --- a/docs/projects/selection-sort/julia/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- sniklas142 -date: 2020-10-01 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2020-10-01 -layout: default -tags: -- julia -- selection-sort -title: Selection Sort in Julia -title1: Selection -title2: Sort in Julia ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Julia](/languages/julia) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```julia -#!/usr/bin/julia - -function SelectionSort(arr) - l = length(arr) - sorted_list = [] - for i = 1:l - m = minimum(arr) - push!(sorted_list,m) - deleteat!(arr, findfirst(x->x==m,arr)) - end - return sorted_list -end - -function error() - println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") -end - -function HandleInput(inp) - - a = split(inp,",") - a = map(x->split(x," "),a) - a = map(x->last(x),a) - numbers = map(x->parse(Int,x),a) - if length(numbers) == 1 - error() - exit() - end - return numbers - -end - -function PrintOutput(out) - for i = 1:length(out) - print(out[i]) - if i != length(out) - print(", ") - end - end - println() -end - -try - - n = HandleInput(ARGS[1]) - sorted = SelectionSort(n) - PrintOutput(sorted) - -catch e - error() -end - - - -``` - -{% endraw %} - -Selection Sort in [Julia](/languages/julia) was written by: - -- sniklas142 - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/kotlin/index.md b/docs/projects/selection-sort/kotlin/index.md deleted file mode 100644 index 71ee8686b1..0000000000 --- a/docs/projects/selection-sort/kotlin/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2025-10-06 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2025-10-06 -layout: default -tags: -- kotlin -- selection-sort -title: Selection Sort in Kotlin -title1: Selection Sort -title2: in Kotlin ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Kotlin](/languages/kotlin) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```kotlin -import kotlin.system.exitProcess - -fun main(args: Array) { - val nums: IntArray = errorChecking(args) - selectionSort(nums) - outputList(nums) -} - -fun usageError() { - println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"") -} - -fun errorChecking(args: Array): IntArray { - val nums: IntArray - try { - nums = args[0].split(", ").map { it.toInt() }.toIntArray() - } catch (e: Exception) { - usageError() - exitProcess(1) - } - if (nums.size < 2) { - usageError() - exitProcess(1) - } - return nums -} - -fun selectionSort(nums: IntArray) { - for (i in 0 until nums.count() - 1) { - - var smallestIndex: Int = i - for (j in i + 1 until nums.count()) { - if (nums[j] < nums[smallestIndex]) { - smallestIndex = j - } - } - - var swap: Int = nums[i] - nums[i] = nums[smallestIndex] - nums[smallestIndex] = swap - } -} - -fun outputList(nums: IntArray) { - for (i in nums.indices) { - if (i == nums.count() - 1) { - println("${nums[i]}") - return - } - print("${nums[i]}, ") - } -} - -``` - -{% endraw %} - -Selection Sort in [Kotlin](/languages/kotlin) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/m4/index.md b/docs/projects/selection-sort/m4/index.md deleted file mode 100644 index 2c69aab376..0000000000 --- a/docs/projects/selection-sort/m4/index.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-03 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2025-10-03 -layout: default -tags: -- m4 -- selection-sort -title: Selection Sort in m4 -title1: Selection -title2: Sort in m4 ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl array_swap(var_name, idx1, idx2): -dnl t = var_name[idx1] -dnl var_name[idx1] = var_name[idx2] -dnl var_name[idx] = t -define(`array_swap', -`pushdef(`t', array_get(`$1', `$2'))dnl -array_set(`$1', `$2', array_get(`$1', `$3'))dnl -array_set(`$1', `$3', t)dnl -popdef(`t')'dnl -) - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname[length] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname[length]] = arg -dnl varname[length] = varname[length] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl show_int_list(varname): -dnl for i = 0 to n-1: -dnl if i > 0: -dnl Output ", " -dnl Output varname[i] -define(`show_int_list', `_show_int_list(`$1', 0)') -define(`_show_int_list', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`ifelse(eval($2 > 0), 1, `, ')dnl -array_get(`$1', $2)`'dnl -_show_int_list(`$1', incr($2))'`'dnl -)'dnl -) - -dnl Reference: https://en.wikipedia.org/wiki/Selection_sort#Implementations -dnl selection_sort(varname): -dnl n = varname[length] -dnl for i = 0 to n-2: -dnl jmin = i -dnl for j = i+1 to n-1: -dnl if varname[j] < varname[jmin]: -dnl jmin = j -dnl if jmin != i: -dnl swap(varname, i, jmin) -define(`selection_sort', `_selection_sort_outer(`$1', 0)') -define(`_selection_sort_outer', -`ifelse(eval($2 < decr(array_get(`$1', `length'))), 1, -`_selection_sort_inner(`$1', `$2', incr($2), `$2')dnl -_selection_sort_outer(`$1', incr($2))'dnl -)'dnl -) -dnl varname=$1, i=$2, j=$3, jmin=$4 -define(`_selection_sort_inner', -`ifelse(eval($3 >= array_get(`$1', `length')), 1, -`ifelse(eval($4 != $2), 1, array_swap(`$1', `$2', `$4'))', -`ifelse(eval(array_get(`$1', $3) < array_get(`$1', $4)), 1, -`_selection_sort_inner(`$1', `$2', incr($3), `$3')', -`_selection_sort_inner(`$1', `$2', incr($3), `$4')'dnl -)'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !parse_int_list(`arr', ARGV1)), 1, `show_usage()')dnl -ifelse(eval(array_get(`arr', `length') < 2), 1, `show_usage()')dnl -selection_sort(`arr')dnl -show_int_list(`arr') - -``` - -{% endraw %} - -Selection Sort in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/mathematica/index.md b/docs/projects/selection-sort/mathematica/index.md deleted file mode 100644 index 8c8cd515ca..0000000000 --- a/docs/projects/selection-sort/mathematica/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-19 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2023-01-19 -layout: default -tags: -- mathematica -- selection-sort -title: Selection Sort in Mathematica -title1: Selection Sort -title2: in Mathematica ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* Implement by recursion. Mathematica doesn't really have a sense of modifying things 'in place', - so there isn't much value in trying to simulate it. Instead, use Mathematica to focus on the algorithm itself: *) - -selectionSort[{}] := {} -selectionSort[l_List] := Module[ - {i = First[Ordering[l, 1]]}, (* find the index of the lowest-valued element *) - Join[ (* build a new list by *) - Take[l, {i}],(* taking that lowest-valued element *) - selectionSort[Drop[l, {i}]]]] (* and sorting the rest of the list *) - -(* The outer function provides the 'user interface': *) - -selectionSortMain = l \[Function] - Module[{e = "Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""}, - Catch[ - StringRiffle[ - selectionSort @ - (* list must have more than one element *) - If[Length[#] > 1, #, Throw[e]] & @ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct arguments to bubble sort: list of items *) - StringSplit[l, ", "], - {-1} (* at each leaf *)], - ", "]]]; - - -(* Valid Tests *) - -Print /@ selectionSortMain /@ { - "4, 5, 3, 1, 2", - "4, 5, 3, 1, 4, 2", - "1, 2, 3, 4, 5", - "9, 8, 7, 6, 5, 4, 3, 2, 1" - }; - - -(* Invalid Tests *) - -selectionSortMain[""] -selectionSortMain["1"] -selectionSortMain["4 5 3"] - -``` - -{% endraw %} - -Selection Sort in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/octave/index.md b/docs/projects/selection-sort/octave/index.md deleted file mode 100644 index ff9d92d312..0000000000 --- a/docs/projects/selection-sort/octave/index.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-12-09 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2023-12-09 -layout: default -tags: -- octave -- selection-sort -title: Selection Sort in Octave -title1: Selection Sort -title2: in Octave ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Octave](/languages/octave) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```octave -function selection_sort() - %input validation - usage = 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - arg_list = argv(); - nargin = length(arg_list); - if nargin == 0 - %if there was no input - disp(usage); - return; - end - - array_string = arg_list{1}; - array_size = sum(array_string == ',') + 1; - if array_size < 2 - disp(usage); - return; - end - - %build array - array = str2num(array_string); - if length(array) ~= array_size || any(mod(array, 1) ~= 0) - disp(usage); - return; - end - - %selection sort in ascending order - sorted = []; - while ~isempty(array) - x = min(array); - sorted = [ sorted array(array==x) ]; - array(array==x) = []; - end - - %convert to string - result_string = num2str(sorted); - - %replace space with ', ' - result_string = regexprep(result_string, '\s+', ', '); - disp(result_string); -end - -``` - -{% endraw %} - -Selection Sort in [Octave](/languages/octave) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/pascal/index.md b/docs/projects/selection-sort/pascal/index.md deleted file mode 100644 index d402e6c61f..0000000000 --- a/docs/projects/selection-sort/pascal/index.md +++ /dev/null @@ -1,173 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-21 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2025-07-21 -layout: default -tags: -- pascal -- selection-sort -title: Selection Sort in Pascal -title1: Selection Sort -title2: in Pascal ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program SelectionSort; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - StrUtils, - SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) < 2 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function FormatIntegerList(const List: TIntegerList): string; -var - i: integer; -begin - Result := ''; - for i := 0 to List.Count - 1 do - begin - if i > 0 then - Result += ', '; - Result += IntToStr(List[i]); - end; -end; - -procedure SelectionSort(List: TIntegerList); -var - startIdx, endIdx, i, minIdx, maxIdx: integer; - - procedure SwapElements(Index1, Index2: integer); - var - Temp: integer; - begin - Temp := List[Index1]; - List[Index1] := List[Index2]; - List[Index2] := Temp; - end; - -begin - startIdx := 0; - endIdx := List.Count - 1; - - while startIdx < endIdx do - begin - minIdx := startIdx; - maxIdx := startIdx; - - for i := startIdx to endIdx do - begin - if List[i] < List[minIdx] then - minIdx := i; - if List[i] > List[maxIdx] then - maxIdx := i; - end; - - // Swap min to start - if minIdx <> startIdx then - begin - SwapElements(startIdx, minIdx); - - // Adjust maxIdx if it was swapped - if maxIdx = startIdx then - maxIdx := minIdx; - end; - - // Swap max to end - if maxIdx <> endIdx then - SwapElements(endIdx, maxIdx); - - Inc(startIdx); - Dec(endIdx); - end; -end; - -var - rawArg: string; - numbers: TIntegerList; -begin - if ParamCount <> 1 then - ShowUsage; - - rawArg := ParamStr(1); - numbers := ParseIntegerList(rawArg); - try - SelectionSort(numbers); - Writeln(FormatIntegerList(numbers)); - finally - numbers.Free; - end; -end. - -``` - -{% endraw %} - -Selection Sort in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/perl/index.md b/docs/projects/selection-sort/perl/index.md deleted file mode 100644 index 8e8357467f..0000000000 --- a/docs/projects/selection-sort/perl/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- Mr Anand Somashekhara Rao Somavarapete -- Ștefan-Iulian Alecu -date: 2023-10-03 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- perl -- selection-sort -title: Selection Sort in Perl -title1: Selection -title2: Sort in Perl ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Perl](/languages/perl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```perl -#!/usr/bin/env perl -use v5.42; - -use feature qw/keyword_any/; -no warnings 'experimental::keyword_any'; - -sub usage { - say 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'; - exit; -} - -sub parse_list ($s) { - return undef unless defined $s; - - my @vals = split /\s*,\s*/, $s; - - return undef if @vals < 2; - return undef if any { $_ !~ /\A-?\d+\z/ } @vals; - - return [ map 0 + $_, @vals ]; -} - -sub selection_sort ($a) { - my $n = @$a; - - for my $i ( 0 .. $n - 2 ) { - my $min = $i; - - for my $j ( $i + 1 .. $n - 1 ) { - $min = $j if $a->[$j] < $a->[$min]; - } - - ( $a->[$i], $a->[$min] ) = ( $a->[$min], $a->[$i] ) if $i != $min; - } - - return $a; -} - -my ($input) = @ARGV; -my $a = parse_list($input) or usage(); - -selection_sort($a); -say join ', ', @$a; - -``` - -{% endraw %} - -Selection Sort in [Perl](/languages/perl) was written by: - -- Mr Anand Somashekhara Rao Somavarapete -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/php/index.md b/docs/projects/selection-sort/php/index.md deleted file mode 100644 index 0f037cd54d..0000000000 --- a/docs/projects/selection-sort/php/index.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -authors: -- Gurmeet -- Jeremy Grifski -date: 2019-10-16 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2022-05-09 -layout: default -tags: -- php -- selection-sort -title: Selection Sort in PHP -title1: Selection -title2: Sort in PHP ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - - -Welcome to the [Selection Sort](/projects/selection-sort) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -# Source: https://en.wikipedia.org/wiki/Selection_sort#Implementations -function Invoke-SelectionSort([array]$Values) { - $n = $Values.Length - for ($i = 0; $i -lt ($n - 1); $i++) { - $jMin = $i - for ($j = $i + 1; $j -lt $n; $j++) { - if ($Values[$j] -lt $Values[$jMin]) { - $jMin = $j - } - } - - if ($jMin -ne $i) { - $Values[$i], $Values[$jMin] = $Values[$jMin], $Values[$i] - } - } -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $values = Parse-IntList $args[0] - if ($values.Length -lt 2) { - Show-Usage - } -} catch { - Show-Usage -} - -Invoke-SelectionSort $values -Write-Host ($values -join ', ') - -``` - -{% endraw %} - -Selection Sort in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/python/index.md b/docs/projects/selection-sort/python/index.md deleted file mode 100644 index fcc42ecd50..0000000000 --- a/docs/projects/selection-sort/python/index.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -authors: -- Haseeb Majid -- Jeremy Grifski -- Parker Johansen -- rzuckerm -date: 2018-12-23 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2023-05-15 -layout: default -tags: -- python -- selection-sort -title: Selection Sort in Python -title1: Selection Sort -title2: in Python ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - - -def selection_sort(xs, sorted_xs=None): - sorted_xs = sorted_xs or [] - if len(xs) <= 0: - return sorted_xs - x = min(xs) - sorted_xs.append(x) - xs.remove(x) - return selection_sort(xs, sorted_xs) - - -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] - - -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) - - -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(selection_sort(xs)) - except (IndexError, ValueError): - exit_with_error() - - -if __name__ == "__main__": - main(sys.argv[1:]) - -``` - -{% endraw %} - -Selection Sort in [Python](/languages/python) was written by: - -- Jeremy Grifski -- Parker Johansen - -This article was written by: - -- Haseeb Majid -- Jeremy Grifski -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -Let's dig into the code a bit. The following sections break -down the Selection Sort in Python functionality. - -### The Main Function - -Breaking down this solution bottom up, - -```python -if __name__ == "__main__": - main(sys.argv[1:]) -``` - -This bit of code checks to see if this is the `main` module run. If it is it then calls the `main` -function and passes user input to it. In this case the user input would be a string of numbers to sort -like so: `"2, 1, 10, 5, 3"`. - -```python -def main(args): - try: - xs = input_list(args[0]) - if len(xs) <= 1: - exit_with_error() - print(selection_sort(xs)) - except (IndexError, ValueError): - exit_with_error() -``` - -This is the `main` function of this file. It parses the input, then calls our selection sort -function (and prints the results). It also deals with any errors raised. - -### Transform Input Parameters - -```python -def input_list(list_str): - return [int(x.strip(" "), 10) for x in list_str.split(',')] -``` - -This function takes a string like `"2, 1, 10, 5, 3"`, and turns into a list of numbers. -It does this using a list comprehension, first we need to convert our string into a -list `list_str.split(',')` which is a list of strings split by comma (`,`). -So our original input string becomes `["2", " 1", " 10", " 5", " 3"]`. Then for each -element in the list `for x in ...` , we do something to it. - -In this example we convert it into a decimal integer, `int(x.strip(" "), 10)`. Then `x.strip(" ")`, -removes any whitespace so `" 1"` becomes `"1"`. Then `int("1", 10)` -converts the string `"1"` into a decimal number in this case `1`. This is done -for every item in the list so our original input of `"2, 1, 10, 5, 3"` becomes `[2, 1, 10, 5, 3]`. - -### Throw Errors - -```python -def exit_with_error(): - print('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"') - sys.exit(1) -``` - -This function prints a message and then exits the script with an error, `sys.exit(1)`. -If any non-zero value is returned then the program didn't complete properly. This function is called -if the user input isn't correct. - -### Selection Sort - -```python -def selection_sort(xs, sorted_xs=None): - sorted_xs = sorted_xs or [] - if len(xs) <= 0: - return sorted_xs - x = min(xs) - sorted_xs.append(x) - xs.remove(x) - return selection_sort(xs, sorted_xs) -``` - -Now onto the main part of the program, this is the function that actually sorts our list. -The `selection_sort()` takes two parameters `xs` which is the unsorted list and `sorted_xs` -which funnily enough is the current sorted list. When you first call the `selection_sort()` -function you then pass it to your unsorted list as `sorted_xs=None` by default. - -If the `sorted_xs` value is set (not `None`) then we make `sorted_xs` equal itself, else -`sorted_xs` equals `[]` (an empty list). You should never make a mutable object a default -argument in Python as you get can get unexpected result. You can get more -information [here](http://effbot.org/zone/default-values.htm). Therefore we set -`sorted_xs=None` instead of `sorted_xs=[]`. - -Then we check if xs is empty (`<=0`), which would mean we have sorted every element, -then we return the `sorted_xs` which is the sorted this. We can do this because -as we sort element we move them from `xs` to `sorted_xs` ( items get removed from the `xs` list). - -If `xs` still has items then that means we haven't completely sorted the list. -We found the smallest value in `x = min(xs)`. We append that value to `sorted_xs` and then we -remove it from the `xs` list. Finally, we call the selection sort function with the new `xs` and -`sorted_xs` values. This repeats until `xs` is empty and you are left with a completely sorted -`sorted_xs`. - -Taking a look at a simple example where we want to sort `[5, 1, 3]`. - -1st: - -* Call `selection_sort([5, 1, 3])` -* `xs = [5, 1, 3]`, `sorted_xs=[]` -* Minimum value is `1` -* `xs = [5, 3]`, `sorted_xs = [1]` -* `selection_sort([5, 3], [1])` - -2nd: - -* `xs = [5, 3]`, `sorted_xs = [1]` -* Minimum value is `3` -* `xs = [5]`, `sorted_xs = [1, 3]` -* `selection_sort([5], [1, 3])` - -3rd: - -* `xs = [5]`, `sorted_xs = [1, 3]` -* Minimum value is `5` -* `xs = []`, `sorted_xs = [1, 3, 5]` -* `selection_sort([], [1, 3, 5])` - -4th: - -* `xs = []`, `sorted_xs = [1, 3, 5]` -* `len(xs) <= 0`, as we have 0 elements -* So we return `sorted_xs = [1, 3, 5]` - - -## How to Run the Solution - -If we want to run this program, we should probably download a copy of [Selection Sort in Python](https://github.com/TheRenegadeCoder/sample-programs/blob/main/archive/p/python/selection_sort.py). -After that, we should make sure we have the [latest Python interpreter](https://www.python.org/downloads/). From there, we can run the following command in the terminal: - -`python selection-sort.py "3, 2, 10, 6, 1, 7"` - -Alternatively, we can copy the solution into an [online Python interpreter](https://www.online-python.com/) and hit run. diff --git a/docs/projects/selection-sort/ruby/index.md b/docs/projects/selection-sort/ruby/index.md deleted file mode 100644 index fba73e02f9..0000000000 --- a/docs/projects/selection-sort/ruby/index.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -authors: -- Ahmed -- Ștefan-Iulian Alecu -date: 2025-10-29 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- ruby -- selection-sort -title: Selection Sort in Ruby -title1: Selection -title2: Sort in Ruby ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -def parse_input(str) - return if str.to_s.strip.empty? - - nums = str.split(",").map { Integer(it.strip, exception: false) } - return if nums.any?(nil?) || nums.length < 2 - - nums -end - -class Array - def selection_sort - arr = dup - sorted = [] - - until arr.empty? - min_index = arr.each_index.min_by { |i| arr[i] } - sorted << arr.delete_at(min_index) - end - - sorted - end -end - -USAGE = 'Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"' - -input = parse_input(ARGV.first) -abort(USAGE) unless input - -puts input.selection_sort.join(", ") - -``` - -{% endraw %} - -Selection Sort in [Ruby](/languages/ruby) was written by: - -- Ahmed -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/rust/index.md b/docs/projects/selection-sort/rust/index.md deleted file mode 100644 index 7c698d6296..0000000000 --- a/docs/projects/selection-sort/rust/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-06 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- rust -- selection-sort -title: Selection Sort in Rust -title1: Selection -title2: Sort in Rust ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\""); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -fn selection_sort(arr: &mut Vec) { - // Source: https://en.wikipedia.org/wiki/Selection_sort#Implementations - for i in 0..(arr.len() - 1) { - let mut min_pos = i; - for j in (i + 1)..arr.len() { - if arr[j] < arr[min_pos] { - min_pos = j; - } - } - - if min_pos != i { - arr.swap(min_pos, i); - } - } -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to list of integers - let mut arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if list too small - if arr.len() < 2 { - usage(); - } - - selection_sort::(&mut arr); - println!("{arr:?}"); -} - -``` - -{% endraw %} - -Selection Sort in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/swift/index.md b/docs/projects/selection-sort/swift/index.md deleted file mode 100644 index 0c1de4f9da..0000000000 --- a/docs/projects/selection-sort/swift/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- selection-sort -- swift -title: Selection Sort in Swift -title1: Selection -title2: Sort in Swift ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = """ - Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" - """ - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseIntegers(from args: [String]) -> [Int]? { - guard args.count == 2 else { return nil } - - let parts = args[1].split(separator: ",", omittingEmptySubsequences: false) - let values = parts.compactMap { Int($0.trimmed) } - - guard values.count == parts.count, - values.count >= 2 - else { - return nil - } - - return values -} - -extension MutableCollection where Self: BidirectionalCollection { - mutating func selectionSort(by areInIncreasingOrder: (Element, Element) -> Bool) { - guard count > 1 else { return } - - var i = startIndex - - while i != index(before: endIndex) { - var minIndex = i - var j = index(after: i) - - while j != endIndex { - if areInIncreasingOrder(self[j], self[minIndex]) { - minIndex = j - } - j = index(after: j) - } - - if minIndex != i { - swapAt(i, minIndex) - } - - i = index(after: i) - } - } -} - -guard var numbers = parseIntegers(from: CommandLine.arguments) else { - print(usage) - exit(1) -} - -numbers.selectionSort(by: <) - -print(numbers.map(String.init).joined(separator: ", ")) - -``` - -{% endraw %} - -Selection Sort in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/tcl/index.md b/docs/projects/selection-sort/tcl/index.md deleted file mode 100644 index 542f77b177..0000000000 --- a/docs/projects/selection-sort/tcl/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- selection-sort -- tcl -title: Selection Sort in Tcl -title1: Selection -title2: Sort in Tcl ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts stderr {Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"} - exit 1 -} - -proc parseList {s} { - set tokens [split [string trim $s] ","] - if {[llength $tokens] < 2} { usage } - - set result {} - - set result {} - foreach token $tokens { - set t [string trim $token] - if {$t eq "" || [catch {expr {int($t)}} val]} usage - lappend result $val - } - return $result -} - -proc isSorted {lst} { - set prev [lindex $lst 0] - foreach x [lrange $lst 1 end] { - if {$x < $prev} {return 0} - set prev $x - } - return 1 -} - -proc selectionSort {lstVar} { - upvar 1 $lstVar lst - set n [llength $lst] - - for {set i 0} {$i < $n - 1} {incr i} { - set minIdx $i - for {set j [expr {$i + 1}]} {$j < $n} {incr j} { - if {[lindex $lst $j] < [lindex $lst $minIdx]} { - set minIdx $j - } - } - if {$minIdx != $i} { - set temp [lindex $lst $i] - lset lst $i [lindex $lst $minIdx] - lset lst $minIdx $temp - } - } -} - -proc formatList {lst} { return [join $lst ", "] } - -if {$argc != 1} { usage } - -set numbers [parseList [lindex $argv 0]] - -if {![isSorted $numbers]} { - selectionSort numbers -} - -puts [formatList $numbers] - -``` - -{% endraw %} - -Selection Sort in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/typescript/index.md b/docs/projects/selection-sort/typescript/index.md deleted file mode 100644 index 7a7b698e09..0000000000 --- a/docs/projects/selection-sort/typescript/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- Meet Thakur -date: 2024-10-13 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2024-10-13 -layout: default -tags: -- selection-sort -- typescript -title: Selection Sort in TypeScript -title1: Selection Sort -title2: in TypeScript ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -function selectionSort(arr: number[]): number[] { - const n = arr.length; - - for (let i = 0; i < n - 1; i++) { - let minIndex = i; - - for (let j = i + 1; j < n; j++) { - if (arr[j] < arr[minIndex]) { - minIndex = j; - } - } - - if (minIndex !== i) { - const temp = arr[i]; - arr[i] = arr[minIndex]; - arr[minIndex] = temp; - } - } - - return arr; -} - -function displayUsage() { - console.log('Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5"'); -} - -const args = process.argv.slice(2); - -if (args.length === 0) { - displayUsage(); - process.exit(1); -} - -const inputString = args.join(' '); -if (inputString.trim() === '') { - displayUsage(); - process.exit(1); -} - -if (args.length === 1 && !args[0].includes(',')) { - displayUsage(); - process.exit(1); -} - -const numbers = inputString.split(',').map(arg => parseFloat(arg.trim())).filter(num => !isNaN(num)); - -if (numbers.length < 2) { - displayUsage(); - process.exit(1); -} - -const sortedNumbers = selectionSort(numbers); - -console.log(sortedNumbers.join(', ')); - -``` - -{% endraw %} - -Selection Sort in [TypeScript](/languages/typescript) was written by: - -- Meet Thakur - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/selection-sort/visual-basic/index.md b/docs/projects/selection-sort/visual-basic/index.md deleted file mode 100644 index 56b5d2f7d0..0000000000 --- a/docs/projects/selection-sort/visual-basic/index.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: selection-sort-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- selection-sort -- visual-basic -title: Selection Sort in Visual Basic -title1: Selection Sort -title2: in Visual Basic ---- - - - -Welcome to the [Selection Sort](/projects/selection-sort) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module SelectionSort - - - Public Function Sort(Of T)(input As IEnumerable(Of T), - Optional compare As IComparer(Of T) = Nothing) As List(Of T) - - If compare Is Nothing Then - compare = Comparer(Of T).Default - End If - - Dim list As New List(Of T)(input) - - If list.Count < 2 Then - Return list - End If - - SelectionSortInternal(list, compare) - - Return list - - End Function - - - Private Sub SelectionSortInternal(Of T)(list As List(Of T), comparer As IComparer(Of T)) - - For i As Integer = 0 To list.Count - 2 - - Dim minIndex As Integer = FindMinIndex(list, i, comparer) - - If minIndex <> i Then - Swap(list, i, minIndex) - End If - - Next - - End Sub - - - Private Function FindMinIndex(Of T)(list As List(Of T), - startIndex As Integer, - comparer As IComparer(Of T)) As Integer - - Dim minIndex As Integer = startIndex - - For j As Integer = startIndex + 1 To list.Count - 1 - - If comparer.Compare(list(j), list(minIndex)) < 0 Then - minIndex = j - End If - - Next - - Return minIndex - - End Function - - Private Sub Swap(Of T)(list As List(Of T), i As Integer, j As Integer) - Dim temp = list(i) - list(i) = list(j) - list(j) = temp - End Sub - - - Private Sub ShowUsage() - - Console.WriteLine( - "Usage: please provide a list of at least two integers to sort " & - "in the format ""1, 2, 3, 4, 5""" - ) - - Environment.Exit(1) - - End Sub - - - Public Sub Main(args As String()) - - If args.Length <> 1 Then - ShowUsage() - End If - - Dim parts = args(0).Split(","c, StringSplitOptions.RemoveEmptyEntries) - - Dim numbers As New List(Of Integer) - - For Each p In parts - - Dim value As Integer - - If Not Integer.TryParse(p.Trim(), value) Then - ShowUsage() - End If - - numbers.Add(value) - - Next - - If numbers.Count < 2 Then - ShowUsage() - End If - - Dim sorted = Sort(numbers) - - Console.WriteLine(String.Join(", ", sorted)) - - End Sub - -End Module -``` - -{% endraw %} - -Selection Sort in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/algol60/index.md b/docs/projects/transpose-matrix/algol60/index.md deleted file mode 100644 index 413879fa7d..0000000000 --- a/docs/projects/transpose-matrix/algol60/index.md +++ /dev/null @@ -1,313 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-04-18 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-04-18 -layout: default -tags: -- algol60 -- transpose-matrix -title: Transpose Matrix in ALGOL 60 -title1: Transpose Matrix -title2: in ALGOL 60 ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring( - 1, - "Usage: please enter the dimension of the matrix and the " - "serialized matrix\n" - ); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - comma maps to 13 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - "," maps to 17 - - null byte maps to 18 - - invalid byte maps 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ,", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else if ch = 17 then ch := 13 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch, allowComma); - value allowComma; - integer result, ch; - boolean allowComma; - begin - boolean valid, commaFound; - integer s; - - result := 0; - valid := false; - commaFound := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment If comma not allowed, ignore characters until end - input. If comma allowed, ignore characters until comma - or end of input. Indicate if comma found; - ignoreloop: - if !(ch = -1 | (allowComma & ch = 13)) then - begin - if ch != 12 & ch != 13 then valid := false; - if ch = 13 then - begin - commaFound := true; - if !allowComma then valid := false - end; - - ch := indigit; - goto ignoreloop - end; - - comment If comma found, indicate last character is comma; - if commaFound then ch := 13; - - inValidInteger := valid - end inValidInteger; - - comment Returns length of array if valid, -1 otherwise; - integer procedure inIntegerArray(arr, maxLen); - value maxLen; - integer array arr; - integer maxLen; - begin - integer arrLen, val, ch; - boolean valid; - - arrLen := 0; - - comment Get value with possible comma (13). Indicate invalid, - if invalid integer. Otherwise, append value to array if - no invalid values and there is room; - itemloop: - if !inValidInteger(val, ch, true) then arrLen := -1 - else if arrLen >= 0 & arrLen < maxLen then - begin - arrLen := arrLen + 1; - arr[arrLen] := val - end; - - comment Repeat until end of input; - if ch != -1 then goto itemloop; - - inIntegerArray := arrLen - end inIntegerArray; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Output integer array; - procedure outIntegerArray(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i; - for i := 1 step 1 until arrLen do - begin - if i > 1 then outstring(1, ", "); - outIntegerNoSpace(arr[i]) - end; - - if arrLen > 0 then outstring(1, "\n") - end outIntegerArray; - - procedure arrayToMatrix(arr, numRows, numCols, mtx); - value numRows, numCols; - integer array arr, mtx; - integer numRows, numCols; - begin - integer i, j, idx; - - idx := 0; - for i := 1 step 1 until numRows do - begin - for j := 1 step 1 until numCols do - begin - idx := idx + 1; - mtx[i, j] := arr[idx] - end - end - end arrayToMatrix; - - procedure transposeMatrix(mtx, numRows, numCols, mtxT); - value numRows, numCols; - integer array mtx, mtxT; - integer numRows, numCols; - begin - integer i, j; - - for i := 1 step 1 until numRows do - begin - for j := 1 step 1 until numCols do mtxT[j, i] := mtx[i, j] - end - end transposeMatrix; - - procedure matrixToArray(mtx, numRows, numCols, arr); - value numRows, numCols; - integer array mtx, arr; - integer numRows, numCols; - begin - integer i, j, idx; - - idx := 0; - for i := 1 step 1 until numRows do - begin - for j := 1 step 1 until numCols do - begin - idx := idx + 1; - arr[idx] := mtx[i, j] - end - end - end matrixToArray; - - integer argc, size, ch, numCols, numRows; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 3 then usage; - - comment Get number of columns from 1st argument. Exit if invalid; - if !inValidInteger(numCols, ch, false) then usage; - - comment Get number of rows from 2nd argument. Exit if invalid; - if !inValidInteger(numRows, ch, false) then usage; - - comment Get total size of array; - size := numRows * numCols; - - begin - integer arrLen; - integer array arr[1:size]; - integer array mtx[1:numRows, 1:numCols], mtxT[1:numCols, 1:numRows]; - - comment Get array from 3rd argument. Exit if invalid or does not - match expect size; - arrLen := inIntegerArray(arr, size + 1); - if arrLen != size then usage; - - comment Convert array to matrix; - arrayToMatrix(arr, numRows, numCols, mtx); - - comment Transpose matrix; - transposeMatrix(mtx, numRows, numCols, mtxT); - - comment Convert matrix to array and display; - matrixToArray(mtxT, numCols, numRows, arr); - outIntegerArray(arr, arrLen) - end -end - -``` - -{% endraw %} - -Transpose Matrix in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/algol68/index.md b/docs/projects/transpose-matrix/algol68/index.md deleted file mode 100644 index b0ce046883..0000000000 --- a/docs/projects/transpose-matrix/algol68/index.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-06 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2023-02-06 -layout: default -tags: -- algol68 -- transpose-matrix -title: Transpose Matrix in ALGOL 68 -title1: Transpose Matrix -title2: in ALGOL 68 ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); -MODE PARSEINTLIST_RESULT = STRUCT(BOOL valid, REF []INT values); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC count list items = (STRING s) INT: -( - INT count := 1; - FOR k TO UPB s - DO - IF s[k] = "," - THEN - count +:= 1 - FI - OD; - - count -); - -PROC parse int list = (REF STRING s) PARSEINTLIST_RESULT: -( - BOOL valid := FALSE; - STRING leftover := s; - INT num list items = count list items(s); - HEAP [num list items]INT values; - - # Repeat while valid value # - FOR k TO num list items - DO - # Get next integer value and update leftover string # - PARSEINT_RESULT result = parse int(leftover); - valid := valid OF result; - leftover := leftover OF result; - - # Append the integer value to list # - values[k] := value OF result; - - # Do nothing if end of string # - IF leftover = "" - THEN - SKIP - # Skip comma if leftover string starts with comma # - ELIF leftover[1] = "," - THEN - leftover := leftover[2:] - # Otherwise indicate invalid # - ELSE - valid := FALSE - FI - UNTIL NOT valid - OD; - - PARSEINTLIST_RESULT(valid, values) -); - -PROC usage = VOID: printf(($gl$, "Usage: please enter the dimension of the matrix and the serialized matrix")); - -# Convert list of values to a matrix # -PROC convert to matrix = (REF []INT values, INT num rows, INT num cols) REF [, ]INT: -( - HEAP [num rows, num cols]INT matrix; - INT count := 0; - FOR i TO num rows - DO - FOR j TO num cols - DO - count +:= 1; - matrix[i, j] := values[count] - OD - OD; - - matrix -); - -# Return a transposed version of a matrix # -PROC transpose matrix = (REF [, ]INT matrix) REF [, ]INT: -( - # Use built-in transpose operator # - TRNSP matrix -); - -# Show matrix as a list of comma-separated values # -PROC show matrix as list = (REF [, ]INT matrix) VOID: -( - INT num rows = 1 UPB matrix; - INT num cols = 2 UPB matrix; - FOR i TO num rows - DO - FOR j TO num cols - DO - IF i > 1 OR j > 1 - THEN - print(", ") - FI; - - print(whole(matrix[i, j], 0)) - OD - OD; - - print(newline) -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINT_RESULT result := parse int(s); -INT num cols := value OF result; -IF NOT valid OF result OR num cols < 1 -THEN - usage; - stop -FI; - -# Parse 2nd command-line argument # -s := argv(5); -result := parse int(s); -INT num rows := value OF result; -IF NOT valid OF result OR num rows < 1 -THEN - usage; - stop -FI; - -# Parse 3rd command-line argument and make sure that it is the product # -# of the number of rows and columns # -s := argv(6); -PARSEINTLIST_RESULT list result := parse int list(s); -REF []INT values := values OF list result; -INT num values := UPB values; -IF NOT valid OF list result OR num values /= num rows * num cols -THEN - usage; - stop -FI; - -# Convert values to matrix # -REF [, ]INT matrix := convert to matrix(values, num rows, num cols); - -# Transpose matrix # -REF [, ]INT matrix t := transpose matrix(matrix); - -# Show transposed matrix as a list # -show matrix as list(matrix t) - -``` - -{% endraw %} - -Transpose Matrix in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/awk/index.md b/docs/projects/transpose-matrix/awk/index.md deleted file mode 100644 index bf19a646d8..0000000000 --- a/docs/projects/transpose-matrix/awk/index.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-04-25 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2025-04-25 -layout: default -tags: -- awk -- transpose-matrix -title: Transpose Matrix in AWK -title1: Transpose -title2: Matrix in AWK ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please enter the dimension of the matrix and the serialized matrix" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function str_to_array(s, arr, str_arr, idx, result) { - split(s, str_arr, ",") - for (idx in str_arr) { - result = str_to_number(str_arr[idx]) - if (result == "ERROR") { - delete arr - arr[1] = "ERROR" - break - } else { - arr[idx] = result - } - } -} - -function arr_to_matrix(arr, num_rows, num_cols, matrix, idx, i, j) { - idx = 0 - for (i = 1; i <= num_rows; i++) { - for (j = 1; j <= num_cols; j++) { - matrix[i, j] = arr[++idx] - } - } -} - -function transpose_matrix(matrix, num_rows, num_cols, t_matrix, i, j) { - for (i = 1; i <= num_rows; i++) { - for (j = 1; j <= num_cols; j++) { - t_matrix[j, i] = matrix[i, j] - } - } -} - -function matrix_to_arr(matrix, num_rows, num_cols, arr, idx, i, j) { - idx = 0 - for (i = 1; i <= num_rows; i++) { - for (j = 1; j <= num_cols; j++) { - arr[++idx] = matrix[i, j] - } - } -} - -function show_array(arr, idx, s) { - s = "" - for (idx in arr) { - if (s) { - s = s ", " - } - s = s arr[idx] - } - - print s -} - -BEGIN { - if (ARGC < 4) { - usage() - } - - num_cols = str_to_number(ARGV[1]) - num_rows = str_to_number(ARGV[2]) - str_to_array(ARGV[3], arr) - arr_len = length(arr) - if (num_cols == "ERROR" || num_rows == "ERROR" || \ - !arr_len || arr[1] == "ERROR" || \ - num_cols * num_rows != arr_len) { - usage() - } - - arr_to_matrix(arr, num_rows, num_cols, matrix) - transpose_matrix(matrix, num_rows, num_cols, t_matrix) - matrix_to_arr(t_matrix, num_cols, num_rows, arr) - show_array(arr) -} - -``` - -{% endraw %} - -Transpose Matrix in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/beef/index.md b/docs/projects/transpose-matrix/beef/index.md deleted file mode 100644 index dd025c3725..0000000000 --- a/docs/projects/transpose-matrix/beef/index.md +++ /dev/null @@ -1,206 +0,0 @@ ---- -authors: -- rzuckerm -date: 2024-02-18 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2024-02-18 -layout: default -tags: -- beef -- transpose-matrix -title: Transpose Matrix in Beef -title1: Transpose -title2: Matrix in Beef ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace TransposeMatrix; - -class Matrix -{ - int mRows; - int mCols; - T[,] mMatrix ~ delete _; - - public this(int rows, int cols, List arr) - { - mRows = rows; - mCols = cols; - mMatrix = new T[mRows, mCols]; - int index = 0; - for (int i < mRows) - { - for (int j < mCols) - { - mMatrix[i, j] = arr[index]; - index++; - } - } - } - - public void ShowMatrixAsList() - { - String line = scope .(); - for (int i < mRows) - { - for (int j < mCols) - { - if (!line.IsEmpty) - { - line += ", "; - } - - line.AppendF("{}", mMatrix[i, j]); - } - } - - Console.WriteLine(line); - } - - public void Transpose() - { - T[,] matrixT = new T[mCols, mRows]; - for (int i < mRows) - { - for (int j < mCols) - { - matrixT[j, i] = mMatrix[i, j]; - } - } - - Swap!(mRows, mCols); - delete mMatrix; - mMatrix = matrixT; - } -} - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please enter the dimension of the matrix and the serialized matrix"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static Result ParseIntList(StringView str, List arr) - where T: IParseable - { - arr.Clear(); - for (StringView item in str.Split(',')) - { - switch (ParseInt(item)) - { - case .Ok(let val): - arr.Add(val); - - case .Err: - return .Err; - } - } - - return .Ok; - } - - public static int Main(String[] args) - { - if (args.Count < 3) - { - Usage(); - } - - int cols = ?; - switch (ParseInt(args[0])) - { - case .Ok(out cols): - if (cols < 1) - { - Usage(); - } - - case .Err: - Usage(); - } - - int rows = ?; - switch (ParseInt(args[1])) - { - case .Ok(out rows): - if (rows < 1) - { - Usage(); - } - - case .Err: - Usage(); - } - - List arr = scope .(); - if (ParseIntList(args[2], arr) case .Err) - { - Usage(); - } - - if (rows * cols != arr.Count) - { - Usage(); - } - - Matrix matrix = scope .(rows, cols, arr); - matrix.Transpose(); - matrix.ShowMatrixAsList(); - return 0; - } -} - -``` - -{% endraw %} - -Transpose Matrix in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/c-plus-plus/index.md b/docs/projects/transpose-matrix/c-plus-plus/index.md deleted file mode 100644 index 1cf9eb21df..0000000000 --- a/docs/projects/transpose-matrix/c-plus-plus/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- Meet Thakur -- Ștefan-Iulian Alecu -date: 2025-10-11 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-05-05 -layout: default -tags: -- c-plus-plus -- transpose-matrix -title: Transpose Matrix in C++ -title1: Transpose -title2: Matrix in C++ ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include - -namespace ranges = std::ranges; -namespace views = std::views; - -[[noreturn]] void usage() { - std::cout << "Usage: please enter the dimension of the matrix and the " - "serialized matrix\n"; - std::exit(1); -} - -static constexpr std::string_view ws = " \t\n\r\f\v"; -constexpr std::string_view trim(std::string_view s) { - const auto start = s.find_first_not_of(ws); - if (start == std::string_view::npos) return ""; - s.remove_prefix(start); - - const auto end = s.find_last_not_of(ws); - s.remove_suffix(s.size() - 1 - end); - return s; -} - -std::optional to_positive_int(std::string_view s) { - int value{}; - auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value); - return (ec == std::errc{} && ptr == s.data() + s.size() && value > 0) - ? std::make_optional(value) - : std::nullopt; -} - -std::optional> parse_vec(std::string_view s) { - auto pipe = s | views::split(',') | views::transform([](auto&& r) { - return std::string_view{ - std::addressof(*ranges::begin(r)), - static_cast(ranges::distance(r))}; - }) | - views::transform(trim) | views::transform(to_positive_int); - - std::vector out; - for (auto&& opt : pipe) { - if (!opt) return std::nullopt; - out.push_back(*opt); - } - return out.size() < 2 ? std::nullopt : std::make_optional(out); -} - -std::vector transpose(int rows, int cols, const std::vector& m) { - std::vector out(rows * cols); - - for (int i = 0; i < rows; ++i) { - for (int j = 0; j < cols; ++j) { - out[j * rows + i] = m[i * cols + j]; - } - } - - return out; -} - -int main(int argc, char* argv[]) { - if (argc != 4) usage(); - - const auto cols = to_positive_int(argv[1]); - const auto rows = to_positive_int(argv[2]); - if (!cols || !rows) usage(); - - std::string_view input = argv[3]; - if (input.empty()) usage(); - - const int total = (*rows) * (*cols); - - auto matrix = parse_vec(input); - if (!matrix) usage(); - - if (matrix->size() != static_cast(total)) usage(); - - auto result = transpose(*rows, *cols, *matrix); - - for (const char* sep = ""; int val : result) { - std::cout << std::exchange(sep, ", ") << val; - } - std::cout << "\n"; -} -``` - -{% endraw %} - -Transpose Matrix in [C++](/languages/c-plus-plus) was written by: - -- Meet Thakur -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/c-sharp/index.md b/docs/projects/transpose-matrix/c-sharp/index.md deleted file mode 100644 index bf577d86af..0000000000 --- a/docs/projects/transpose-matrix/c-sharp/index.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-29 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- transpose-matrix -title: Transpose Matrix in C# -title1: Transpose -title2: Matrix in C# ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System.Runtime.InteropServices; - -if (args is not [var colsRaw, var rowsRaw, var matrixRaw] - || !int.TryParse(colsRaw, out int cols) - || !int.TryParse(rowsRaw, out int rows) - || cols <= 0 || rows <= 0 - || !TryParseMatrix(matrixRaw.AsSpan(), cols, rows, out var matrix) -) -{ - return ExitWithUsage(); -} - -Console.WriteLine(string.Join(", ", Transpose(matrix, cols, rows))); -return 0; - -static List Transpose(List m, int cols, int rows) -{ - var o = new List(m.Count); - for (int i = 0; i < m.Count; i++) o.Add(0); - - var src = CollectionsMarshal.AsSpan(m); - var dst = CollectionsMarshal.AsSpan(o); - - for (int r = 0; r < rows; r++) - for (int c = 0; c < cols; c++) - dst[c * rows + r] = src[r * cols + c]; - - return o; -} - -static bool TryParseMatrix(ReadOnlySpan view, int cols, int rows, out List numbers) -{ - numbers = new(cols * rows); - - if (view.IsWhiteSpace()) - return false; - - int expected = cols * rows; - int count = 0; - - while (!view.IsEmpty) - { - int i = view.IndexOf(','); - var token = i >= 0 ? view[..i] : view; - - view = i >= 0 ? view[(i + 1)..] : []; - - if (!int.TryParse(token, out int v)) - return false; - - numbers.Add(v); - - if (++count > expected) - return false; - } - - return count == expected; -} - -static int ExitWithUsage() -{ - Console.Error.WriteLine( - """Usage: please enter the dimension of the matrix and the serialized matrix""" - ); - return 1; -} - -``` - -{% endraw %} - -Transpose Matrix in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/c/index.md b/docs/projects/transpose-matrix/c/index.md deleted file mode 100644 index b752210a40..0000000000 --- a/docs/projects/transpose-matrix/c/index.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -authors: -- Maximillian Naza -- Ștefan-Iulian Alecu -date: 2025-01-21 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-04-15 -layout: default -tags: -- c -- transpose-matrix -title: Transpose Matrix in C -title1: Transpose -title2: Matrix in C ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include - -#define MAX_MATRIX_SIZE 100 - -void transpose_matrix(int *matrix, int rows, int cols, int *transposed) -{ - for (int i = 0; i < rows; i++) - for (int j = 0; j < cols; j++) - transposed[j * rows + i] = matrix[i * cols + j]; -} - -int main(int argc, char *argv[]) -{ - if (argc != 4) - { - printf("Usage: please enter the dimension of the matrix and the " - "serialized matrix\n"); - return 1; - } - - int cols = atoi(argv[1]); - int rows = atoi(argv[2]); - char *input = argv[3]; - - if (cols <= 0 || rows <= 0 || strlen(input) == 0) - { - printf("Usage: please enter the dimension of the matrix and the " - "serialized matrix\n"); - return 1; - } - - int matrix[MAX_MATRIX_SIZE]; - int transposed[MAX_MATRIX_SIZE]; - int count = 0; - char *token = strtok(input, ", "); - - while (token != NULL && count < rows * cols) - { - matrix[count++] = atoi(token); - token = strtok(NULL, ", "); - } - - if (count != rows * cols) - { - printf("Usage: please enter the dimension of the matrix and the " - "serialized matrix\n"); - return 1; - } - - transpose_matrix(matrix, rows, cols, transposed); - - for (int i = 0; i < cols * rows; i++) - { - printf("%d", transposed[i]); - if (i < cols * rows - 1) - printf(", "); - } - printf("\n"); - - return 0; -} - -``` - -{% endraw %} - -Transpose Matrix in [C](/languages/c) was written by: - -- Maximillian Naza -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/cobol/index.md b/docs/projects/transpose-matrix/cobol/index.md deleted file mode 100644 index 4032eabef9..0000000000 --- a/docs/projects/transpose-matrix/cobol/index.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- transpose-matrix -title: Transpose Matrix in COBOL -title1: Transpose -title2: Matrix in COBOL ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. transpose-matrix. - -data division. -working-storage section. - -01 cmd-args. - 05 cols-raw pic x(8). - 05 rows-raw pic x(8). - 05 matrix-raw pic x(500). - -01 matrix-dims. - 05 num-cols pic 9(4) comp. - 05 num-rows pic 9(4) comp. - 05 total-elements pic 9(4) comp. - -01 table-indices. - 05 i pic s9(4) comp. - 05 j pic s9(4) comp. - 05 curr-pos pic 9(4) comp value 1. - 05 element-ptr pic 9(4) comp value 1. - -01 matrix-data. - 05 row occurs 100 times. - 10 val occurs 100 times - pic 9(9) comp. - -01 output-utils. - 05 display-num pic z(8)9. - 05 is-first pic x value "Y". - 88 first-item value "Y". - 88 not-first value "N". - -procedure division. - -main-logic. - perform get-and-validate-input - perform parse-matrix - perform print-transposed - display space - goback. - -get-and-validate-input. - accept cols-raw from argument-value - accept rows-raw from argument-value - accept matrix-raw from argument-value - - if cols-raw = spaces or rows-raw = spaces or matrix-raw = spaces - or function trim(cols-raw) is not numeric - or function trim(rows-raw) is not numeric - display "Usage: please enter the dimension of the matrix and the serialized matrix" - stop run - end-if - - compute num-cols = function numval(cols-raw) - compute num-rows = function numval(rows-raw) - compute total-elements = num-cols * num-rows. - -parse-matrix. - move 1 to i - move 1 to j - move 1 to curr-pos - - perform until i > num-rows - - unstring matrix-raw - delimited by ", " - into val(i, j) - pointer curr-pos - end-unstring - - add 1 to j - - if j > num-cols - move 1 to j - add 1 to i - end-if - - end-perform. - -print-transposed. - set first-item to true - - perform varying j from 1 by 1 until j > num-cols - perform varying i from 1 by 1 until i > num-rows - - if not-first - display ", " with no advancing - end-if - - move val(i, j) to display-num - display function trim(display-num) with no advancing - - set not-first to true - end-perform - end-perform. - -``` - -{% endraw %} - -Transpose Matrix in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/commodore-basic/index.md b/docs/projects/transpose-matrix/commodore-basic/index.md deleted file mode 100644 index 80ca89e94a..0000000000 --- a/docs/projects/transpose-matrix/commodore-basic/index.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-10-23 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2023-10-23 -layout: default -tags: -- commodore-basic -- transpose-matrix -title: Transpose Matrix in Commodore BASIC -title1: Transpose Matrix -title2: in Commodore BASIC ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -10 DIM A(99) -20 DIM M(9, 9): REM Allow up to a 10x10 matrix -30 DIM T(9, 9): REM Storage for matrix transpose -15 REM Get number of columns -20 GOSUB 1000 -30 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -40 MC = NR -45 REM Get number of rows -50 GOSUB 1000 -60 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -70 MR = NR -75 REM Get matrix as an array -80 GOSUB 2000 -90 IF V = 0 OR C >= 0 THEN GOTO 200: REM invalid or not end of input/value -100 IF NA <> (MC * MR) THEN GOTO 200: REM incorrect matrix size -105 REM Convert array to matrix -110 GOSUB 2500 -115 REM Get matrix transpose -120 GOSUB 3000 -125 REM Convert matrix transpose back to array and display -130 GOSUB 3500 -140 GOSUB 4000 -150 END -200 PRINT "Usage: please enter the dimension of the matrix "; -210 PRINT "and the serialized matrix" -220 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Read array value -2001 REM A contains array value -2002 REM NA contains length of array -2003 REM V = 1 if valid number, 0 otherwise -2004 REM C = -2 if end of input, -1 if end of value, -2005 REM 32 if whitespace, ASCII code of last character otherwise -2006 REM Initialize -2010 NA = 0 -2020 GOSUB 1000: REM Read input value -2030 IF V = 0 THEN RETURN: REM invalid -2040 A(NA) = NR -2050 NA = NA + 1 -2060 IF C < 0 THEN RETURN: REM end of input or value -2070 IF C = 44 THEN GOTO 2020: REM comma, get next value -2080 V = 0 -2090 RETURN -2500 REM Convert array to matrix -2501 REM Inputs: -2502 REM - A contains array -2503 REM - MR contains number of rows -2504 REM - MC contains number of columns -2505 REM Output: M contains matrix -2510 N = -1 -2520 FOR I = 0 TO MR - 1 -2530 FOR J = 0 TO MC - 1 -2540 N = N + 1 -2550 M(I, J) = A(N) -2560 NEXT J -2570 NEXT I -2580 RETURN -3000 REM Calculate matrix transpose -3001 REM Inputs: -3002 REM - M contains matrix -3003 REM - MR contains number of rows -3004 REM - MC contains number of columns -3005 REM Outputs: -3006 REM - T contains matrix transpose -3007 REM - TR contains number of rows in matrix transpose -3008 REM - TC contains number of columns in matrix transpose -3010 FOR I = 0 TO MR - 1 -3020 FOR J = 0 TO MC - 1 -3030 T(J, I) = M(I, J) -3040 NEXT J -3050 NEXT I -3060 TR = MC -3070 TC = MR -3080 RETURN -3500 REM Convert matrix transpose to array -3501 REM Inputs: -3502 REM - T contains matrix transpose -3503 REM - TR contains number of rows in matrix transpose -3504 REM - TC contains number of columns in matrix transpose -3505 REM Outputs: -3506 REM - A contains array -3507 REM - NA contains size of array -3508 NA = 0 -3510 FOR I = 0 TO TR - 1 -3520 FOR J = 0 TO TC - 1 -3530 A(NA) = T(I, J) -3540 NA = NA + 1 -3550 NEXT J -3560 NEXT I -3570 RETURN -4000 REM Display array -4001 REM A contains array -4002 REM NA contains size of array -4010 IF NA < 1 THEN GOTO 3590 -4020 FOR I = 0 TO NA - 1 -4030 S$ = STR$(A(I)) -4040 IF A(I) >= 0 THEN S$ = MID$(S$, 2): REM strip leading space -4050 PRINT S$; -4060 IF I < (NA - 1)THEN PRINT ", "; -4070 NEXT I -4080 PRINT -4090 RETURN - -``` - -{% endraw %} - -Transpose Matrix in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/euphoria/index.md b/docs/projects/transpose-matrix/euphoria/index.md deleted file mode 100644 index af46c83523..0000000000 --- a/docs/projects/transpose-matrix/euphoria/index.md +++ /dev/null @@ -1,203 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-02-27 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2023-02-27 -layout: default -tags: -- euphoria -- transpose-matrix -title: Transpose Matrix in Euphoria -title1: Transpose Matrix -title2: in Euphoria ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - --- Indices for parse_int_list() return value -enum PARSE_INT_LIST_VALID, PARSE_INT_LIST_VALUES - -function parse_int_list(sequence s) - -- Split string on comma - sequence list = split(s, ",") - - -- Parse each item - integer valid = FALSE - sequence values = {} - for n = 1 to length(list) - do - sequence result = parse_int(list[n]) - valid = result[PARSE_INT_VALID] - values &= result[PARSE_INT_VALUE] - if not valid - then - exit - end if - end for - - return {valid, values} -end function - -procedure usage() - puts(STDOUT, "Usage: please enter the dimension of the matrix and the serialized matrix\n") - abort(0) -end procedure - --- Convert list of values to a matrix -function convert_to_matrix(sequence values, integer num_rows, integer num_cols) - sequence matrix = repeat(repeat(0, num_cols), num_rows) - integer count = 1 - for i = 1 to num_rows - do - matrix[i] = values[count..count + num_cols - 1] - count += num_cols - end for - - return matrix -end function - --- Transpose matrix -function transpose_matrix(sequence matrix) - integer num_rows = length(matrix) - integer num_cols = length(matrix[1]) - sequence matrix_t = repeat(repeat(0, num_rows), num_cols) - for j = 1 to num_cols - do - matrix_t[j] = vslice(matrix, j) - end for - - return matrix_t -end function - --- Show matrix as a list of comma-separated values -procedure show_matrix_as_list(sequence matrix) - integer num_rows = length(matrix) - integer num_cols = length(matrix[1]) - if num_rows > 0 and num_cols > 0 - then - sequence format = repeat_pattern("%d, ", num_cols) - sequence s = "" - for i = 1 to num_rows - do - s &= sprintf(format, matrix[i]) - end for - - s = s[1..$-2] - printf(STDOUT, "%s\n", {s}) - end if -end procedure - --- Check command-line arguments -sequence argv = command_line() -if ( - length(argv) < 6 - or length(argv[4]) = 0 - or length(argv[5]) = 0 - or length(argv[6]) = 0 -) -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int(argv[4]) -integer num_cols = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] or num_cols < 0 -then - usage() -end if - --- Parse 2nd command-line argument -result = parse_int(argv[5]) -integer num_rows = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] or num_rows < 0 -then - usage() -end if - --- Parse 3rd command-line argument -result = parse_int_list(argv[6]) -sequence values = result[PARSE_INT_LIST_VALUES] -integer num_values = length(values) -if not result[PARSE_INT_LIST_VALID] or num_values != num_rows * num_cols -then - usage() -end if - --- Convert values to matrix -sequence matrix = convert_to_matrix(values, num_rows, num_cols) - --- Transpose matrix -sequence matrix_t = transpose_matrix(matrix) - --- Show transposed matrix as a list -show_matrix_as_list(matrix_t) - -``` - -{% endraw %} - -Transpose Matrix in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/f-sharp/index.md b/docs/projects/transpose-matrix/f-sharp/index.md deleted file mode 100644 index 63f3173ad3..0000000000 --- a/docs/projects/transpose-matrix/f-sharp/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- transpose-matrix -title: Transpose Matrix in F# -title1: Transpose -title2: Matrix in F# ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Matrix = - let transpose (data: int[,]) = - let rows = data.GetLength 0 - let cols = data.GetLength 1 - - Array2D.init cols rows (fun x y -> - data.[y, x] - ) - -module Helpers = - let parseInt (s: string) = - match s.Trim() |> Int32.TryParse with - | true, v -> Some v - | _ -> None - - let parseMatrix (s: string) = - s.Split(',', StringSplitOptions.RemoveEmptyEntries) - |> Array.choose parseInt - |> function - | arr when arr.Length > 0 -> Some arr - | _ -> None - - let parseArgs (argv: string[]) = - match argv with - | [| cStr; rStr; matrixStr |] -> - match parseInt cStr, parseInt rStr, parseMatrix matrixStr with - | Some c, Some r, Some values when values.Length = c * r -> - Ok (c, r, values) - - | _ -> - Error () - - | _ -> - Error () - - let buildMatrix (c, r, values: int[]) = - Array2D.init r c (fun i j -> - values.[i * c + j] - ) - - let handleResult = - function - | Ok m -> - m |> Seq.cast |> Seq.map string |> String.concat ", " |> printfn "%s" - 0 - - | Error () -> - printfn "Usage: please enter the dimension of the matrix and the serialized matrix" - 1 - - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map Helpers.buildMatrix - |> Result.map Matrix.transpose - |> Helpers.handleResult -``` - -{% endraw %} - -Transpose Matrix in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/go/index.md b/docs/projects/transpose-matrix/go/index.md deleted file mode 100644 index 4a977b54a0..0000000000 --- a/docs/projects/transpose-matrix/go/index.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -authors: -- Meet Thakur -date: 2024-10-11 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2024-10-11 -layout: default -tags: -- go -- transpose-matrix -title: Transpose Matrix in Go -title1: Transpose -title2: Matrix in Go ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" - "strings" -) - -func main() { - if len(os.Args) < 4 { - fmt.Println("Usage: please enter the dimension of the matrix and the serialized matrix") - return - } - - cols, err1 := strconv.Atoi(os.Args[1]) - rows, err2 := strconv.Atoi(os.Args[2]) - matrixStr := os.Args[3] - - if err1 != nil || err2 != nil || cols <= 0 || rows <= 0 || matrixStr == "" { - fmt.Println("Usage: please enter the dimension of the matrix and the serialized matrix") - return - } - - matrixStr = strings.ReplaceAll(matrixStr, " ", "") - matrixElements := strings.Split(matrixStr, ",") - if len(matrixElements) != cols*rows { - fmt.Println("Usage: please enter the dimension of the matrix and the serialized matrix") - return - } - - matrix := make([][]int, rows) - for i := range matrix { - matrix[i] = make([]int, cols) - } - - for i := 0; i < rows; i++ { - for j := 0; j < cols; j++ { - num, err := strconv.Atoi(matrixElements[i*cols+j]) - if err != nil { - fmt.Println("Usage: please enter the dimension of the matrix and the serialized matrix") - return - } - matrix[i][j] = num - } - } - - transposed := transpose(matrix) - printMatrix(transposed) -} - -func transpose(matrix [][]int) [][]int { - if len(matrix) == 0 { - return [][]int{} - } - - transposed := make([][]int, len(matrix[0])) - for i := range transposed { - transposed[i] = make([]int, len(matrix)) - } - - for i := range matrix { - for j := range matrix[i] { - transposed[j][i] = matrix[i][j] - } - } - - return transposed -} - -func printMatrix(matrix [][]int) { - var result []string - for _, row := range matrix { - for _, val := range row { - result = append(result, strconv.Itoa(val)) - } - } - fmt.Println(strings.Join(result, ", ")) -} -``` - -{% endraw %} - -Transpose Matrix in [Go](/languages/go) was written by: - -- Meet Thakur - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/haskell/index.md b/docs/projects/transpose-matrix/haskell/index.md deleted file mode 100644 index 404825ca8b..0000000000 --- a/docs/projects/transpose-matrix/haskell/index.md +++ /dev/null @@ -1,86 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-11 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-05-11 -layout: default -tags: -- haskell -- transpose-matrix -title: Transpose Matrix in Haskell -title1: Transpose Matrix -title2: in Haskell ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell - -module Main where - -import System.Environment -import Text.Read -import Data.List (transpose, intercalate) -import Data.Function ((&)) -import Control.Monad (guard) - --- Converts string in format "1, 2, 3" to a Maybe list of int -stringToListMaybe :: String -> Maybe [Int] -stringToListMaybe str = readMaybe $ "[" ++ str ++ "]" :: Maybe [Int] - -listToMatrix :: Int -> [Int] -> [[Int]] -listToMatrix _ [] = [] -listToMatrix n l = let (row, xs) = splitAt n l in row : listToMatrix n xs - -listToString :: (Show a) => [a] -> String -listToString = intercalate ", " . map show - -parseArgs :: [String] -> Maybe (Int, Int, [Int]) -parseArgs [cols, rows, list] = do - cols' <- readMaybe cols - rows' <- readMaybe rows - list' <- stringToListMaybe list - guard $ cols' > 0 && rows' > 0 && cols' * rows' == length list' - return (cols', rows', list') -parseArgs _ = Nothing - -main :: IO () -main = do - args <- getArgs - case parseArgs args of - Nothing -> putStrLn "Usage: please enter the dimension of the matrix and the serialized matrix" - Just (c, _, l) -> listToMatrix c l & transpose & concat & listToString & putStrLn - -``` - -{% endraw %} - -Transpose Matrix in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/index.md b/docs/projects/transpose-matrix/index.md deleted file mode 100644 index 14b5bc5810..0000000000 --- a/docs/projects/transpose-matrix/index.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -date: 2022-04-28 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- transpose-matrix -title: Transpose Matrix -title1: Transpose -title2: Matrix ---- - - - -Welcome to the Transpose Matrix page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- Jeremy Grifski -- rzuckerm - -## Description - - - -In linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal; -that is, it switches the row and column indices of the matrix A by producing another matrix, often -denoted by AT. For example, the following matrix could be the matrix A: - - - - - - - - - - - - - - - - - - - - - - - - - - -
 column 1column 2column 3
row 1123
row 2456
row 3789
- -Once transposed, A becomes the following matrix, AT: - - - - - - - - - - - - - - - - - - - - - - - - - - -
 column 1column 2column 3
row 1147
row 2258
row 3369
- -The transpose of a matrix was introduced in 1858 by the British mathematician Arthur Cayley. - - -## Requirements - -For the purposes of this project, we'll ask that you create a program which accepts -a matrix as a list of integers and the dimensions of that matrix in the following -format: - -``` -transpose-matrix.lang 3 3 "1, 2, 3, 4, 5, 6, 7, 8, 9" -``` - -Here, the first two input numbers indicate the column and row size of the matrix, respectively, and the -next input is the list of numbers to be included in the matrix. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Transpose Matrix. -In order to keep things simple, we split up the testing as follows: - -- Transpose Matrix Valid Tests -- Transpose Matrix Invalid Tests - -### Transpose Matrix Valid Tests - -| Description | Cols | Rows | Matrix | Output | -| ----------- | ---- | ---- | ------ | ------ | -| Sample Input: Routine | "3" | "2" | "1, 2, 3, 4, 5, 6" | "1, 4, 2, 5, 3, 6" | - -### Transpose Matrix Invalid Tests - -| Description | Cols | Rows | Matrix | -| ----------- | ---- | ---- | ------ | -| No Input | | | | -| Missing Input: No Columns Or Rows | "" | "" | "1, 2, 3, 4, 5, 6" | -| Missing Input: No Matrix | "3" | "3" | "" | - -All of these tests should output the following: - -``` -Usage: please enter the dimension of the matrix and the serialized matrix -``` - - -## Articles - -There are 27 articles: - -- [Transpose Matrix in ALGOL 60](/projects/transpose-matrix/algol60) -- [Transpose Matrix in ALGOL 68](/projects/transpose-matrix/algol68) -- [Transpose Matrix in AWK](/projects/transpose-matrix/awk) -- [Transpose Matrix in Beef](/projects/transpose-matrix/beef) -- [Transpose Matrix in C](/projects/transpose-matrix/c) -- [Transpose Matrix in C#](/projects/transpose-matrix/c-sharp) -- [Transpose Matrix in C++](/projects/transpose-matrix/c-plus-plus) -- [Transpose Matrix in COBOL](/projects/transpose-matrix/cobol) -- [Transpose Matrix in Commodore BASIC](/projects/transpose-matrix/commodore-basic) -- [Transpose Matrix in Euphoria](/projects/transpose-matrix/euphoria) -- [Transpose Matrix in F#](/projects/transpose-matrix/f-sharp) -- [Transpose Matrix in Go](/projects/transpose-matrix/go) -- [Transpose Matrix in Haskell](/projects/transpose-matrix/haskell) -- [Transpose Matrix in Java](/projects/transpose-matrix/java) -- [Transpose Matrix in JavaScript](/projects/transpose-matrix/javascript) -- [Transpose Matrix in Mathematica](/projects/transpose-matrix/mathematica) -- [Transpose Matrix in PHP](/projects/transpose-matrix/php) -- [Transpose Matrix in Pascal](/projects/transpose-matrix/pascal) -- [Transpose Matrix in PowerShell](/projects/transpose-matrix/powershell) -- [Transpose Matrix in Python](/projects/transpose-matrix/python) -- [Transpose Matrix in Ruby](/projects/transpose-matrix/ruby) -- [Transpose Matrix in Rust](/projects/transpose-matrix/rust) -- [Transpose Matrix in Swift](/projects/transpose-matrix/swift) -- [Transpose Matrix in Tcl](/projects/transpose-matrix/tcl) -- [Transpose Matrix in TypeScript](/projects/transpose-matrix/typescript) -- [Transpose Matrix in Visual Basic](/projects/transpose-matrix/visual-basic) -- [Transpose Matrix in m4](/projects/transpose-matrix/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/transpose-matrix/java/index.md b/docs/projects/transpose-matrix/java/index.md deleted file mode 100644 index 1dbf674f7f..0000000000 --- a/docs/projects/transpose-matrix/java/index.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -authors: -- Apurva Vats -date: 2025-10-31 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2025-10-31 -layout: default -tags: -- java -- transpose-matrix -title: Transpose Matrix in Java -title1: Transpose -title2: Matrix in Java ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; - -public class TransposeMatrix { - private static final int MAX_MATRIX_SIZE = 100; - private static final String USAGE_MSG = "Usage: please enter the dimension of the matrix and the serialized matrix"; - - public static void transposeMatrix(int[] matrix, int rows, int cols, int[] transposed) { - for (int i = 0; i < rows; i++) { - for (int j = 0; j < cols; j++) { - transposed[j * rows + i] = matrix[i * cols + j]; - } - } - } - - public static void main(String[] args) { - if (args.length != 3) { - System.out.println(USAGE_MSG); - return; - } - - int cols, rows; - String input = args[2]; - - try { - cols = Integer.parseInt(args[0]); - rows = Integer.parseInt(args[1]); - } catch (Exception e) { - System.out.println(USAGE_MSG); - return; - } - - if (cols <= 0 || rows <= 0 || input.isEmpty()) { - System.out.println(USAGE_MSG); - return; - } - - int[] matrix = new int[MAX_MATRIX_SIZE]; - int[] transposed = new int[MAX_MATRIX_SIZE]; - int count = 0; - - String[] tokens = input.split(","); - for (String token : tokens) { - if (count >= rows * cols) break; - - token = token.trim(); - try { - matrix[count++] = Integer.parseInt(token); - } catch (Exception e) { - System.out.println(USAGE_MSG); - return; - } - } - - if (count != rows * cols) { - System.out.println(USAGE_MSG); - return; - } - - transposeMatrix(matrix, rows, cols, transposed); - - for (int i = 0; i < cols * rows; i++) { - System.out.print(transposed[i]); - if (i < cols * rows - 1) { - System.out.print(", "); - } - } - System.out.println(); - } -} - -``` - -{% endraw %} - -Transpose Matrix in [Java](/languages/java) was written by: - -- Apurva Vats - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/javascript/index.md b/docs/projects/transpose-matrix/javascript/index.md deleted file mode 100644 index 128d07499b..0000000000 --- a/docs/projects/transpose-matrix/javascript/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2023-10-07 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2023-10-07 -layout: default -tags: -- javascript -- transpose-matrix -title: Transpose Matrix in JavaScript -title1: Transpose Matrix -title2: in JavaScript ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -var error_msg = "Usage: please enter the dimension of the matrix and the serialized matrix"; -if (process.argv.length != 5) { - console.log(error_msg); - process.exit(1); -} -var cols = parseInt(process.argv[2]); -var rows = parseInt(process.argv[3]); -var list_str = process.argv[4]; -if (isNaN(cols) || isNaN(rows) || list_str.length == 0) { - console.log(error_msg); - process.exit(1); -} -var list = list_str.split(",").map(function (x) { return parseInt(x); }); -var matrix = []; -for (var i = 0; i < rows; i++) { - matrix.push(list.slice(i * cols, (i + 1) * cols)); -} -var transpose = []; -for (var i = 0; i < cols; i++) { - transpose.push([]); - for (var j = 0; j < rows; j++) { - transpose[i].push(matrix[j][i]); - } -} -console.log(transpose.map(function (x) { return x.join(", "); }).join(", ")); - -``` - -{% endraw %} - -Transpose Matrix in [JavaScript](/languages/javascript) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/m4/index.md b/docs/projects/transpose-matrix/m4/index.md deleted file mode 100644 index 83d75f2370..0000000000 --- a/docs/projects/transpose-matrix/m4/index.md +++ /dev/null @@ -1,202 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-10-13 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2025-10-18 -layout: default -tags: -- m4 -- transpose-matrix -title: Transpose Matrix in m4 -title1: Transpose -title2: Matrix in m4 ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please enter the dimension of the matrix and the serialized matrix -m4exit(`1')') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(varname, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(varname, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl 2D versions of "array_get" and "array_set" -dnl array2_get(varname, idx1, idx2) -define(`array2_get', `defn(format(``%s[%s][%s]'', `$1', `$2', `$3'))') - -dnl array2_set(varname, idx1, idx2, value) -define(`array2_set', `define(format(``%s[%s][%s]'', `$1', `$2', `$3'), `$4')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl parse_int_list(varname, args): -dnl varname["length"] = 0 -dnl foreach arg in args: -dnl if not is_valid(arg): -dnl Return 0 -dnl varname[varname["length"]] = arg -dnl varname["length"] = varname["length"] + 1 -dnl Return 1 -define(`parse_int_list', -`array_set(`$1', `length', 0)dnl -_parse_int_list(`$1', $2)'dnl -) -define(`_parse_int_list', -`ifelse(is_valid(`$2'), 0, `0', -`array_set(`$1', array_get(`$1', `length'), `$2')dnl -array_set(`$1', `length', incr(array_get(`$1', `length')))dnl -ifelse(eval($# > 2), 1, `_parse_int_list(`$1', shift(shift($@)))', `1')'dnl -)'dnl -) - -dnl show_int_list(varname): -dnl for i = 0 to varname["length"]-1: -dnl if i > 0: -dnl Output ", " -dnl Output varname[i] -define(`show_int_list', `_show_int_list(`$1', 0)') -define(`_show_int_list', -`ifelse(eval($2 < array_get(`$1', `length')), 1, -`ifelse(eval($2 > 0), 1, `, ')dnl -array_get(`$1', $2)`'dnl -_show_int_list(`$1', incr($2))'`'dnl -)'dnl -) - -dnl list_to_matrix(arrname, mtxname, rows, cols): -dnl mtxname["rows"] = rows -dnl mtxname["cols"] = cols -dnl idx = 0 -dnl for i = 0 to rows-1: -dnl for j = 0 to cols-1: -dnl mtxname[i][j] = arrname[idx] -dnl idx = idx + 1 -define(`list_to_matrix', -`array_set(`$2', `rows', `$3')dnl -array_set(`$2', `cols', `$4')dnl -_list_to_matrix_outer(`$1', `$2', `$3', `$4', 0, 0)'dnl -) - -dnl arrname=$1, mtxname=$2, rows=$3, cols=$4, i=$5, idx=$6 -define(`_list_to_matrix_outer', -`ifelse(eval($5 < $3), 1, -`_list_to_matrix_inner(`$1', `$2', `$4', `$5', 0, `$6')dnl -_list_to_matrix_outer(`$1', `$2', `$3', `$4', incr($5), eval($6 + $4))'dnl -)'dnl -) - -dnl arrname=$1, mtxname=$2, cols=$3, i=$4, j=$5, idx=$6 -define(`_list_to_matrix_inner', -`ifelse(eval($5 < $3), 1, -`array2_set(`$2', `$4', `$5', array_get(`$1', `$6'))dnl -_list_to_matrix_inner(`$1', `$2', `$3', `$4', incr($5), incr($6))'dnl -)'dnl -) - -dnl transpose_matrix(mtxname1, mtxname2): -dnl mtxname2["rows"] = mtxname1["cols"] -dnl mtxname2["cols"] = mtxname2["rows"] -dnl for i = 0 to mtxname1["rows"]-1: -dnl for j = 0 to mtxname1["cols"]-1: -dnl mtxname2[j][i] = mtxname1[i][j] -define(`transpose_matrix', -`array_set(`$2', `rows', array_get(`$1', `cols'))dnl -array_set(`$2', `cols', array_get(`$1', `rows'))dnl -_transpose_matrix_outer(`$1', `$2', 0)'dnl -) - -dnl mtxname1=$1, mtxname2=$2, i=$3 -define(`_transpose_matrix_outer', -`ifelse(eval($3 < array_get(`$1', `rows')), 1, -`_transpose_matrix_inner(`$1', `$2', `$3', 0)dnl -_transpose_matrix_outer(`$1', `$2', incr($3))'dnl -)'dnl -) - -dnl mtxname1=$1, mtxname2=$2, i=$3, j=$4 -define(`_transpose_matrix_inner', -`ifelse(eval($4 < array_get(`$1', `cols')), 1, -`array2_set(`$2', `$4', `$3', array2_get(`$1', `$3', `$4'))dnl -_transpose_matrix_inner(`$1', `$2', `$3', incr($4))'dnl -)'dnl -) - -dnl matrix_to_list(mtxname, arrname): -dnl arrname["length"] = 0 -dnl idx = 0 -dnl for i = 0 to mtxname["rows"]-1: -dnl for j = 0 to mtxname["cols"]-1: -dnl arrname[arrname["length"]] = mtxname[i][j] -dnl arrname["length"] = arrname["length"] + 1 -define(`matrix_to_list', -`array_set(`$2', `length', 0)dnl -_matrix_to_list_outer(`$1', `$2', 0)'dnl -) - -dnl mtxname=$1, arrname=$2, i=$3 -define(`_matrix_to_list_outer', -`ifelse(eval($3 < array_get(`$1', `rows')), 1, -`_matrix_to_list_inner(`$1', `$2', `$3', 0)dnl -_matrix_to_list_outer(`$1', `$2', incr($3))'dnl -)'dnl -) - -dnl mtxname=$1, arrname=$2, i=$3, j=$4 -define(`_matrix_to_list_inner', -`ifelse(eval($4 < array_get(`$1', `cols')), 1, -`array_set(`$2', array_get(`$2', `length'), array2_get(`$1', `$3', `$4'))dnl -array_set(`$2', `length', incr(array_get(`$2', `length')))dnl -_matrix_to_list_inner(`$1', `$2', `$3', incr($4))'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 3 || !is_valid(ARGV1) || !is_valid(ARGV2)), 1, `show_usage()')dnl -ifelse(eval(len(ARGV3) < 1 || !parse_int_list(`arr', ARGV3)), 1, `show_usage()')dnl -ifelse(eval(ARGV1 < 1 || ARGV2 < 1 || array_get(`arr', `length') != ARGV1 * ARGV2), 1, `show_usage()')dnl -list_to_matrix(`arr', `mtx', ARGV2, ARGV1)dnl -transpose_matrix(`mtx', `mtx_t')dnl -matrix_to_list(`mtx_t', `arr_t')dnl -show_int_list(`arr_t') - -``` - -{% endraw %} - -Transpose Matrix in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/mathematica/index.md b/docs/projects/transpose-matrix/mathematica/index.md deleted file mode 100644 index 74a8070bee..0000000000 --- a/docs/projects/transpose-matrix/mathematica/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Ben Hekster -date: 2023-01-17 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2023-01-17 -layout: default -tags: -- mathematica -- transpose-matrix -title: Transpose Matrix in Mathematica -title1: Transpose Matrix -title2: in Mathematica ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -(* Code *) - -(* This is provided by the Mathematica built-in Transpose; so the only code needed is the 'user interface' - to make it look a little more like a Unix command-line tool: *) - -transposeMain = Function[{columns, rows, values}, - Module[{e = "Usage: please enter the dimension of the matrix and the serialized matrix"}, - Catch[ - StringRiffle[ - Flatten @* - Transpose @* - (* convert list of values and dimensions into matrix *) - Function[{c, r, v}, - If[c*r == Length[v], Partition[v, c], Throw[e]]] @@ - Map[ - (* convert string to integer, or throw *) - s \[Function] If[StringMatchQ[s, DigitCharacter ..], - FromDigits[s], - Throw[e]], - (* construct three arguments to transpose: number of columns, rows, and list of values *) - {columns, rows, StringSplit[If[StringLength[values] > 0, values, Throw[e]], ", "]}, - {-1} (* at each leaf *)], - ", "]]]]; - - -(* Valid Tests *) - -Print /@ Apply[transposeMain] /@ { - {"3", "2", "1, 2, 3, 4, 5, 6"} - }; - - -(* Invalid Tests *) - -transposeMain["", "", "1, 2, 3, 4, 5, 6"] -transposeMain["3", "3", ""] - -``` - -{% endraw %} - -Transpose Matrix in [Mathematica](/languages/mathematica) was written by: - -- Ben Hekster - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/pascal/index.md b/docs/projects/transpose-matrix/pascal/index.md deleted file mode 100644 index f4bf2a8d65..0000000000 --- a/docs/projects/transpose-matrix/pascal/index.md +++ /dev/null @@ -1,149 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-07-21 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2025-07-21 -layout: default -tags: -- pascal -- transpose-matrix -title: Transpose Matrix in Pascal -title1: Transpose Matrix -title2: in Pascal ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program TransposeMatrix; - -{$mode objfpc}{$H+} - -uses - Classes, - Generics.Collections, - StrUtils, - SysUtils; - -type - TIntegerList = specialize TList; - -procedure ShowUsage; -begin - Writeln('Usage: please enter the dimension of the matrix and the serialized matrix'); - Halt(1); -end; - -function ParseIntegerList(const S: string): TIntegerList; -var - Tokens: TStringArray; - Token: string; - Value: integer; -begin - if S.Trim = '' then - ShowUsage; - - Tokens := S.Split([',']); - if Length(Tokens) < 2 then - ShowUsage; - - Result := TIntegerList.Create; - for Token in Tokens do - begin - if not TryStrToInt(Trim(Token), Value) then - begin - Result.Free; - ShowUsage; - end; - Result.Add(Value); - end; -end; - -function FormatIntegerList(const List: TIntegerList): string; -var - i: integer; -begin - Result := ''; - for i := 0 to List.Count - 1 do - begin - if i > 0 then - Result += ', '; - Result += IntToStr(List[i]); - end; -end; - -function TransposeMatrix(const Cols, Rows: integer; -const Input: TIntegerList): TIntegerList; -var - i, j, index: integer; -begin - Result := TIntegerList.Create; - Result.Count := Rows * Cols; - - for i := 0 to Pred(Rows) do - for j := 0 to Pred(Cols) do - begin - index := j * Rows + i; - Result[index] := Input[i * Cols + j]; - end; -end; - -var - Cols, Rows: integer; - Numbers, Transposed: TIntegerList; -begin - if ParamCount <> 3 then - ShowUsage; - - if (not TryStrToInt(ParamStr(1), Cols)) or (not TryStrToInt(ParamStr(2), Rows)) then - ShowUsage; - - Numbers := ParseIntegerList(ParamStr(3)); - if Numbers.Count <> (Cols * Rows) then - begin - Numbers.Free; - ShowUsage; - end; - - Transposed := TransposeMatrix(Cols, Rows, Numbers); - try - Writeln(FormatIntegerList(Transposed)); - finally - Numbers.Free; - Transposed.Free; - end; -end. - -``` - -{% endraw %} - -Transpose Matrix in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/php/index.md b/docs/projects/transpose-matrix/php/index.md deleted file mode 100644 index b0e854b0ba..0000000000 --- a/docs/projects/transpose-matrix/php/index.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-03-27 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2023-03-27 -layout: default -tags: -- php -- transpose-matrix -title: Transpose Matrix in PHP -title1: Transpose -title2: Matrix in PHP ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function parse_int_array($str_values) -{ - $str_array = explode(",", $str_values); - $values = array(); - foreach ($str_array as $str_value) - { - $value = parse_int($str_value); - if ($value === FALSE) - { - return FALSE; - } - - array_push($values, $value); - } - - return $values; -} - -// Convert list to matrix -function convert_list_to_matrix($values, $num_cols) -{ - return array_chunk($values, $num_cols); -} - -// Transpose matrix -function transpose_matrix($matrix) -{ - // Get number of rows. - // If 1, use 'array_chunk' to output each value in the row to its own row. - // Otherwise, use 'array_map' with no function and the "splat" operator to - // output one value in each column and append it to each row - return (count($matrix) == 1) ? array_chunk($matrix[0], 1) : array_map(NULL, ...$matrix); -} - -// Show matrix as a list -function show_matrix_as_list($matrix) -{ - // Join each row value with a comma for each column value - printf( - "%s\n", - implode(", ", array_map( - function ($value) { return implode(", ", $value); }, - $matrix) - ) - ); -} - -// Exit if too few arguments -if (count($argv) < 4) -{ - usage(); -} - -// Parse 1st argument. Exit if invalid or less than 1 -$num_cols = parse_int($argv[1]); -if ($num_cols === FALSE || $num_cols < 1) -{ - usage(); -} - -// Parse 2nd argument. Exit if invalid or less than 1 -$num_rows = parse_int($argv[2]); -if ($num_rows === FALSE || $num_rows < 1) -{ - usage(); -} - -// Parse 3nd argument. Exit if invalid if incorrect size -$values = parse_int_array($argv[3]); -if ($values == FALSE || count($values) != $num_rows * $num_cols) -{ - usage(); -} - -// Convert list to matrix -$matrix = convert_list_to_matrix($values, $num_cols); - -// Transpose matrix -$matrix_t = transpose_matrix($matrix); - -// Show matrix as a list -show_matrix_as_list($matrix_t); - -``` - -{% endraw %} - -Transpose Matrix in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/powershell/index.md b/docs/projects/transpose-matrix/powershell/index.md deleted file mode 100644 index 6a6db64623..0000000000 --- a/docs/projects/transpose-matrix/powershell/index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -authors: -- rzuckerm -date: 2025-07-20 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2025-07-20 -layout: default -tags: -- powershell -- transpose-matrix -title: Transpose Matrix in PowerShell -title1: Transpose Matrix -title2: in PowerShell ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please enter the dimension of the matrix and the serialized matrix" - Exit 1 -} - -function Parse-IntList([string]$Str) { - @($Str.Split(",") | ForEach-Object { [int]::Parse($_) }) -} - -function ConvertTo-Matrix([int]$numCols, [int]$numRows, [array]$values) { - @(0..($numRows - 1) | ForEach-Object { , $values[($_ * $numCols)..($_ * $numCols + $numCols - 1)]}) -} - -function Invoke-TransposeMatrix($matrix) { - @(0..($matrix[0].Length - 1) | ForEach-Object { - $i = $_ - , (0..($matrix.Length - 1) | ForEach-Object { $matrix[$_][$i]}) - }) -} - -function ConvertFrom-Matrix([int[][]]$matrix) { - @($matrix | ForEach-Object { $_ }) -} - -if ($args.Length -lt 3 -or -not $args[2]) { - Show-Usage -} - -try { - $numCols = [int]::Parse($args[0]) - $numRows = [int]::Parse($args[1]) - $values = Parse-IntList($args[2]) - if ($numCols * $numRows -ne $values.Length) { - Show-Usage - } -} catch { - Show-Usage -} - -$matrix = ConvertTo-Matrix $numCols $numRows $values -$tMatrix = Invoke-TransposeMatrix $matrix -$tValues = ConvertFrom-Matrix $tMatrix -Write-Output ($tValues -join ', ') - -``` - -{% endraw %} - -Transpose Matrix in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/python/index.md b/docs/projects/transpose-matrix/python/index.md deleted file mode 100644 index 80f2554477..0000000000 --- a/docs/projects/transpose-matrix/python/index.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -authors: -- Jeremy Grifski -date: 2022-05-13 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2022-05-13 -layout: default -tags: -- python -- transpose-matrix -title: Transpose Matrix in Python -title1: Transpose Matrix -title2: in Python ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys - -if len(sys.argv) != 4 or any(not x for x in sys.argv[1:]): - print("Usage: please enter the dimension of the matrix and the serialized matrix") - sys.exit(1) - -columns = int(sys.argv[1]) -rows = int(sys.argv[2]) -serial_matrix = [int(x) for x in sys.argv[3].split(',')] -matrix = [[serial_matrix[i * columns + j] for j in range(columns)] for i in range(rows)] -transposed_matrix = [[matrix[j][i] for j in range(rows)] for i in range(columns)] -serial_transposed_matrix = [x for row in transposed_matrix for x in row] -print(serial_transposed_matrix) - -``` - -{% endraw %} - -Transpose Matrix in [Python](/languages/python) was written by: - -- Jeremy Grifski - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/ruby/index.md b/docs/projects/transpose-matrix/ruby/index.md deleted file mode 100644 index 23d6ab1f78..0000000000 --- a/docs/projects/transpose-matrix/ruby/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-05-14 -layout: default -tags: -- ruby -- transpose-matrix -title: Transpose Matrix in Ruby -title1: Transpose -title2: Matrix in Ruby ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = "Usage: please enter the dimension of the matrix and the serialized matrix" - -def usage! - warn USAGE - exit 1 -end - -def parse_int(str) - Integer(str) -rescue ArgumentError, NoMethodError - usage! -end - -def parse_list(str) - str.split(",").map { parse_int(it.strip) } -end - -cols_str, rows_str, matrix_str = ARGV - -usage! if cols_str.nil? || rows_str.nil? || matrix_str.nil? -usage! if cols_str.strip.empty? || rows_str.strip.empty? || matrix_str.strip.empty? - -cols = parse_int(cols_str) -rows = parse_int(rows_str) - -usage! if cols <= 0 || rows <= 0 - -flat = parse_list(matrix_str) -usage! if flat.length != cols * rows - -matrix = flat.each_slice(cols).to_a -transposed = matrix.transpose - -puts transposed.flatten.join(", ") - -``` - -{% endraw %} - -Transpose Matrix in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/rust/index.md b/docs/projects/transpose-matrix/rust/index.md deleted file mode 100644 index 1111f0989b..0000000000 --- a/docs/projects/transpose-matrix/rust/index.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -authors: -- rzuckerm -date: 2023-04-17 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2023-05-08 -layout: default -tags: -- rust -- transpose-matrix -title: Transpose Matrix in Rust -title1: Transpose -title2: Matrix in Rust ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::env::args; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please enter the dimension of the matrix and the serialized matrix"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn parse_int_list(s: &str) -> Result, ::Err> { - s.split(',') - .map(parse_int) - .collect::, ::Err>>() -} - -type Matrix = Vec>; - -fn convert_array_to_matrix( - arr: Vec, num_rows: usize, num_cols: usize -) -> Matrix { - // Combine 'num_rows' vectors of 'num_cols' items from array - let mut arr_iter = arr.iter(); - (0..num_rows) - .map(|_| - (0..num_cols) - .map(|_| *arr_iter.next().unwrap()) - .collect::>() - ) - .collect::>() -} - -fn transpose_matrix(matrix: Matrix) -> Matrix { - let num_rows = matrix.len(); - let num_cols = matrix[0].len(); - - // Construct transposed matrix by grabbing one item from each row - // and combining them - (0..num_cols) - .map(|col| - (0..num_rows) - .map(|row| matrix[row][col]) - .collect::>() - ) - .collect::>() -} - -fn convert_matrix_to_array(matrix: Matrix) -> Vec { - let mut arr: Vec = vec![]; - for mut row in matrix { - arr.append(&mut row); - } - - arr -} - -fn main() { - let mut args = args().skip(1); - - // Convert 1st command-line argument to integer - let num_cols: usize = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 2nd command-line argument to integer - let num_rows: usize = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Convert 3rd command-line argument to list of integers - let arr: Vec = args - .next() - .and_then(|s| parse_int_list(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if invalid number of columns, rows, and size of array - if num_cols == 0 || - num_rows == 0 || - arr.len() != num_cols * num_rows { - usage() - } - - // Convert array to matrix - let matrix: Matrix = convert_array_to_matrix::(arr, num_rows, num_cols); - - // Transpose matrix - let matrix_t = transpose_matrix::(matrix); - - // Show transposed matrix as an array - let arr_t = convert_matrix_to_array::(matrix_t); - println!("{arr_t:?}"); -} - -``` - -{% endraw %} - -Transpose Matrix in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/swift/index.md b/docs/projects/transpose-matrix/swift/index.md deleted file mode 100644 index 6b02a609e8..0000000000 --- a/docs/projects/transpose-matrix/swift/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-03 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-05-03 -layout: default -tags: -- swift -- transpose-matrix -title: Transpose Matrix in Swift -title1: Transpose -title2: Matrix in Swift ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -let usage = "Usage: please enter the dimension of the matrix and the serialized matrix" - -extension StringProtocol { - var trimmed: String { trimmingCharacters(in: .whitespacesAndNewlines) } -} - -func parseInt(_ s: String?) -> Int? { - guard let s = s else { return nil } - return Int(s.trimmed) -} - -func parseMatrix(_ input: String, rows: Int, cols: Int) -> [Int]? { - let values = input - .split(separator: ",") - .compactMap { Int($0.trimmed) } - - guard values.count == rows * cols else { return nil } - return values -} - -func transpose(_ matrix: [Int], rows: Int, cols: Int) -> [Int] { - var result = [Int]() - result.reserveCapacity(matrix.count) - - for c in 0..= 4, - let cols = parseInt(args[1]), - let rows = parseInt(args[2]), - let matrix = parseMatrix(args[3], rows: rows, cols: cols) -else { - print(usage) - exit(1) -} - -let result = transpose(matrix, rows: rows, cols: cols) -print(result.map(String.init).joined(separator: ", ")) -``` - -{% endraw %} - -Transpose Matrix in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/tcl/index.md b/docs/projects/transpose-matrix/tcl/index.md deleted file mode 100644 index 9ec71ba787..0000000000 --- a/docs/projects/transpose-matrix/tcl/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2025-10-09 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2025-10-09 -layout: default -tags: -- tcl -- transpose-matrix -title: Transpose Matrix in Tcl -title1: Transpose -title2: Matrix in Tcl ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -package require Tcl 8.6 -package require struct::matrix - -proc usage {} { - puts stderr {Usage: please enter the dimension of the matrix and the serialized matrix} - exit 1 -} - -if {$argc != 3} { usage } -set cols [lindex $argv 0] -set rows [lindex $argv 1] -set matrixStr [lindex $argv 2] - -if {$cols eq "" || $rows eq "" || $matrixStr eq ""} { usage } - -if {![string is integer -strict $cols] || ![string is integer -strict $rows]} { - usage -} - -set values [lmap v [split $matrixStr ","] {string trim $v}] -if {[llength $values] != $cols * $rows} { usage } - -set m [struct::matrix] -$m add columns $cols -$m add rows $rows - -for {set r 0} {$r < $rows} {incr r} { - set start [expr {$r*$cols}] - set end [expr {($r+1)*$cols - 1}] - $m set row $r [lrange $values $start $end] -} - -$m transpose - -set outList {} -for {set i 0} {$i < $cols} {incr i} { - lappend outList {*}[$m get row $i] -} - -puts [join $outList ", "] - - -``` - -{% endraw %} - -Transpose Matrix in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/typescript/index.md b/docs/projects/transpose-matrix/typescript/index.md deleted file mode 100644 index 89b58b87d2..0000000000 --- a/docs/projects/transpose-matrix/typescript/index.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -authors: -- Vipin Yadav -date: 2023-10-07 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2023-10-07 -layout: default -tags: -- transpose-matrix -- typescript -title: Transpose Matrix in TypeScript -title1: Transpose Matrix -title2: in TypeScript ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -const error_msg: string = "Usage: please enter the dimension of the matrix and the serialized matrix"; -if (process.argv.length != 5) { - console.log(error_msg); - process.exit(1); -} -const cols: number = parseInt(process.argv[2]); -const rows: number = parseInt(process.argv[3]); -const list_str: string = process.argv[4]; -if (isNaN(cols) || isNaN(rows) || list_str.length == 0) { - console.log(error_msg); - process.exit(1); -} -const list: number[] = list_str.split(",").map(function (x: string) { return parseInt(x); }); - -const matrix: number[][] = []; -for (let i: number = 0; i < rows; i++) { - matrix.push(list.slice(i * cols, (i + 1) * cols)); -} -const transpose: number[][] = []; -for (let i: number = 0; i < cols; i++) { - transpose.push([]); - for (let j: number = 0; j < rows; j++) { - transpose[i].push(matrix[j][i]); - } -} -console.log(transpose.map(function (x: number[]) { return x.join(", "); }).join(", ")); -``` - -{% endraw %} - -Transpose Matrix in [TypeScript](/languages/typescript) was written by: - -- Vipin Yadav - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/transpose-matrix/visual-basic/index.md b/docs/projects/transpose-matrix/visual-basic/index.md deleted file mode 100644 index 8c9ed2cd16..0000000000 --- a/docs/projects/transpose-matrix/visual-basic/index.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: transpose-matrix-in-every-language.jpg -last-modified: 2026-05-07 -layout: default -tags: -- transpose-matrix -- visual-basic -title: Transpose Matrix in Visual Basic -title1: Transpose Matrix -title2: in Visual Basic ---- - - - -Welcome to the [Transpose Matrix](/projects/transpose-matrix) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module TransposeMatrix - - Private Sub ShowUsage() - Console.Error.WriteLine("Usage: please enter the dimension of the matrix and the serialized matrix") - Environment.Exit(1) - End Sub - - - Private Function ParseIntegerList(input As String) As List(Of Integer) - - If String.IsNullOrWhiteSpace(input) Then - ShowUsage() - End If - - Dim numbers As New List(Of Integer) - - For Each token In input.Split(","c, StringSplitOptions.RemoveEmptyEntries Or StringSplitOptions.TrimEntries) - - Dim value As Integer - - If Not Integer.TryParse(token, value) Then - ShowUsage() - End If - - numbers.Add(value) - - Next - - Return numbers - - End Function - - - Private Function TransposeMatrix(cols As Integer, rows As Integer, input As List(Of Integer)) As List(Of Integer) - - Dim result As New List(Of Integer)(New Integer(rows * cols - 1) {}) - - For i As Integer = 0 To rows - 1 - - For j As Integer = 0 To cols - 1 - - Dim sourceIndex As Integer = i * cols + j - Dim targetIndex As Integer = j * rows + i - - result(targetIndex) = input(sourceIndex) - - Next - - Next - - Return result - - End Function - - - Public Sub Main(args As String()) - - If args.Length <> 3 Then - ShowUsage() - End If - - Dim cols As Integer - Dim rows As Integer - - If Not Integer.TryParse(args(0), cols) OrElse Not Integer.TryParse(args(1), rows) Then - ShowUsage() - End If - - Dim numbers = ParseIntegerList(args(2)) - - If numbers.Count <> cols * rows Then - ShowUsage() - End If - - Dim transposed = TransposeMatrix(cols, rows, numbers) - - Console.WriteLine(String.Join(", ", transposed)) - - End Sub - -End Module -``` - -{% endraw %} - -Transpose Matrix in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/algol60/index.md b/docs/projects/zeckendorf/algol60/index.md deleted file mode 100644 index 7c1c159593..0000000000 --- a/docs/projects/zeckendorf/algol60/index.md +++ /dev/null @@ -1,261 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-30 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-11 -layout: default -tags: -- algol60 -- zeckendorf -title: Zeckendorf in ALGOL 60 -title1: Zeckendorf -title2: in ALGOL 60 ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [ALGOL 60](/languages/algol60) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_60 -begin - procedure usage; - begin - outstring(1, "Usage: please input a non-negative integer\n"); - stop - end usage; - - comment Input a digit character from stdin and return the following: - - "0" to "9" maps to 0 to 9 - - "+" maps to 10 - - "-" maps to 11 - - whitespace maps to 12 - - null byte maps to -1 - - invalid bytes map to -2; - integer procedure indigit; - begin - comment Mapping: - - "0" to "9" maps to 1 to 10 - - "+" maps to 11 - - "-" maps to 12 - - "\t" maps to 13 - - "\r" maps to 14 - - "\n" maps to 15 - - " " maps to 16 - - null byte maps to 17 - - invalid byte maps to 0; - integer ch; - inchar(0, "0123456789+-\t\r\n ", ch); - if ch < 1 then ch := -2 - else if ch < 13 then ch := ch - 1 - else if ch < 17 then ch := 12 - else ch := -1; - indigit := ch - end indigit; - - comment Input an integer from stdin into 'result' and parse it. - The last character is read into 'ch'. - return true if integer is valid, false otherwise; - boolean procedure inValidInteger(result, ch); - integer result, ch; - begin - boolean valid; - integer s; - - result := 0; - valid := false; - s := 1; - - comment Ignore whitespace; - whiteloop: - ch := indigit; - if ch = 12 then goto whiteloop; - - comment Process signs: ignore "+" and invert sign if "-"; - signloop: - if ch = 10 | ch = 11 then - begin - if ch = 11 then s := -s; - ch := indigit; - goto signloop - end; - - comment Indicate valid if "0" to "9"; - if ch >= 0 & ch <= 9 then valid := true; - - comment Process digits: update value; - valueloop: - if ch >= 0 & ch <= 9 then - begin - comment Invalid if overflow or underflow; - if (s > 0 & (maxint - ch) % 10 < result) | - (s < 0 & (-1 - maxint + ch) % 10 > result) then valid := false; - - result := result * 10 + s * ch; - ch := indigit; - goto valueloop - end; - - comment Ignore characters until end of argument. Indicate invalid - if not whitespace; - ignoreloop: - if ch != -1 then - begin - if ch != 12 then valid := false; - ch := indigit; - goto ignoreloop - end; - - inValidInteger := valid - end inValidInteger; - - comment Number of Fibonacci numbers before the math overflows; - integer procedure maxfibs; - begin - maxfibs := 43 - end maxfibs; - - integer procedure fibonacciUpTo(n, fibs); - value n; - integer n; - integer array fibs; - begin - integer a, b, c, idx; - - a := 1; - b := 2; - idx := 0; - fibloop: - if a <= n & idx < maxfibs then - begin - idx := idx + 1; - fibs[idx] := a; - c := a + b; - a := b; - b := c; - goto fibloop - end; - fibonacciUpTo := idx - end fibonacciUpTo; - - integer procedure zeckendorf(n, zecks); - value n; - integer n; - integer array zecks; - begin - integer numFibs, fibIdx, zeckIdx, fib; - integer array fibs[1:maxfibs]; - - comment Get Fibonacci numbers up to and including n; - numFibs := fibonacciUpTo(n, fibs); - - comment Going from largest to smallest, repeat until no more Fibonacci numbers - left or sum of Fibonacci numbers is equal to n; - fibIdx := numFibs; - zeckIdx := 0; - zeckloop: - if fibIdx > 0 & n > 0 then - begin - comment If this Fibonacci number is less than or equal to n, use it and skip the - previous Fibonacci number. Otherwise, go to previous Fibonacci number; - fib := fibs[fibIdx]; - if fib <= n then - begin - zeckIdx := zeckIdx + 1; - zecks[zeckIdx] := fib; - fibIdx := fibIdx - 2; - n := n - fib - end - else fibIdx := fibIdx - 1; - goto zeckloop - end; - - zeckendorf := zeckIdx - end zeckendorf; - - comment Output integer without space. This is needed since ALGOL60 - 'outinteger' automatically adds a space after the integer. - Source: 'outinteger' function source code in Appendix 2 of - https://www.algol60.org/reports/algol60_mr.pdf; - procedure outIntegerNoSpace(x); - value x; - integer x; - begin - procedure digits(x); - value x; - integer x; - begin - integer d; - d := x % 10; - x := x - 10 * d; - if d != 0 then digits(d); - outchar(1, "0123456789", iabs(x) + 1) - end digits; - if x < 0 then outstring(1, "-"); - digits(x) - end outIntegerNoSpace; - - comment Output integer array; - procedure outIntegerArray(arr, arrLen); - value arrLen; - integer array arr; - integer arrLen; - begin - integer i; - for i := 1 step 1 until arrLen do - begin - if i > 1 then outstring(1, ", "); - outIntegerNoSpace(arr[i]) - end; - - if arrLen > 0 then outstring(1, "\n") - end outIntegerArray; - - integer argc, result, ch, numZecks; - - comment Get number of parameters. Exit if too few; - ininteger(0, argc); - if argc < 1 then usage; - - comment Get integer value from 1st argument. Exit if invalid or - negative; - if !inValidInteger(result, ch) | result < 0 then usage; - - begin - comment Output Zeckendorf values; - integer array zecks[1:(maxfibs + 1) % 2]; - numZecks := zeckendorf(result, zecks); - outIntegerArray(zecks, numZecks) - end -end - -``` - -{% endraw %} - -Zeckendorf in [ALGOL 60](/languages/algol60) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/algol68/index.md b/docs/projects/zeckendorf/algol68/index.md deleted file mode 100644 index 1bbef5f61e..0000000000 --- a/docs/projects/zeckendorf/algol68/index.md +++ /dev/null @@ -1,203 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-01-20 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-01-20 -layout: default -tags: -- algol68 -- zeckendorf -title: Zeckendorf in ALGOL 68 -title1: Zeckendorf -title2: in ALGOL 68 ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [ALGOL 68](/languages/algol68) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```algol_68 -# Number of Fibonacci numbers before the math overflows # -INT max fibonaccis = 43; - -MODE PARSEINT_RESULT = STRUCT(BOOL valid, INT value, STRING leftover); - -PROC parse int = (REF STRING s) PARSEINT_RESULT: -( - BOOL valid := FALSE; - REAL r := 0.0; - INT n := 0; - STRING leftover; - - # Associate string with a file # - FILE f; - associate(f, s); - - # On end of input, exit if valid number not seen. Otherwise ignore it # - on logical file end(f, (REF FILE dummy) BOOL: - ( - IF NOT valid THEN done FI; - TRUE - ) - ); - - # Exit if value error # - on value error(f, (REF FILE dummy) BOOL: done); - - # Convert string to real number # - get(f, r); - - # If real number is in range of an integer, convert to integer. Indicate integer is valid if same as real # - IF ABS r <= max int - THEN - n := ENTIER(r); - valid := (n = r) - FI; - - # Get leftover string # - get(f, leftover); - -done: - close(f); - PARSEINT_RESULT(valid, n, leftover) -); - -PROC usage = VOID: printf(($gl$, "Usage: please input a non-negative integer")); - -COMMENT -fib(n) = fib(n - 1) + fib(n - 2) -where: -- fib(0) = 0 -- fib(1) = 1 -- fib(2) = 1 -- fib(3) = 2 -COMMENT -MODE FIBSTATE = STRUCT(INT prev, INT result); -PROC init fib = FIBSTATE: FIBSTATE(1, 2); -OP FIB = (FIBSTATE state) FIBSTATE: (result OF state, prev OF state + result OF state); -OP FIBRESULT = (FIBSTATE state) INT: prev OF state; - -PROC fibonacci up to = (INT n) REF [] INT: -( - # Temporary array that can handle Fibonacci numbers # - REF [] INT temp results = HEAP [1:max fibonaccis] INT; - - # Initialize Fibonacci state # - FIBSTATE state := init fib; - - # Collect all Fibonacci numbers up to the specified value # - INT idx := 0; - WHILE FIBRESULT state <= n AND idx < max fibonaccis - DO - idx +:= 1; - temp results[idx] := FIBRESULT state; - state := FIB state - OD; - - # Resize results # - REF [] INT results := HEAP [1:idx] INT; - results := temp results[1:idx]; - results -); - -PROC zeckendorf = (INT n) REF [] INT: -( - # Get Fibonacci numbers up to and including n # - REF [] INT fibs = fibonacci up to(n); - - # Allocate temporary space for Zeckendorf values # - INT num fibs := UPB fibs; - REF [] INT temp results := HEAP [1:ENTIER((num fibs + 1) / 2)] INT; - - # Going from largest to smallest, repeat until no more Fibonacci numbers # - # left or sum of Fibonacci numbers is equal to n # - INT fib idx := num fibs; - INT zeck idx := 0; - INT remaining := n; - WHILE fib idx > 0 AND remaining > 0 - DO - # If this Fibonacci number is less than or equal to n, use it and skip the # - # previous Fibonacci number. Otherwise, go to previous Fibonacci number # - INT fib = fibs[fib idx]; - IF fib <= remaining - THEN - zeck idx +:= 1; - temp results [zeck idx] := fib; - fib idx -:= 2; - remaining -:= fib - ELSE - fib idx -:= 1 - FI - OD; - - # Resize results # - REF [] INT results := HEAP [1:zeck idx] INT; - results := temp results[1:zeck idx]; - results -); - -PROC show list values = (REF []INT values) VOID: -( - INT n = UPB values; - FOR k TO n - DO - IF k > 1 - THEN - print(", ") - FI; - - print(whole(values[k], 0)) - OD; - - IF n > 0 - THEN - print(newline) - FI -); - -# Parse 1st command-line argument # -STRING s := argv(4); -PARSEINT_RESULT result := parse int(s); - -# If invalid or extra characters or negative number, exit # -INT n := value OF result; -IF NOT (valid OF result) OR (leftover OF result) /= "" OR n < 0 -THEN - usage; - stop -FI; - -REF [] INT results := zeckendorf(n); -show list values(results) - -``` - -{% endraw %} - -Zeckendorf in [ALGOL 68](/languages/algol68) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/awk/index.md b/docs/projects/zeckendorf/awk/index.md deleted file mode 100644 index d3578960cf..0000000000 --- a/docs/projects/zeckendorf/awk/index.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-01-31 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-01-31 -layout: default -tags: -- awk -- zeckendorf -title: Zeckendorf in AWK -title1: Zeckendorf -title2: in AWK ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [AWK](/languages/awk) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```awk -function usage() { - print "Usage: please input a non-negative integer" - exit(1) -} - -function str_to_number(s) { - return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR" -} - -function fibonacci_up_to(n, fibs, a, b, c, k) { - a = 1 - b = 2 - for (k = 1; a <= n; k++) { - fibs[k] = a - c = a + b - a = b - b = c - } -} - -function zeckendorf(n, zecks, i, k) { - fibonacci_up_to(n, fibs) - k = length(fibs) - i = 1 - while (k > 0 && n > 0) { - fib = fibs[k] - if (fib <= n) { - zecks[i++] = fib - n -= fib - k -= 2 - } else { - k-- - } - } -} - -function show_array(arr, idx, s) { - s = "" - for (idx in arr) { - if (s) { - s = s ", " - } - s = s arr[idx] - } - - print s -} - -BEGIN { - if (ARGC < 2) { - usage() - } - - n = str_to_number(ARGV[1]) - if (n == "ERROR" || n < 0) { - usage() - } - - zeckendorf(n, zecks) - show_array(zecks) -} - -``` - -{% endraw %} - -Zeckendorf in [AWK](/languages/awk) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/beef/index.md b/docs/projects/zeckendorf/beef/index.md deleted file mode 100644 index 3b494725e7..0000000000 --- a/docs/projects/zeckendorf/beef/index.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-01-31 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-01-31 -layout: default -tags: -- beef -- zeckendorf -title: Zeckendorf in Beef -title1: Zeckendorf -title2: in Beef ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Beef](/languages/beef) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```beef -using System; -using System.Collections; - -namespace Zeckendorf; - -class Program -{ - public static void Usage() - { - Console.WriteLine("Usage: please input a non-negative integer"); - Environment.Exit(0); - } - - public static Result ParseInt(StringView str) - where T : IParseable - { - StringView trimmedStr = scope String(str); - trimmedStr.Trim(); - - // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 - if (trimmedStr.Contains('\'')) - { - return .Err; - } - - return T.Parse(trimmedStr); - } - - public static void FibonacciUpTo(T n, List fibs) - where T : IInteger, operator explicit int, operator T + T, operator T - T - where int : operator explicit T, operator T <=> T - { - T a = (T)1; - T b = (T)2; - fibs.Clear(); - while (a <= n) { - fibs.Add(a); - b += a; - a = b - a; - } - } - - public static void Zeckendorf(T n, List zecks) - where T : IInteger, operator explicit int, operator T + T, operator T - T - where int : operator explicit T, operator T <=> T - { - List fibs = scope .(); - FibonacciUpTo(n, fibs); - zecks.Clear(); - int k = fibs.Count - 1; - T remaining = n; - while (k >= 0 && remaining > (T)0) { - T fib = fibs[k]; - if (fib <= remaining) { - zecks.Add(fib); - remaining -= fib; - k -= 2; - } else { - k--; - } - } - } - - public static void ShowList(List arr) - { - String line = scope .(); - for (T val in arr) - { - if (!line.IsEmpty) - { - line += ", "; - } - - line.AppendF("{}", val); - } - - Console.WriteLine(line); - } - - public static int Main(String[] args) - { - if (args.Count < 1) - { - Usage(); - } - - int32 n = 0; - switch (ParseInt(args[0])) - { - case .Ok(out n): - if (n < 0) { - Usage(); - } - case .Err: - Usage(); - } - - List zecks = scope .(); - Zeckendorf(n, zecks); - ShowList(zecks); - return 0; - } -} - -``` - -{% endraw %} - -Zeckendorf in [Beef](/languages/beef) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/c-plus-plus/index.md b/docs/projects/zeckendorf/c-plus-plus/index.md deleted file mode 100644 index 419f20582e..0000000000 --- a/docs/projects/zeckendorf/c-plus-plus/index.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-11 -layout: default -tags: -- c-plus-plus -- zeckendorf -title: Zeckendorf in C++ -title1: Zeckendorf -title2: in C++ ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [C++](/languages/c-plus-plus) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c++ -#include -#include -#include -#include -#include -#include -#include - -namespace Zeckendorf -{ -constexpr auto generate_fibs() noexcept -{ - std::array arr{}; // 93rd overflows uint64_t - arr[0] = 1; - arr[1] = 2; - for (size_t i = 2; i < arr.size(); ++i) - arr[i] = arr[i - 1] + arr[i - 2]; - return arr; -} - -static constexpr auto fibs = generate_fibs(); - -void print_representation(uint64_t n) -{ - if (n == 0) - { - std::cout << "\n"; - return; - } - - // O(log N) lookup - auto it = std::upper_bound(fibs.begin(), fibs.end(), n); - bool first = true; - - while (it != fibs.begin()) - { - --it; - if (*it <= n) - { - std::cout << (first ? "" : ", ") << *it; - n -= *it; - first = false; - } - } - std::cout << '\n'; -} -} // namespace Zeckendorf - -[[nodiscard]] std::optional try_parse_arg(std::string_view s) noexcept -{ - if (s.empty() || s.front() == '-' || s.front() == '+') - return std::nullopt; - - uint64_t value{}; - const auto [ptr, ec] = - std::from_chars(s.data(), s.data() + s.size(), value); - - if (ec != std::errc{} || ptr != s.data() + s.size()) - return std::nullopt; - - return value; -} - -void usage() -{ - std::cerr << "Usage: please input a non-negative integer\n"; -} - -int main(int argc, char *argv[]) -{ - if (argc != 2) - { - usage(); - return EXIT_FAILURE; - } - - if (auto value = try_parse_arg(argv[1])) - { - Zeckendorf::print_representation(*value); - return EXIT_SUCCESS; - } - - usage(); - return EXIT_FAILURE; -} -``` - -{% endraw %} - -Zeckendorf in [C++](/languages/c-plus-plus) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/c-sharp/index.md b/docs/projects/zeckendorf/c-sharp/index.md deleted file mode 100644 index f0ab6e3297..0000000000 --- a/docs/projects/zeckendorf/c-sharp/index.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-05-13 -layout: default -tags: -- c-sharp -- zeckendorf -title: Zeckendorf in C# -title1: Zeckendorf -title2: in C# ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [C#](/languages/c-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c# -using System; -using System.Collections.Generic; -using System.Globalization; - -if (args is not [var raw] || - !long.TryParse(raw, out long n) || - n < 0) -{ - return ExitWithUsage(); -} - -if (n == 0) - return 0; - -ReadOnlySpan fibs = GenerateFibs(); -Span buffer = stackalloc long[fibs.Length]; - -int count = Decompose(n, fibs, buffer); -Console.WriteLine(string.Join(", ", buffer[..count].ToArray())); - -return 0; - -static int Decompose(long n, ReadOnlySpan fibs, Span result) -{ - int count = 0; - - for (int i = fibs.Length - 1; i >= 0 && n > 0; i--) - { - long f = fibs[i]; - - if (f <= n) - { - result[count++] = f; - n -= f; - } - } - - return count; -} - -static int ExitWithUsage() -{ - Console.WriteLine("Usage: please input a non-negative integer"); - return 1; -} - -static long[] GenerateFibs() -{ - var list = new List { 1, 2 }; - - while (true) - { - long next = list[^1] + list[^2]; - if (next < 0 || next > long.MaxValue - list[^1]) - break; - - list.Add(next); - } - - return list.ToArray(); -} -``` - -{% endraw %} - -Zeckendorf in [C#](/languages/c-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/c/index.md b/docs/projects/zeckendorf/c/index.md deleted file mode 100644 index ee0b6b81ea..0000000000 --- a/docs/projects/zeckendorf/c/index.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-15 -layout: default -tags: -- c -- zeckendorf -title: Zeckendorf in C -title1: Zeckendorf -title2: in C ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [C](/languages/c) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```c -#include -#include -#include -#include -#include -#include - -static void usage(void) -{ - fputs("Usage: please input a non-negative integer\n", stderr); - exit(EXIT_FAILURE); -} - -void zeckendorf(uint64_t n) -{ - if (n == 0) - { - putchar('\n'); - return; - } - - uint64_t a = 1, b = 2; - - while (b <= n) - { - uint64_t next = a + b; - a = b; - b = next; - } - - bool first = true; - - while (n > 0) - { - if (a <= n) - { - if (!first) - fputs(", ", stdout); - printf("%" PRIu64, a); - n -= a; - first = false; - } - - uint64_t prev = b - a; - b = a; - a = prev; - } - - putchar('\n'); -} - -int main(int argc, char *argv[]) -{ - if (argc != 2) - usage(); - - const char *s = argv[1]; - char *end = NULL; - - errno = 0; - uint64_t n = strtoull(s, &end, 10); - - if (*s == '\0' || *end != '\0' || errno == ERANGE || *s == '-') - usage(); - - zeckendorf(n); - return EXIT_SUCCESS; -} -``` - -{% endraw %} - -Zeckendorf in [C](/languages/c) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/cobol/index.md b/docs/projects/zeckendorf/cobol/index.md deleted file mode 100644 index 9d7338fb8e..0000000000 --- a/docs/projects/zeckendorf/cobol/index.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-24 -layout: default -tags: -- cobol -- zeckendorf -title: Zeckendorf in COBOL -title1: Zeckendorf -title2: in COBOL ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [COBOL](/languages/cobol) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```cobol -identification division. -program-id. zeckendorf. - -data division. -working-storage section. - -01 input-str pic x(32). -01 n pic 9(18) comp. - -01 a pic 9(18) comp. -01 b pic 9(18) comp. -01 c pic 9(18) comp. -01 last-valid pic 9(18) comp. - -01 first-flag pic 9 value 1. - 88 is-first value 1. - 88 not-first value 0. - -01 display-num pic ---------9. -01 separator pic x(2) value ", ". - -procedure division. - -main. - perform get-input - perform solve - goback. - - -get-input. - accept input-str from argument-value - - if input-str = spaces - perform show-usage - end-if - - if function trim(input-str) not numeric - perform show-usage - end-if - - compute n = function numval(input-str) - - if n < 0 - perform show-usage - end-if. - - -solve. - if n = 0 - exit paragraph - end-if - - set is-first to true - - perform until n = 0 - - move 1 to a - move 2 to b - - perform until b > n - compute c = a + b - move b to a - move c to b - end-perform - - move a to last-valid - - if not-first - display separator with no advancing - end-if - - move last-valid to display-num - display function trim(display-num) with no advancing - - subtract last-valid from n - set not-first to true - - end-perform - - display space. - - -show-usage. - display "Usage: please input a non-negative integer" - stop run. - -``` - -{% endraw %} - -Zeckendorf in [COBOL](/languages/cobol) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/commodore-basic/index.md b/docs/projects/zeckendorf/commodore-basic/index.md deleted file mode 100644 index 5a42fb6f5f..0000000000 --- a/docs/projects/zeckendorf/commodore-basic/index.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-01-31 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-01-31 -layout: default -tags: -- commodore-basic -- zeckendorf -title: Zeckendorf in Commodore BASIC -title1: Zeckendorf in -title2: Commodore BASIC ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Commodore BASIC](/languages/commodore-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```commodore_basic -5 REM Input N -10 GOSUB 1000 -20 IF V = 0 OR C >=0 OR NR < 0 THEN GOTO 110: REM invalid or not end character -30 N = NR -35 REM Max Fibonacci numbers than can be displayed as integers -40 MF = 43 -50 DIM F(MF - 1) -55 REM Max Zeckendorf values -60 MZ = INT((MF + 1) / 2) -70 DIM A(MZ - 1) -75 REM Get Zeckendorf values -80 GOSUB 2000 -85 REM Display results -90 GOSUB 3500 -100 END -110 PRINT "Usage: please input a non-negative integer" -120 END -1000 REM Read input value one character at a time since Commodore BASIC -1001 REM has trouble reading line from stdin properly -1002 REM NR = number -1003 REM V = 1 if valid number, 0 otherwise -1004 REM C = -2 if end of input, -1 if end of value, -1005 REM 32 if whitespace, ASCII code of last character otherwise -1006 REM Initialize -1010 NR = 0 -1020 V = 0 -1030 S = 1 -1035 REM Loop while leading spaces -1040 GOSUB 1500 -1050 IF C = 43 OR C = 45 THEN GOTO 1100: REM + or - -1060 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1070 IF C = 32 THEN GOTO 1040: REM whitespace -1080 RETURN: REM other character -1085 REM Loop while sign -1090 GOSUB 1500 -1100 IF C = 43 THEN GOTO 1090: REM + -1110 IF C >= 48 AND C <= 57 THEN GOTO 1150: REM 0 to 9 -1120 IF C <> 45 THEN RETURN: REM not - -1130 S = -S -1140 GOTO 1090 -1145 REM Set valid flag -1150 V = 1 -1155 REM Loop while digits -1160 NR = (ABS(NR) * 10 + C - 48) * S -1170 GOSUB 1500 -1180 IF C >= 48 AND C <= 57 THEN GOTO 1160: REM 0 to 9 -1185 REM Loop while trailing spaces -1190 IF C < 0 OR C <> 32 THEN RETURN: REM end character or not whitespace -1200 GOSUB 1500 -1210 GOTO 1180 -1500 REM Get input character -1501 REM A$ = input character -1502 REM C = One of the following: -1502 REM - -1 if end of value -1503 REM - -2 if end of input -1504 REM - 32 if whitespace -1505 REM - ASCII code otherwise -1510 GET A$ -1520 C = ASC(A$) -1530 IF C = 13 THEN C = -1 -1540 IF C = 255 THEN C = -2 -1550 IF C = 9 OR C = 10 THEN C = 32 -1560 RETURN -2000 REM Get Zeckendorf values -2001 REM N = input number -2002 REM A = array containing Fibonacci numbers that add up to N -2003 REM NA = size of array -2005 REM Get Fibonacci numbers up to an including N -2010 GOSUB 3000 -2015 REM Get Fibonacci numbers that add up to N -2020 K = NF - 1 -2030 NA = 0 -2040 IF K < 0 OR N < 1 THEN GOTO 2130 -2045 REM Get Fibonacci value -2050 FV = F(K) -2060 K = K - 1 -2065 REM If Too large, get previous Fibonacci value -2070 IF FV > N THEN GOTO 2040 -2075 REM Store Fibonacci value and skip previous one -2080 A(NA) = FV -2090 NA = NA + 1 -2100 K = K - 1 -2110 N = N - FV -2120 GOTO 2040 -2130 RETURN -3000 REM Fibonacci numbers up to an including N -3001 REM N = input number -3002 REM F = array of Fibonacci -3003 REM NF = number of Fibonacci numbers -3010 FA = 1 -3020 FB = 2 -3030 NF = 0 -3040 IF FA > N OR NF >= MF THEN GOTO 3110 -3050 F(NF) = FA -3060 NF = NF + 1 -3070 FC = FA + FB -3080 FA = FB -3090 FB = FC -3100 GOTO 3040 -3110 RETURN -3500 REM Display array -3501 REM A contains array -3502 REM NA contains size of array -3510 IF NA < 1 THEN GOTO 3590 -3520 FOR I = 0 TO NA - 1 -3530 S$ = STR$(A(I)) -3540 IF A(I) >= 0 THEN S$ = MID$(S$, 2): REM strip leading space -3550 PRINT S$; -3560 IF I < (NA - 1) THEN PRINT ", "; -3570 NEXT I -3580 PRINT -3590 RETURN - -``` - -{% endraw %} - -Zeckendorf in [Commodore BASIC](/languages/commodore-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/euphoria/index.md b/docs/projects/zeckendorf/euphoria/index.md deleted file mode 100644 index a78d6b63bb..0000000000 --- a/docs/projects/zeckendorf/euphoria/index.md +++ /dev/null @@ -1,169 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-07 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-03-07 -layout: default -tags: -- euphoria -- zeckendorf -title: Zeckendorf in Euphoria -title1: Zeckendorf -title2: in Euphoria ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Euphoria](/languages/euphoria) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```euphoria -include std/io.e -include std/types.e -include std/text.e -include std/get.e as stdget -include std/sequence.e - --- Indices for value() return value -enum VALUE_ERROR_CODE, VALUE_VALUE, VALUE_NUM_CHARS_READ - --- Indices for parse_int() return value -enum PARSE_INT_VALID, PARSE_INT_VALUE - -function parse_int(sequence s) - -- Trim off whitespace and parse string - s = trim(s) - sequence result = stdget:value(s,, GET_LONG_ANSWER) - - -- Error if any errors, value is not an integer, or any leftover characters - boolean valid = ( - result[VALUE_ERROR_CODE] = GET_SUCCESS - and integer(result[VALUE_VALUE]) - and result[VALUE_NUM_CHARS_READ] = length(s) - ) - - -- Get value if invalid - integer value = 0 - if valid - then - value = result[VALUE_VALUE] - end if - - return {valid, value} -end function - -procedure usage() - puts(STDOUT, "Usage: please input a non-negative integer\n") - abort(0) -end procedure - -procedure show_list_values(sequence values) - if length(values) > 0 - then - sequence format = repeat_pattern("%d, ", length(values)) - sequence s = sprintf(format[1..$-2], values) - printf(STDOUT, "%s\n", {s}) - end if -end procedure - -function get_fibonacci_values(integer value) - -- Initialize Fibonacci state: - -- fib(2) = 1 - -- fib(3) = 2 - sequence fibs = {} - integer a = 1 - integer b = 2 - integer t - - -- Update Fibonacci state and store values - while a <= value - do - -- fib(n) = fib(n - 1) + fib(n - 2) - fibs &= a - t = a + b - a = b - b = t - end while - - return fibs -end function - -function get_zeckendorf_values(integer value) - sequence zecks = {} - - -- Go through Fibonacci numbers in reverse order, stopping when - -- remaining value is zero - sequence fibs = get_fibonacci_values(value) - integer n = length(fibs) - while n > 0 and value > 0 - do - -- If candidate Fibonacci number is greater than or equal to remaining value, - integer f = fibs[n] - if value >= f - then - -- Append Fibonacci number to result - zecks &= f - - -- Reduce remaining value - value -= f - - -- Skip previous value - n -= 2 - -- Else, go to previous value - else - n -= 1 - end if - end while - - return zecks -end function - --- Check 1st command-line argument -sequence argv = command_line() -if length(argv) < 4 or length(argv[4]) = 0 -then - usage() -end if - --- Parse 1st command-line argument -sequence result = parse_int(argv[4]) -integer value = result[PARSE_INT_VALUE] -if not result[PARSE_INT_VALID] or value < 0 -then - usage() -end if - ---Get Zeckendorf values -sequence values = get_zeckendorf_values(value) -show_list_values(values) - -``` - -{% endraw %} - -Zeckendorf in [Euphoria](/languages/euphoria) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/f-sharp/index.md b/docs/projects/zeckendorf/f-sharp/index.md deleted file mode 100644 index 53b28c9dbf..0000000000 --- a/docs/projects/zeckendorf/f-sharp/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-10 -layout: default -tags: -- f-sharp -- zeckendorf -title: Zeckendorf in F# -title1: Zeckendorf -title2: in F# ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [F#](/languages/f-sharp) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```f# -open System - -module Zeckendorf = - - let getDescendingFibs n = - let rec loop a b acc = - if a > n then acc - else loop b (a + b) (a :: acc) - - loop 1 2 [] - - let compute n = - if n = 0 then [] - else - let rec go remaining fibs acc = - match remaining, fibs with - | 0, _ -> List.rev acc - | _, [] -> List.rev acc - | r, f :: tail -> - if f <= r then - go (r - f) tail (f :: acc) - else - go r tail acc - - go n (getDescendingFibs n) [] - - let run n = - match compute n with - | [] -> "" - | fibs -> String.concat ", " (List.map string fibs) - -module Helpers = - - let usage = "Usage: please input a non-negative integer" - - let (|NonNegativeInt|_|) (s: string) = - match Int32.TryParse(s.Trim()) with - | true, n when n >= 0 -> Some n - | _ -> None - - let parseArgs = - function - | [| NonNegativeInt n |] -> Ok n - | _ -> Error usage - - let handleResult = - function - | Ok result -> - printfn "%s" result - 0 - | Error msg -> - eprintfn "%s" msg - 1 - -[] -let main argv = - argv - |> Helpers.parseArgs - |> Result.map Zeckendorf.run - |> Helpers.handleResult -``` - -{% endraw %} - -Zeckendorf in [F#](/languages/f-sharp) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/go/index.md b/docs/projects/zeckendorf/go/index.md deleted file mode 100644 index 2562ace773..0000000000 --- a/docs/projects/zeckendorf/go/index.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-24 -layout: default -tags: -- go -- zeckendorf -title: Zeckendorf in Go -title1: Zeckendorf -title2: in Go ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Go](/languages/go) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```go -package main - -import ( - "fmt" - "os" - "strconv" - "strings" -) - -func main() { - if len(os.Args) != 2 { - fmt.Println("Usage: please input a non-negative integer") - return - } - - n, err := strconv.Atoi(os.Args[1]) - if err != nil || n < 0 { - fmt.Println("Usage: please input a non-negative integer") - return - } - - if n == 0 { - fmt.Println("") - return - } - - var result []string - - for n > 0 { - a, b := 1, 2 - prev := 1 - - for b <= n { - prev = b - a, b = b, a+b - } - - result = append(result, strconv.Itoa(prev)) - n -= prev - } - - fmt.Println(strings.Join(result, ", ")) -} -``` - -{% endraw %} - -Zeckendorf in [Go](/languages/go) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/haskell/index.md b/docs/projects/zeckendorf/haskell/index.md deleted file mode 100644 index 5011cc1ccc..0000000000 --- a/docs/projects/zeckendorf/haskell/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Ricardo Mapurunga Junior -date: 2026-05-23 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-05-23 -layout: default -tags: -- haskell -- zeckendorf -title: Zeckendorf in Haskell -title1: Zeckendorf -title2: in Haskell ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Haskell](/languages/haskell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```haskell -module Main where - -import Data.Maybe (listToMaybe) -import Data.Function ((&)) -import Data.List (intercalate) -import Control.Monad (guard) -import Text.Read (readMaybe) -import System.Environment (getArgs) - -listToString :: [Int] -> String -listToString = intercalate ", " . map show - -fib :: [Int] -fib = 1 : 1 : zipWith (+) fib (drop 1 fib) - -zeckendorf :: Int -> [Int] -zeckendorf n = - takeWhile (<= n) fib - & foldr (\m (n, l) -> if m <= n then (n-m, m:l) else (n, l)) (n, []) - & snd - & reverse - -parseArgs :: [String] -> Maybe Int -parseArgs args = do - n <- listToMaybe args - n' <- readMaybe n - guard (n' >= 0) - return n' - -main :: IO () -main = do - args <- getArgs - case parseArgs args of - Nothing -> putStrLn "Usage: please input a non-negative integer" - Just n -> putStrLn $ listToString (zeckendorf n) - - -``` - -{% endraw %} - -Zeckendorf in [Haskell](/languages/haskell) was written by: - -- Ricardo Mapurunga Junior - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/index.md b/docs/projects/zeckendorf/index.md deleted file mode 100644 index f79bafb5bb..0000000000 --- a/docs/projects/zeckendorf/index.md +++ /dev/null @@ -1,193 +0,0 @@ ---- -date: 2026-01-19 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-05-23 -layout: default -tags: -- zeckendorf -title: Zeckendorf -title1: Zeckendorf -title2: '' ---- - - - -Welcome to the Zeckendorf page! Here, you'll find a description of the project as well as a list of sample programs written in various languages. - -This article was written by: - -- rzuckerm - -## Description - -[Edouard Zeckendorf][3] was a Belgian amateur mathematician who proposed a -[Theorem][1] that states that every non-negative integer (_N_) can be -represented as a sum of distinct non-consecutive [Fibonacci Numbers][2]. In -other words, - -* _N_ = _F__c_1 + _F__c_2 + ... + _F__c__n_ - -where: - -* _F__k_ is the _k_ th Fibonacci number -* _c__i_ ≥ 2 -* _c__i_ + 1 > _c__i_ + 1 - -Each Fibonacci number (_F__k_) is the sum of the previous two Fibonacci -numbers: - -* _F_0 = 0 -* _F_1 = 1 -* _F_2 = _F_1 + _F_0 = 0 + 1 = 1 -* _F_3 = _F_2 + _F_1 = 1 + 1 = 2 -* ... -* _F__k_ = _F__k_ - 1 + _F__k_ - 2 - -This relationship is the reason why non-consecutive Fibonacci numbers are used. - -To find the Fibonacci numbers that add up to _N_: - -* Find all the Fibonacci numbers up to and including _N_, starting at - _F_2. -* Going from largest to smallest, select each Fibonacci number such that the - sum of this value plus all the prior selected values is less than or equal to - _N_. - -For example, for _N_ = 67, these are the Fibonacci numbers up to 67: - -* 1, 2, 3, 5, 8, 13, 21, 34, 55 - -Select the appropriate Fibonacci numbers: - -| Trial Sum | Fibonacci Number | Selected | -| :---------: | :--------------: | :------: | -| 0 | 55 | ✅ | -| 55 | 34 | | -| 55 | 21 | | -| 55 | 13 | | -| 55 | 8 | ✅ | -| 63 | 5 | | -| 63 | 3 | ✅ | -| 66 | 2 | | -| 66 | 1 | ✅ | - -Therefore, using the selected numbers, _N_ can be represented as: - -* 67 = 55 + 8 + 3 + 1 - -A possible optimization for this procedure would be to skip Fibonacci -numbers that are consecutive to the last selected value and to terminate -the loop as soon as the sum equals to _N_. - -[1]: https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem -[2]: https://en.wikipedia.org/wiki/Fibonacci_sequence -[3]: https://en.wikipedia.org/wiki/Edouard_Zeckendorf - - -## Requirements - -Create a file called "Zeckendorf" using the naming convention appropriate for -your language of choice. - -Write a sample program that accepts a single non-negative integer from the -command line and outputs a comma-separated list of Fibonacci numbers whose -sum equals the specified value. For zero, output an empty list. If the command -line argument is missing or not a non-negative integer, output the error -message specified in the [Testing](#testing) section. - - -## Testing - -Every project in the [Sample Programs repo](https://github.com/TheRenegadeCoder/sample-programs) should be tested. -In this section, we specify the set of tests specific to Zeckendorf. -In order to keep things simple, we split up the testing as follows: - -- Zeckendorf Valid Tests -- Zeckendorf Invalid Tests - -### Zeckendorf Valid Tests - -| Description | Input | Output | -| ----------- | ----- | ------ | -| Zero | "0" | "" | -| Small Fibonacci Value | "55" | "55" | -| Small Non-Fibonacci Value | "67" | "55, 8, 3, 1" | -| Large Fibonacci Value | "10946" | "10946" | -| Large Non-Fibonacci Value | "16383" | "10946, 4181, 987, 233, 34, 2" | - -### Zeckendorf Invalid Tests - -| Description | Input | -| ----------- | ----- | -| No Input | | -| Empty Input | "" | -| Negative Input | "-2" | -| Floating Point Input | "2.6" | -| Non-Numeric Input | "bad" | - -All of these tests should output the following: - -``` -Usage: please input a non-negative integer -``` - - -## Articles - -There are 28 articles: - -- [Zeckendorf in ALGOL 60](/projects/zeckendorf/algol60) -- [Zeckendorf in ALGOL 68](/projects/zeckendorf/algol68) -- [Zeckendorf in AWK](/projects/zeckendorf/awk) -- [Zeckendorf in Beef](/projects/zeckendorf/beef) -- [Zeckendorf in C](/projects/zeckendorf/c) -- [Zeckendorf in C#](/projects/zeckendorf/c-sharp) -- [Zeckendorf in C++](/projects/zeckendorf/c-plus-plus) -- [Zeckendorf in COBOL](/projects/zeckendorf/cobol) -- [Zeckendorf in Commodore BASIC](/projects/zeckendorf/commodore-basic) -- [Zeckendorf in Euphoria](/projects/zeckendorf/euphoria) -- [Zeckendorf in F#](/projects/zeckendorf/f-sharp) -- [Zeckendorf in Go](/projects/zeckendorf/go) -- [Zeckendorf in Haskell](/projects/zeckendorf/haskell) -- [Zeckendorf in Java](/projects/zeckendorf/java) -- [Zeckendorf in JavaScript](/projects/zeckendorf/javascript) -- [Zeckendorf in Mathematica](/projects/zeckendorf/mathematica) -- [Zeckendorf in PHP](/projects/zeckendorf/php) -- [Zeckendorf in Pascal](/projects/zeckendorf/pascal) -- [Zeckendorf in PowerShell](/projects/zeckendorf/powershell) -- [Zeckendorf in Python](/projects/zeckendorf/python) -- [Zeckendorf in Ruby](/projects/zeckendorf/ruby) -- [Zeckendorf in Rust](/projects/zeckendorf/rust) -- [Zeckendorf in Swift](/projects/zeckendorf/swift) -- [Zeckendorf in TI-BASIC](/projects/zeckendorf/ti-basic) -- [Zeckendorf in Tcl](/projects/zeckendorf/tcl) -- [Zeckendorf in TypeScript](/projects/zeckendorf/typescript) -- [Zeckendorf in Visual Basic](/projects/zeckendorf/visual-basic) -- [Zeckendorf in m4](/projects/zeckendorf/m4) - -*** - - \ No newline at end of file diff --git a/docs/projects/zeckendorf/java/index.md b/docs/projects/zeckendorf/java/index.md deleted file mode 100644 index f209a779ea..0000000000 --- a/docs/projects/zeckendorf/java/index.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-10 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-10 -layout: default -tags: -- java -- zeckendorf -title: Zeckendorf in Java -title1: Zeckendorf -title2: in Java ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Java](/languages/java) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```java -import java.util.*; -import java.util.stream.Collectors; - -public class Zeckendorf { - public static void main(String[] args) { - try { - if (args.length == 0 || args[0].isBlank()) { - throw new Exception(); - } - - long n = Long.parseLong(args[0].trim()); - if (n < 0) throw new Exception(); - - if (n == 0) { - System.out.println(""); - return; - } - - System.out.println(formatResult(getZeckendorf(n))); - - } catch (Exception e) { - System.out.println("Usage: please input a non-negative integer"); - } - } - - private static List getZeckendorf(long target) { - List fibs = new ArrayList<>(); - long a = 1; - long b = 2; - - fibs.add(a); - while (b <= target) { - fibs.add(b); - long next = a + b; - a = b; - b = next; - } - - List selected = new ArrayList<>(); - long remaining = target; - - for (int i = fibs.size() - 1; i >= 0 && remaining > 0; i--) { - long currentFib = fibs.get(i); - - if (currentFib <= remaining) { - selected.add(currentFib); - remaining -= currentFib; - i--; - } - } - - return selected; - } - - private static String formatResult(List result) { - return result.stream().map(String::valueOf).collect(Collectors.joining(", ")); - } -} -``` - -{% endraw %} - -Zeckendorf in [Java](/languages/java) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/javascript/index.md b/docs/projects/zeckendorf/javascript/index.md deleted file mode 100644 index 2d753b8bfc..0000000000 --- a/docs/projects/zeckendorf/javascript/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-24 -layout: default -tags: -- javascript -- zeckendorf -title: Zeckendorf in JavaScript -title1: Zeckendorf in -title2: JavaScript ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [JavaScript](/languages/javascript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```javascript -const arg = process.argv[2]; - -if (process.argv.length !== 3 || !/^\d+$/.test(arg)) { - console.log("Usage: please input a non-negative integer"); - process.exit(0); -} - -let n = parseInt(arg, 10); - -if (n === 0) { - console.log(""); - process.exit(0); -} - -let a = 1; -let b = 2; - -while (b <= n) { - [a, b] = [b, a + b]; -} - -const result = []; - -while (n > 0 && a > 0) { - if (a <= n) { - result.push(a); - n -= a; - - const prev = b - a; - [a, b] = [a - prev, prev]; - } else { - let prevA = b - a; - [a, b] = [b - a, a]; - } -} - -console.log(result.join(", ")); -``` - -{% endraw %} - -Zeckendorf in [JavaScript](/languages/javascript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/m4/index.md b/docs/projects/zeckendorf/m4/index.md deleted file mode 100644 index d1250e6a42..0000000000 --- a/docs/projects/zeckendorf/m4/index.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-07 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-03-07 -layout: default -tags: -- m4 -- zeckendorf -title: Zeckendorf in m4 -title1: Zeckendorf -title2: in m4 ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [m4](/languages/m4) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```m4 -divert(-1) -define(`show_usage', -`Usage: please input a non-negative integer -m4exit(`1')') - -dnl is_valid(n) -define(`is_valid', `eval(regexp(`$1', `^\s*-?[0-9]+\s*$') >= 0)') - -dnl Reference: https://www.gnu.org/software/m4/manual/m4.html#index-array -dnl array_get(var_name, idx) -define(`array_get', `defn(format(``%s[%s]'', `$1', `$2'))') - -dnl array_set(var_name, idx, value) -define(`array_set', `define(format(``%s[%s]'', `$1', `$2'), `$3')') - -dnl show_int_list(varname): -dnl for i = 0 to varname["length"] - 1: -dnl if i > 0: -dnl Output ", " -dnl Output varname[i] -define(`show_int_list', `_show_int_list(`$1', 0)') -define(`_show_int_list', -`ifelse(eval(`$2' < array_get(`$1', `length')), 1, -`ifelse(eval(`$2' > 0), 1, `, ')dnl -array_get(`$1', `$2')`'dnl -_show_int_list(`$1', incr($2))'`'dnl -)'dnl -) - -dnl fibonacci(value, result_varname): -dnl a = 1 -dnl b = 2 -dnl result_varname["length"] = 0 -dnl while a <= value: -dnl result_varname[result_varname["length"]] = a -dnl result_varname["length"] = result_varname["length"] + 1 -dnl a, b = b, a + b -define(`fibonacci', -`array_set(`$2', `length', 0)dnl -_fibonacci(`$1', `$2', 1, 2)'dnl -) - -dnl value=$1, result_varname=$2, a=$3, b=$4 -define(`_fibonacci', -`ifelse(eval(`$3' <= `$1'), 1, -`array_set(`$2', array_get(`$2', `length'), `$3')dnl -array_set(`$2', `length', eval(incr(array_get(`$2', `length'))))dnl -_fibonacci(`$1', `$2', `$4', eval(`$3 + $4'))'dnl -)'dnl -) - -dnl zeckendorf(value, fibs_varname, zecks_varname) -dnl fibonacci(value, fibs_varname) -dnl zecks_varname["length"] = 0 -dnl n = fibs_varname["length"] - 1 -dnl while n >= 0 and value > 0: -dnl if fibs_varname[n] >= value: -dnl zecks_varname[zecks_varname["length"]] = fibs_varname[n] -dnl zecks_varname["length"] = zecks_varname["length"] + 1 -dnl value = value - fibs_varname[n] -dnl n = n - 2 -dnl else: -dnl n = n - 1 -define(`zeckendorf', -`fibonacci(`$1', `$2')dnl -array_set(`$3', `length', 0)dnl -_zeckendorf(`$1', `$2', `$3', decr(array_get(`$2', `length')))dnl -'dnl -) - -dnl value=$1, fibs_varname=$2, zecks_varname=$3, n=$4 -define(`_zeckendorf', -`ifelse(eval(`$4' >= 0 && `$1' > 0), 1, -`ifelse(eval(array_get(`$2', `$4') <= `$1'), 1, -`array_set(`$3', array_get(`$3', `length'), array_get(`$2', `$4'))dnl -array_set(`$3', `length', incr(array_get(`$3', `length')))dnl -_zeckendorf(eval(`$1' - array_get(`$2', `$4')), `$2', `$3', eval(`$4' - 2))dnl -',dnl -`_zeckendorf(`$1', `$2', `$3', decr(`$4'))'dnl -)'dnl -)'dnl -) - -divert(0)dnl -ifelse(eval(ARGC < 1 || len(ARGV1) < 1 || !is_valid(ARGV1)), 1, `show_usage()')dnl -ifelse(eval(ARGV1 < 0), 1, `show_usage()')dnl -zeckendorf(ARGV1, `fibs', `zecks')dnl -show_int_list(`zecks') - -``` - -{% endraw %} - -Zeckendorf in [m4](/languages/m4) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/mathematica/index.md b/docs/projects/zeckendorf/mathematica/index.md deleted file mode 100644 index 79ddf4dd1d..0000000000 --- a/docs/projects/zeckendorf/mathematica/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-30 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-30 -layout: default -tags: -- mathematica -- zeckendorf -title: Zeckendorf in Mathematica -title1: Zeckendorf in -title2: Mathematica ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Mathematica](/languages/mathematica) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```mathematica -ClearAll[zeckendorfMain, nf, zeckendorf]; - -nf[n_] := Fibonacci @ Floor @ Log[GoldenRatio, n * Sqrt[5] + 1/2]; -zeckendorf[n_Integer?Positive] := -Differences[NestWhileList[# - nf[#] &, n, # != 0 &]]; - -$usage = "Usage: please input a non-negative integer"; - -zeckendorfMain[s_String /; StringMatchQ[s, DigitCharacter ..]] := - With[{n = FromDigits[s]}, - Which[ - n == 0, "", - n > 0, StringRiffle[ToString /@ zeckendorf[n], ", "] - ] - ]; - -zeckendorfMain[___] := $usage; - -Print /@ zeckendorfMain /@ { - (* Valid cases *) - "0", - "55", - "67", - "10946", - "16383", - - (* Invalid cases*) - "", - "-2", - "2.6", - "bad" -}; - -Print[zeckendorfMain[]] -``` - -{% endraw %} - -Zeckendorf in [Mathematica](/languages/mathematica) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/pascal/index.md b/docs/projects/zeckendorf/pascal/index.md deleted file mode 100644 index e563276475..0000000000 --- a/docs/projects/zeckendorf/pascal/index.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-11 -layout: default -tags: -- pascal -- zeckendorf -title: Zeckendorf in Pascal -title1: Zeckendorf -title2: in Pascal ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Pascal](/languages/pascal) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```pascal -program Zeckendorf; - -{$mode objfpc}{$H+}{$J-}{$modeswitch advancedrecords} - -uses - SysUtils; - -const - MAX_FIB_COUNT = {$IFDEF CPU64}92{$ELSE}46{$ENDIF}; - -type - TNatural = {$IFDEF CPU64}UInt64{$ELSE}UInt32{$ENDIF}; - - TZeckendorf = record - private - FFibonacciTable: array[0..MAX_FIB_COUNT - 1] of TNatural; - FActualCount: Integer; - FInitialized: Boolean; - procedure Initialize; - public - procedure DecomposeAndPrint(ANumber: TNatural); - end; - -procedure TZeckendorf.Initialize; -var - A, B, Next: TNatural; -begin - if FInitialized then Exit; - - FFibonacciTable[0] := 1; - FFibonacciTable[1] := 2; - FActualCount := 2; - A := 1; - B := 2; - - while (High(TNatural) - A >= B) and (FActualCount < MAX_FIB_COUNT) do - begin - Next := A + B; - FFibonacciTable[FActualCount] := Next; - Inc(FActualCount); - A := B; - B := Next; - end; - FInitialized := True; -end; - -procedure TZeckendorf.DecomposeAndPrint(ANumber: TNatural); -var - I: Integer; - IsFirstTerm: Boolean; -begin - Initialize; - - if ANumber = 0 then Exit; - - IsFirstTerm := True; - for I := FActualCount - 1 downto 0 do - begin - if FFibonacciTable[I] <= ANumber then - begin - if not IsFirstTerm then Write(', ') else IsFirstTerm := False; - Write(FFibonacciTable[I]); - Dec(ANumber, FFibonacciTable[I]); - end; - if ANumber = 0 then Break; - end; - WriteLn; -end; - -procedure ShowUsage; -begin - WriteLn('Usage: please input a non-negative integer'); - Halt(1); -end; - -var - InputVal: TNatural; - Code: Integer; - Z: TZeckendorf; -begin - if (ParamCount <> 1) then ShowUsage; - - Val(ParamStr(1), InputVal, Code); - if (Code <> 0) or (Pos('-', ParamStr(1)) > 0) then ShowUsage; - - if InputVal = 0 then - WriteLn - else - Z.DecomposeAndPrint(InputVal); -end. -``` - -{% endraw %} - -Zeckendorf in [Pascal](/languages/pascal) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/php/index.md b/docs/projects/zeckendorf/php/index.md deleted file mode 100644 index d2b27d42a2..0000000000 --- a/docs/projects/zeckendorf/php/index.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-07 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-03-07 -layout: default -tags: -- php -- zeckendorf -title: Zeckendorf in PHP -title1: Zeckendorf -title2: in PHP ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [PHP](/languages/php) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```php - array( - 'decimal' => TRUE, - 'min_range' => PHP_INT_MIN, - 'max_range' => PHP_INT_MAX - ) - ) - ) === FALSE - ) - { - return FALSE; - } - - return intval($str_value); -} - -function get_fibonacci_values($value) { - // fib(2) = 1 - // fib(3) = 2 - $a = 1; - $b = 2; - $fibs = array(); - - // Get Fibonacci values up to and including specified value - while ($a <= $value) { - // fib(n) = fib(n - 1) + fib(n - 2) - array_push($fibs, $a); - [$a, $b] = [$b, $a + $b]; - } - - return $fibs; -} - -function get_zeckendorf_values($value) { - $zecks = array(); - - // Go through Fibonacci numbers in reverse order, stopping when - // remaining value is zero - $fibs = get_fibonacci_values($value); - for ($n = count($fibs) - 1; $n >=0 && $value > 0;) { - // If candidate Fibonacci number is greater than or equal to remaining value - $f = $fibs[$n]; - if ($value >= $f) { - // Append Fibonacci number to results - $zecks[] = $f; - - // Reduce remaining value - $value -= $f; - - // Skip previous value - $n -= 2; - } else { - // Else, go to previous value - $n--; - } - } - - return $zecks; -} - -// Exit if too few arguments -if (count($argv) < 2) -{ - usage(); -} - -// Parse 1st argument. Exit if invalid and negative -$value = parse_int($argv[1]); -if ($value === FALSE || $value < 0) { - usage(); -} - -// Get and show Zeckendorf values -$values = get_zeckendorf_values($value); -printf("%s\n", implode(', ', $values)); - -``` - -{% endraw %} - -Zeckendorf in [PHP](/languages/php) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/powershell/index.md b/docs/projects/zeckendorf/powershell/index.md deleted file mode 100644 index 39b3118771..0000000000 --- a/docs/projects/zeckendorf/powershell/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-07 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-03-07 -layout: default -tags: -- powershell -- zeckendorf -title: Zeckendorf in PowerShell -title1: Zeckendorf in -title2: PowerShell ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [PowerShell](/languages/powershell) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```powershell -function Show-Usage() { - Write-Host "Usage: please input a non-negative integer" - Exit 1 -} - -function Get-Fibonacci-Values([int]$Value) { - $a = 1 - $b = 2 - while ($a -le $Value) { - $a - $a, $b = $b, ($a + $b) - } -} - -function Get-Zeckendorf-Values([int]$Value) { - $fibs = Get-Fibonacci-Values($Value) - $n = $fibs.Length - 1 - while ($n -ge 0 -and $Value -gt 0) { - $f = $fibs[$n] - if ($Value -ge $f) { - $f - $Value -= $f - $n -= 2 - } else { - $n-- - } - } -} - -if ($args.Length -lt 1) { - Show-Usage -} - -try { - $value = [int]::Parse($args[0]) -} catch { - Show-Usage -} - -if ($value -lt 0) { - Show-Usage -} - -$values = Get-Zeckendorf-Values($value) -Write-Host ($values -join ', ') - -``` - -{% endraw %} - -Zeckendorf in [PowerShell](/languages/powershell) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/python/index.md b/docs/projects/zeckendorf/python/index.md deleted file mode 100644 index 73be41b8a0..0000000000 --- a/docs/projects/zeckendorf/python/index.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-01-19 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-01-19 -layout: default -tags: -- python -- zeckendorf -title: Zeckendorf in Python -title1: Zeckendorf -title2: in Python ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Python](/languages/python) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```python -import sys -from typing import NoReturn - - -def usage() -> NoReturn: - print("Usage: please input a non-negative integer") - sys.exit(1) - - -def fibonacci_up_to(n: int) -> list[int]: - result: list[int] = [] - a = 1 - b = 2 - while a <= n: - result.append(a) - a, b = b, a + b - - return result - - -def zeckendorf(n: int) -> list[int]: - result: list[int] = [] - fibs = fibonacci_up_to(n) - idx = len(fibs) - 1 - while idx >= 0 and n > 0: - fib = fibs[idx] - if fib <= n: - n -= fib - result.append(fib) - idx -= 2 - else: - idx -= 1 - - return result - - -def main() -> int: - if len(sys.argv) < 2: - usage() - - try: - n = int(sys.argv[1]) - except ValueError: - usage() - - if n < 0: - usage() - - result = zeckendorf(n) - print(result) - - -if __name__ == "__main__": - main() - -``` - -{% endraw %} - -Zeckendorf in [Python](/languages/python) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/ruby/index.md b/docs/projects/zeckendorf/ruby/index.md deleted file mode 100644 index 4293e30923..0000000000 --- a/docs/projects/zeckendorf/ruby/index.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-14 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-05-14 -layout: default -tags: -- ruby -- zeckendorf -title: Zeckendorf in Ruby -title1: Zeckendorf -title2: in Ruby ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Ruby](/languages/ruby) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ruby -# frozen_string_literal: true - -USAGE = "Usage: please input a non-negative integer" - -def usage! - warn USAGE - exit 1 -end - -def parse_input(str) - usage! if str.nil? || str.strip.empty? - - n = Integer(str) - usage! if n < 0 - - n -rescue ArgumentError, NoMethodError - usage! -end - -def fibs_upto(n) - fibs = [1, 2] - fibs << fibs[-1] + fibs[-2] while fibs[-1] <= n - fibs.pop if fibs[-1] > n - fibs -end - -def zeckendorf(n) - return [] if n == 0 - - fibs = fibs_upto(n) - result = [] - - i = fibs.length - 1 - - while n > 0 - if fibs[i] <= n - result << fibs[i] - n -= fibs[i] - i -= 2 - else - i -= 1 - end - end - - result -end - -input = ARGV.first -n = parse_input(input) - -puts zeckendorf(n).join(", ") - -``` - -{% endraw %} - -Zeckendorf in [Ruby](/languages/ruby) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/rust/index.md b/docs/projects/zeckendorf/rust/index.md deleted file mode 100644 index 46db6e8a63..0000000000 --- a/docs/projects/zeckendorf/rust/index.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-07 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-03-07 -layout: default -tags: -- rust -- zeckendorf -title: Zeckendorf in Rust -title1: Zeckendorf -title2: in Rust ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Rust](/languages/rust) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```rust -use std::cmp::PartialOrd; -use std::env::args; -use std::ops::{Add, SubAssign}; -use std::process::exit; -use std::str::FromStr; - -fn usage() -> ! { - println!("Usage: please input a non-negative integer"); - exit(0); -} - -fn parse_int(s: &str) -> Result::Err> { - s.trim().parse::() -} - -fn get_fibonacci_values(value: T) -> Vec -where - T: Add + PartialOrd + From + Copy -{ - let mut fibs = vec![]; - let mut a: T = T::from(1); - let mut b: T = T::from(2); - while a <= value { - fibs.push(a); - (a, b) = (b, a + b); - } - - fibs -} - -fn get_zeckendorf_values(value: T) -> Vec -where - T: Add + SubAssign + PartialOrd + From + Copy -{ - let fibs = get_fibonacci_values(value); - let mut zecks = vec![]; - let mut n = (fibs.len() as i32) - 1; - let mut remaining = value; - while n >= 0 && remaining > T::from(0) { - let f = fibs[n as usize]; - if remaining >= f { - zecks.push(f); - remaining -= f; - n -= 2; - } else { - n -= 1; - } - } - - zecks -} - -fn main() { - let mut args = args().skip(1); - - // Exit if 1st command-line argument not an integer - let input_num: i32 = args - .next() - .and_then(|s| parse_int(&s).ok()) - .unwrap_or_else(|| usage()); - - // Exit if value is negative - if input_num < 0 { - usage(); - } - - let zecks = get_zeckendorf_values::(input_num); - println!("{:?}", zecks); -} - -``` - -{% endraw %} - -Zeckendorf in [Rust](/languages/rust) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/swift/index.md b/docs/projects/zeckendorf/swift/index.md deleted file mode 100644 index 34c481088e..0000000000 --- a/docs/projects/zeckendorf/swift/index.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-24 -layout: default -tags: -- swift -- zeckendorf -title: Zeckendorf in Swift -title1: Zeckendorf -title2: in Swift ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Swift](/languages/swift) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```swift -import Foundation - -func fibs(upTo limit: Int) -> [Int] { - guard limit >= 1 else { return [] } - - var result = [1, 2] - while true { - let next = result[result.count - 1] + result[result.count - 2] - if next > limit { break } - result.append(next) - } - return result -} - -func zeckendorf(_ n: Int) -> String { - guard n > 0 else { return "" } - - let fibsList = fibs(upTo: n).reversed() - - let result = fibsList.reduce(into: (remaining: n, out: [Int]())) { acc, f in - if f <= acc.remaining { - acc.out.append(f) - acc.remaining -= f - } - }.out - - return result.map(String.init).joined(separator: ", ") -} - -guard CommandLine.argc == 2, - let n = Int(CommandLine.arguments[1]), - n >= 0 else { - print("Usage: please input a non-negative integer") - exit(0) -} - -print(zeckendorf(n)) -``` - -{% endraw %} - -Zeckendorf in [Swift](/languages/swift) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/tcl/index.md b/docs/projects/zeckendorf/tcl/index.md deleted file mode 100644 index b23d549d28..0000000000 --- a/docs/projects/zeckendorf/tcl/index.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-11 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-11 -layout: default -tags: -- tcl -- zeckendorf -title: Zeckendorf in Tcl -title1: Zeckendorf -title2: in Tcl ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Tcl](/languages/tcl) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```tcl -proc usage {} { - puts "Usage: please input a non-negative integer" - exit 1 -} - -proc zeckendorf {n} { - set result {} - set a 1 - set b 2 - - while {$b <= $n} { - lassign [list $b [expr {$a + $b}]] a b - } - - while {$n > 0} { - if {$a <= $n} { - set n [expr {$n - $a}] - lappend result $a - } - lassign [list [expr {$b - $a}] $a] a b - } - - return $result -} - -if {$argc != 1} { usage } -lassign $argv arg - -if {![string is integer -strict $arg] || $arg < 0} { - usage -} - -puts [join [zeckendorf $arg] ", "] -``` - -{% endraw %} - -Zeckendorf in [Tcl](/languages/tcl) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/ti-basic/index.md b/docs/projects/zeckendorf/ti-basic/index.md deleted file mode 100644 index 243f52abd6..0000000000 --- a/docs/projects/zeckendorf/ti-basic/index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -authors: -- rzuckerm -date: 2026-03-07 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-03-07 -layout: default -tags: -- ti-basic -- zeckendorf -title: Zeckendorf in TI-BASIC -title1: Zeckendorf -title2: in TI-BASIC ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [TI-BASIC](/languages/ti-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```ti-basic -Input "",Str1 -"0123456789"->Str2 -length(Str1)->L -L<1->E -0->D -0->V -1->N -1->S -While E=0 and N<=L - sub(Str1,N,1)->C - inString(Str2,C)-1->K - If C="+" or C="-" - Then - D>0->E - If C="-" - Then 0-S->S - End - Else - K<0->E - D+1->D - V*10+K*S->V - End - N+1->N -End -If E or D<1 or V<0->E Then Disp "Usage: please input a non-negative integer" -Else - 1->A - 2->B - While A<=V - B+A->B - B-A->A - End - {}->l1 - 0->N - While V>0 - B-A->A - B-A->B - If V>=A Then - N+1->N - A->l1(N) - V-A->V - End - End -End -If l1 Then - Disp l1 -End - -``` - -{% endraw %} - -Zeckendorf in [TI-BASIC](/languages/ti-basic) was written by: - -- rzuckerm - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/typescript/index.md b/docs/projects/zeckendorf/typescript/index.md deleted file mode 100644 index f24dd724f9..0000000000 --- a/docs/projects/zeckendorf/typescript/index.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-04-24 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-04-24 -layout: default -tags: -- typescript -- zeckendorf -title: Zeckendorf in TypeScript -title1: Zeckendorf in -title2: TypeScript ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [TypeScript](/languages/typescript) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```typescript -const arg = process.argv[2]; - -if (process.argv.length !== 3 || !/^\d+$/.test(arg)) { - console.log("Usage: please input a non-negative integer"); - process.exit(0); -} - -let n = parseInt(arg, 10); - -if (n === 0) { - console.log(""); - process.exit(0); -} - -let a = 1; -let b = 2; - -while (b <= n) { - [a, b] = [b, a + b]; -} - -const result: number[] = []; - -while (n > 0 && a > 0) { - if (a <= n) { - result.push(a); - n -= a; - - let prevA = b - a; - let prevPrevA = a - prevA; - [a, b] = [prevPrevA, prevA]; - } else { - let prevA = b - a; - [a, b] = [prevA, a]; - } -} - -console.log(result.join(", ")); -``` - -{% endraw %} - -Zeckendorf in [TypeScript](/languages/typescript) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file diff --git a/docs/projects/zeckendorf/visual-basic/index.md b/docs/projects/zeckendorf/visual-basic/index.md deleted file mode 100644 index dbf9eb277c..0000000000 --- a/docs/projects/zeckendorf/visual-basic/index.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -authors: -- Ștefan-Iulian Alecu -date: 2026-05-07 -featured-image: zeckendorf-in-every-language.png -last-modified: 2026-05-07 -layout: default -tags: -- visual-basic -- zeckendorf -title: Zeckendorf in Visual Basic -title1: Zeckendorf in -title2: Visual Basic ---- - - - -Welcome to the [Zeckendorf](/projects/zeckendorf) in [Visual Basic](/languages/visual-basic) page! Here, you'll find the source code for this program as well as a description of how the program works. - -## Current Solution - -{% raw %} - -```visual_basic -Public Module Zeckendorf - - Private ReadOnly Fibs As Long() = GenerateFibs() - - - Private Function GenerateFibs() As Long() - - Dim fs As New List(Of Long) From {1L, 2L} - - While Long.MaxValue - fs(fs.Count - 1) >= fs(fs.Count - 2) - fs.Add(fs(fs.Count - 1) + fs(fs.Count - 2)) - End While - - Return fs.ToArray() - - End Function - - - Public Sub Main(args As String()) - - Dim n As Long - - If args.Length = 0 OrElse Not Long.TryParse(args(0), n) OrElse n < 0 Then - - Console.WriteLine("Usage: please input a non-negative integer") - Return - - End If - - If n = 0 Then Return - - Dim terms As New List(Of Long) - - Dim count As Integer = Decompose(n, terms) - - Console.WriteLine(String.Join(", ", terms.GetRange(0, count))) - - End Sub - - - Private Function Decompose(n As Long, terms As List(Of Long)) As Integer - - Dim count As Integer = 0 - - Dim i As Integer = Array.BinarySearch(Fibs, n) - - If i < 0 Then - i = Not i - 1 - End If - - For idx As Integer = i To 0 Step -1 - - If n <= 0 Then Exit For - - If Fibs(idx) <= n Then - terms.Add(Fibs(idx)) - n -= Fibs(idx) - count += 1 - End If - - Next - - Return count - - End Function - -End Module -``` - -{% endraw %} - -Zeckendorf in [Visual Basic](/languages/visual-basic) was written by: - -- Ștefan-Iulian Alecu - -If you see anything you'd like to change or update, [please consider contributing](https://github.com/TheRenegadeCoder/sample-programs). - -## How to Implement the Solution - -No 'How to Implement the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). - -## How to Run the Solution - -No 'How to Run the Solution' section available. [Please consider contributing](https://github.com/TheRenegadeCoder/sample-programs-website). \ No newline at end of file