├── .gitattributes ├── .github └── ISSUE_TEMPLATE │ └── add-example-from-wiki.md ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── examples.properties ├── examples ├── Java │ ├── AckermannFunction │ │ └── AckermannFunction.pde │ ├── Anagrams │ │ ├── Anagrams.pde │ │ └── unixdict.txt │ ├── Animation │ │ └── Animation.pde │ ├── ArchimedeanSpiral_Lines │ │ └── ArchimedeanSpiral_Lines.pde │ ├── ArchimedeanSpiral_LinesRotated │ │ └── ArchimedeanSpiral_LinesRotated.pde │ ├── ArchimedeanSpiral_Points │ │ └── ArchimedeanSpiral_Points.pde │ ├── ArchimedeanSpiral_PointsRotatedMatrix │ │ └── ArchimedeanSpiral_PointsRotatedMatrix.pde │ ├── ArchimedeanSpiral_PointsRotatedPVector │ │ └── ArchimedeanSpiral_PointsRotatedPVector.pde │ ├── BarnsleyFern │ │ └── BarnsleyFern.pde │ ├── BezierCurvesCubic │ │ └── BezierCurvesCubic.pde │ ├── BezierCurvesCubicInteractive │ │ └── BezierCurvesCubicInteractive.pde │ ├── BinaryDigits │ │ └── BinaryDigits.pde │ ├── Bitmap │ │ └── Bitmap.pde │ ├── BrownianTree │ │ └── BrownianTree.pde │ ├── BullsAndCows │ │ └── BullsAndCows.pde │ ├── ColorOfAScreenPixel │ │ └── ColorOfAScreenPixel.pde │ ├── ColorWheel │ │ └── ColorWheel.pde │ ├── Comments │ │ └── Comments.pde │ ├── DragonCurve │ │ └── DragonCurve.pde │ ├── DrawAClock │ │ └── DrawAClock.pde │ ├── DrawACuboid │ │ └── DrawACuboid.pde │ ├── DrawAPixel │ │ └── DrawAPixel.pde │ ├── DrawARotatingCube │ │ └── DrawARotatingCube.pde │ ├── DrawASphere │ │ └── DrawASphere.pde │ ├── EmptyProgram │ │ └── EmptyProgram.pde │ ├── EvenOrOdd │ │ └── EvenOrOdd.pde │ ├── Factorial │ │ └── Factorial.pde │ ├── FizzBuzz │ │ └── FizzBuzz.pde │ ├── FizzBuzz_Futureproof │ │ └── FizzBuzz_Futureproof.pde │ ├── FizzBuzz_Viz │ │ └── FizzBuzz_Viz.pde │ ├── FizzBuzz_VizTernary │ │ └── FizzBuzz_VizTernary.pde │ ├── FractalTree_Calculation │ │ └── FractalTree_Calculation.pde │ ├── FractalTree_Rotation │ │ └── FractalTree_Rotation.pde │ ├── GameOfLife │ │ └── GameOfLife.pde │ ├── HelloWorld │ │ └── HelloWorld.pde │ ├── HilbertCurve │ │ └── HilbertCurve.pde │ ├── ImageNoise │ │ └── ImageNoise.pde │ ├── JosephusProblem │ │ └── JosephusProblem.pde │ ├── JuliaSet │ │ └── JuliaSet.pde │ ├── KochCurve │ │ └── KochCurve.pde │ ├── LevenshteinDistance │ │ └── LevenshteinDistance.pde │ ├── MandelbrotSet │ │ └── MandelbrotSet.pde │ ├── MousePosition │ │ └── MousePosition.pde │ ├── NinetyNineBottles │ │ └── NinetyNineBottles.pde │ ├── NinetyNineBottles_Viz │ │ └── NinetyNineBottles_Viz.pde │ ├── OneHundredDoors │ │ └── OneHundredDoors.pde │ ├── PalindromeDetection │ │ └── PalindromeDetection.pde │ ├── PythagorasTree │ │ └── PythagorasTree.pde │ ├── RenameAFile │ │ ├── RenameAFile.pde │ │ ├── docs │ │ │ └── .gitkeep │ │ └── input.txt │ ├── RepeatAString │ │ └── RepeatAString.pde │ ├── SieveOfEratosthenes │ │ └── SieveOfEratosthenes.pde │ ├── SieveOfEratosthenes_Viz │ │ └── SieveOfEratosthenes_Viz.pde │ └── Vector │ │ └── Vector.pde ├── Python │ ├── AckermanFunction │ │ └── AckermanFunction.pyde │ ├── Animation │ │ └── Animation.pyde │ ├── ArchimedeanSpiral_Points │ │ └── ArchimedeanSpiral_Points.pyde │ ├── BarnsleyFern │ │ └── BarnsleyFern.pyde │ ├── BezierCurvesCubicInteractive │ │ └── BezierCurvesCubicInteractive.pyde │ ├── BinaryDigits │ │ └── BinaryDigits.pyde │ ├── Bitmap │ │ └── Bitmap.pyde │ ├── BrownianTree │ │ └── BrownianTree.pyde │ ├── ColorWheel │ │ └── ColorWheel.pyde │ ├── Comments │ │ └── Comments.pyde │ ├── DragonCurve │ │ └── DragonCurve.pyde │ ├── DrawAClock │ │ └── DrawAClock.pyde │ ├── DrawARotatingCube │ │ └── DrawARotatingCube.pyde │ ├── Factorial │ │ └── Factorial.pyde │ ├── FractalTree_Calculation │ │ └── FractalTree_Calculation.pyde │ ├── FractalTree_Rotation │ │ └── FractalTree_Rotation.pyde │ ├── GameOfLife │ │ └── GameOfLife.pyde │ ├── HilbertCurve │ │ └── HilbertCurve.pyde │ ├── ImageNoise │ │ └── ImageNoise.pyde │ ├── JosephusProblem │ │ └── JosephusProblem.pyde │ ├── JuliaSet │ │ └── JuliaSet.pyde │ ├── KochCurve │ │ └── KochCurve.pyde │ ├── LevenshteinDistance │ │ └── LevenshteinDistance.pyde │ ├── MandelbrotSet │ │ └── MandelbrotSet.pyde │ ├── MousePosition │ │ └── MousePosition.pyde │ ├── NinetyNineBottles_Viz │ │ └── NinetyNineBottles_Viz.pyde │ ├── PalindromeDetection │ │ └── PalindromeDetection.pyde │ ├── PythagorasTree │ │ └── PythagorasTree.pyde │ ├── RenameAFile │ │ ├── RenameAFile.pyde │ │ ├── docs │ │ │ └── .gitkeep │ │ └── input.txt │ ├── RepeatAString │ │ └── RepeatAString.pyde │ ├── SieveOfEratosthenes_Viz │ │ └── SieveOfEratosthenes_Viz.pyde │ └── Vector │ │ └── Vector.pyde └── R │ ├── AckermannFunction │ └── AckermannFunction.rpde │ ├── NinetyNineBottles │ └── NinetyNineBottles.rpde │ └── OneHundredDoors │ └── OneHundredDoors.rpde ├── logo ├── assets │ ├── processing-logo_black.png │ ├── rosetta-stone-detail.png │ └── rosettacodeorg--title.png ├── rosetta_examples_p5-logo-300x300.png ├── rosetta_examples_p5-logo-600x600.png ├── rosetta_examples_p5-logo.xcf ├── rosetta_examples_p5-social-media-preview-360x180.png ├── rosetta_examples_p5-social-media-preview.png └── rosetta_examples_p5-social-media-preview.xcf └── release.sh /.gitattributes: -------------------------------------------------------------------------------- 1 | examples/* -linguist-documentation 2 | 3 | ## pyde recognized as Python, could also be configured: 4 | # 5 | # *.pyde linguist-detectable=true 6 | # *.pyde linguist-language=Processing 7 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/add-example-from-wiki.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Add Example from Wiki 3 | about: 'Based on an existing Rosetta Code code snippet, add an example sketch to the 4 | set ' 5 | title: "[ADD EXAMPLE] Name of Task Here" 6 | labels: add_example 7 | assignees: '' 8 | 9 | --- 10 | 11 | **Instructions:** 12 | Find Processing task code on the wiki with no sketch in this repo: 13 | https://rosettacode.org/wiki/Category:Processing 14 | https://rosettacode.org/wiki/Category:Processing_Python_mode 15 | 16 | If you are interested in first contributing new Processing task code to the wiki, check: 17 | https://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_Processing 18 | https://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_Processing_Python_mode 19 | 20 | ### URL of task 21 | e.g. http://rosettacode.org/wiki/100_doors#Processing 22 | or http://rosettacode.org/wiki/100_doors#Processing_Python_mode 23 | 24 | ### Next steps 25 | - [ ] I requesting that somebody else write the .pde / .pyde sketch 26 | - [ ] I will write the .pde / .pyde sketch and submit as an issue comment 27 | - [ ] I will write the .pde / .pyde sketch and submit as a pull request 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | applet 3 | application.linux-arm64 4 | application.linux-armv6hf 5 | application.linux32 6 | application.linux64 7 | application.windows32 8 | application.windows64 9 | application.macosx 10 | 11 | # ignore working area for drafts 12 | examples_draft 13 | 14 | # ignore release assets 15 | release/* 16 | 17 | # ommit Python mode optional metadata files 18 | sketch.properties 19 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Processing examples to the RosettaCode set 2 | 3 | The project welcomes new submissions -- whether you found a task entry already on the Rosetta Code wiki to add, or whether you created the new entry yourself and now want it add. 4 | 5 | > NOTE: This is an example set for Processing (PDE) based on Processing tasks drawn from the Rosetta Code wiki. All submissions to Rosetta Code and to this example set are licensed as open documentation ("copyleft") under the current [LICENSE.md](LICENSE.md). If you are the author of the code and submit to Rosetta Code and/or here, you may of course also make your code available under whatever additional licenses you choose (e.g. the Unlicense, commercial licenses, et cetera). 6 | 7 | For community discussions of contributing, see: 8 | 9 | - https://discourse.processing.org/t/processing-on-rosetta-code-weekly-topics/5980 10 | 11 | Several options for contributing are listed below. 12 | 13 | 14 | ### Find existing tasks 15 | 16 | To identify an existing Processing task already on the Rosetta Code wiki that is not yet part of this example set: 17 | 18 | 1. on the Rosetta Code wiki, browse tasks for: 19 | - [Processing tasks](https://rosettacode.org/wiki/Category:Processing), or 20 | - [Python mode tasks](https://rosettacode.org/wiki/Category:Processing_Python_mode), or 21 | - [Processing.R tasks](https://rosettacode.org/wiki/Category:Processing.R) 22 | If you find a task that is not listed in this repos `examples` folder: 23 | 2. [create a new issue](https://github.com/jeremydouglass/rosetta_examples_p5/issues) named for that task 24 | 25 | 26 | ### Contribute a new task to the Rosetta Code wiki 27 | 28 | 1. on the Rosetta Code wiki, browse unimplemented tasks: 29 | - [Tasks not implemented in Processing](https://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_Processing), or 30 | - [Tasks not implemented in Python mode](https://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_Processing_Python_mode), or 31 | - [Tasks not implemented in Processing.R](https://rosettacode.org/mw/index.php?title=Reports:Tasks_not_implemented_in_Processing.R&action=edit&redlink=1) 32 | 2. select a task to add 33 | 3. edit that page (full page edit) 34 | 4. add a Processing section -- alphabetically using header markup 35 | 5. add a code block with your example sketch code, wrapping the code block in `` tags. The first line of code begins *immediately* after the opening `` with no linebreak. 36 | 37 | The result may look like this: 38 | 39 | ``` 40 | =={{header|Processing}}== 41 | void draw(){ 42 | background(0); 43 | ellipse(width/2, height/2, mouseX, mouseX); 44 | println(frameCount); 45 | } 46 | 47 | ``` 48 | 49 | or this: 50 | 51 | ``` 52 | ==={{header|Processing Python mode}}=== 53 | def draw(): 54 | background(0) 55 | ellipse(width/2, height/2, mouseX, mouseX) 56 | println(frameCount) 57 | 58 | ``` 59 | 60 | or this: 61 | 62 | ``` 63 | ==={{header|Processing.R}}=== 64 | draw <- function() { 65 | background(0) 66 | ellipse(width/2, height/2, mouseX, mouseX) 67 | stdout$println(frameCount) 68 | } 69 | 70 | ``` 71 | 72 | Optionally, a single entry may contain plain text descriptions and multiple code blocks, if needed--for example, if providing two separate solutions to the same problem (simple and complex, or demonstrating two different approaches). Code may also be accompanied by example output, headed by {{out}} and wrapped in `
` tags.
 73 | 
 74 | ```
 75 | {{out}}
 76 | 
1
 77 | 2
 78 | 3
 79 | 
80 | ``` 81 | 82 | Some examples seeking contributors include: 83 | 84 | Some of missing examples with tasks on Rosetta Code are right up Processing’s 85 | alley – for example, animation: 86 | 87 | - https://rosettacode.org/wiki/Animate_a_pendulum 88 | - https://rosettacode.org/wiki/Galton_box_animation 89 | - https://rosettacode.org/wiki/Spinning_rod_animation/Text 90 | 91 | ... Conway’s game of life and the Sierpinski triangle: 92 | 93 | - https://rosettacode.org/wiki/Conway's_Game_of_Life 94 | - https://rosettacode.org/wiki/Sierpinski_triangle/Graphical 1 95 | 96 | ... and games of varying complexity: 97 | 98 | - https://rosettacode.org/wiki/Go_Fish 99 | - https://rosettacode.org/wiki/15_Puzzle_Game 100 | - https://rosettacode.org/wiki/2048 101 | 102 | 103 | ### Turn tasks into sketches 104 | 105 | Once submitted as an issue, a task must be turned into working Processing sketch and added to the example set. 106 | 107 | 1. In Processing, create a new sketch based on the task name, using 108 | Processing / Java naming conventions. For example: 109 | 110 | - Substring --> Substring 111 | - Anti-primes --> AntiPrimes 112 | - Binary search --> BinarySearch 113 | - 100 doors --> OneHundredDoors 114 | 115 | The resulting folder name and .pde file name must match. 116 | 117 | 118 | 2. Add the sketch code, run it and test that it works 119 | 3. Add a comment header with the name of the task, a link to the Rosetta Code 120 | page, and the basic task details taken from the wiki page header. 121 | For exampe: 122 | 123 | ``` 124 | /** 125 | * 100 Doors 126 | * http://rosettacode.org/wiki/100_doors#Processing 127 | * 128 | * There are 100 doors in a row that are all initially closed. 129 | * You make 100 passes by the doors. 130 | * 131 | * The first time through, visit every door and toggle the door 132 | * (if the door is closed, open it; if it is open, close it). 133 | * The second time, only visit every 2nd door (door #2, #4, #6, ...), 134 | * and toggle it. 135 | * The third time, visit every 3rd door (door #3, #6, #9, ...), 136 | * etc, until you only visit the 100th door. 137 | * 138 | * Task: 139 | * Answer the question: 140 | * What state are the doors in after the last pass? 141 | * Which are open, which are closed? 142 | */ 143 | ``` 144 | 145 | #### Submit sketches to the example set 146 | 147 | You may submit a sketch to the example set by: 148 | 149 | - Option 1: Post the sketch contents to the GitHub issue for that task. 150 | - Option 2: Fork the repo, commit the new sketch to the example folder, 151 | and open a pull request. 152 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ### GNU Free Documentation License 2 | 3 | Version 1.2, November 2002 4 | 5 | Copyright (C) 2000,2001,2002 Free Software Foundation, Inc. 6 | 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 7 | 8 | Everyone is permitted to copy and distribute verbatim copies 9 | of this license document, but changing it is not allowed. 10 | 11 | **0. PREAMBLE** 12 | 13 | The purpose of this License is to make a manual, textbook, or other 14 | functional and useful document "free" in the sense of freedom: to 15 | assure everyone the effective freedom to copy and redistribute it, 16 | with or without modifying it, either commercially or noncommercially. 17 | Secondarily, this License preserves for the author and publisher a way 18 | to get credit for their work, while not being considered responsible 19 | for modifications made by others. 20 | 21 | This License is a kind of "copyleft", which means that derivative 22 | works of the document must themselves be free in the same sense. It 23 | complements the GNU General Public License, which is a copyleft 24 | license designed for free software. 25 | 26 | We have designed this License in order to use it for manuals for free 27 | software, because free software needs free documentation: a free 28 | program should come with manuals providing the same freedoms that the 29 | software does. But this License is not limited to software manuals; it 30 | can be used for any textual work, regardless of subject matter or 31 | whether it is published as a printed book. We recommend this License 32 | principally for works whose purpose is instruction or reference. 33 | 34 | **1. APPLICABILITY AND DEFINITIONS** 35 | 36 | This License applies to any manual or other work, in any medium, that 37 | contains a notice placed by the copyright holder saying it can be 38 | distributed under the terms of this License. Such a notice grants a 39 | world-wide, royalty-free license, unlimited in duration, to use that 40 | work under the conditions stated herein. The "Document", below, refers 41 | to any such manual or work. Any member of the public is a licensee, 42 | and is addressed as "you". You accept the license if you copy, modify 43 | or distribute the work in a way requiring permission under copyright 44 | law. 45 | 46 | A "Modified Version" of the Document means any work containing the 47 | Document or a portion of it, either copied verbatim, or with 48 | modifications and/or translated into another language. 49 | 50 | A "Secondary Section" is a named appendix or a front-matter section of 51 | the Document that deals exclusively with the relationship of the 52 | publishers or authors of the Document to the Document's overall 53 | subject (or to related matters) and contains nothing that could fall 54 | directly within that overall subject. (Thus, if the Document is in 55 | part a textbook of mathematics, a Secondary Section may not explain 56 | any mathematics.) The relationship could be a matter of historical 57 | connection with the subject or with related matters, or of legal, 58 | commercial, philosophical, ethical or political position regarding 59 | them. 60 | 61 | The "Invariant Sections" are certain Secondary Sections whose titles 62 | are designated, as being those of Invariant Sections, in the notice 63 | that says that the Document is released under this License. If a 64 | section does not fit the above definition of Secondary then it is not 65 | allowed to be designated as Invariant. The Document may contain zero 66 | Invariant Sections. If the Document does not identify any Invariant 67 | Sections then there are none. 68 | 69 | The "Cover Texts" are certain short passages of text that are listed, 70 | as Front-Cover Texts or Back-Cover Texts, in the notice that says that 71 | the Document is released under this License. A Front-Cover Text may be 72 | at most 5 words, and a Back-Cover Text may be at most 25 words. 73 | 74 | A "Transparent" copy of the Document means a machine-readable copy, 75 | represented in a format whose specification is available to the 76 | general public, that is suitable for revising the document 77 | straightforwardly with generic text editors or (for images composed of 78 | pixels) generic paint programs or (for drawings) some widely available 79 | drawing editor, and that is suitable for input to text formatters or 80 | for automatic translation to a variety of formats suitable for input 81 | to text formatters. A copy made in an otherwise Transparent file 82 | format whose markup, or absence of markup, has been arranged to thwart 83 | or discourage subsequent modification by readers is not Transparent. 84 | An image format is not Transparent if used for any substantial amount 85 | of text. A copy that is not "Transparent" is called "Opaque". 86 | 87 | Examples of suitable formats for Transparent copies include plain 88 | ASCII without markup, Texinfo input format, LaTeX input format, SGML 89 | or XML using a publicly available DTD, and standard-conforming simple 90 | HTML, PostScript or PDF designed for human modification. Examples of 91 | transparent image formats include PNG, XCF and JPG. Opaque formats 92 | include proprietary formats that can be read and edited only by 93 | proprietary word processors, SGML or XML for which the DTD and/or 94 | processing tools are not generally available, and the 95 | machine-generated HTML, PostScript or PDF produced by some word 96 | processors for output purposes only. 97 | 98 | The "Title Page" means, for a printed book, the title page itself, 99 | plus such following pages as are needed to hold, legibly, the material 100 | this License requires to appear in the title page. For works in 101 | formats which do not have any title page as such, "Title Page" means 102 | the text near the most prominent appearance of the work's title, 103 | preceding the beginning of the body of the text. 104 | 105 | A section "Entitled XYZ" means a named subunit of the Document whose 106 | title either is precisely XYZ or contains XYZ in parentheses following 107 | text that translates XYZ in another language. (Here XYZ stands for a 108 | specific section name mentioned below, such as "Acknowledgements", 109 | "Dedications", "Endorsements", or "History".) To "Preserve the Title" 110 | of such a section when you modify the Document means that it remains a 111 | section "Entitled XYZ" according to this definition. 112 | 113 | The Document may include Warranty Disclaimers next to the notice which 114 | states that this License applies to the Document. These Warranty 115 | Disclaimers are considered to be included by reference in this 116 | License, but only as regards disclaiming warranties: any other 117 | implication that these Warranty Disclaimers may have is void and has 118 | no effect on the meaning of this License. 119 | 120 | **2. VERBATIM COPYING** 121 | 122 | You may copy and distribute the Document in any medium, either 123 | commercially or noncommercially, provided that this License, the 124 | copyright notices, and the license notice saying this License applies 125 | to the Document are reproduced in all copies, and that you add no 126 | other conditions whatsoever to those of this License. You may not use 127 | technical measures to obstruct or control the reading or further 128 | copying of the copies you make or distribute. However, you may accept 129 | compensation in exchange for copies. If you distribute a large enough 130 | number of copies you must also follow the conditions in section 3. 131 | 132 | You may also lend copies, under the same conditions stated above, and 133 | you may publicly display copies. 134 | 135 | **3. COPYING IN QUANTITY** 136 | 137 | If you publish printed copies (or copies in media that commonly have 138 | printed covers) of the Document, numbering more than 100, and the 139 | Document's license notice requires Cover Texts, you must enclose the 140 | copies in covers that carry, clearly and legibly, all these Cover 141 | Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on 142 | the back cover. Both covers must also clearly and legibly identify you 143 | as the publisher of these copies. The front cover must present the 144 | full title with all words of the title equally prominent and visible. 145 | You may add other material on the covers in addition. Copying with 146 | changes limited to the covers, as long as they preserve the title of 147 | the Document and satisfy these conditions, can be treated as verbatim 148 | copying in other respects. 149 | 150 | If the required texts for either cover are too voluminous to fit 151 | legibly, you should put the first ones listed (as many as fit 152 | reasonably) on the actual cover, and continue the rest onto adjacent 153 | pages. 154 | 155 | If you publish or distribute Opaque copies of the Document numbering 156 | more than 100, you must either include a machine-readable Transparent 157 | copy along with each Opaque copy, or state in or with each Opaque copy 158 | a computer-network location from which the general network-using 159 | public has access to download using public-standard network protocols 160 | a complete Transparent copy of the Document, free of added material. 161 | If you use the latter option, you must take reasonably prudent steps, 162 | when you begin distribution of Opaque copies in quantity, to ensure 163 | that this Transparent copy will remain thus accessible at the stated 164 | location until at least one year after the last time you distribute an 165 | Opaque copy (directly or through your agents or retailers) of that 166 | edition to the public. 167 | 168 | It is requested, but not required, that you contact the authors of the 169 | Document well before redistributing any large number of copies, to 170 | give them a chance to provide you with an updated version of the 171 | Document. 172 | 173 | **4. MODIFICATIONS** 174 | 175 | You may copy and distribute a Modified Version of the Document under 176 | the conditions of sections 2 and 3 above, provided that you release 177 | the Modified Version under precisely this License, with the Modified 178 | Version filling the role of the Document, thus licensing distribution 179 | and modification of the Modified Version to whoever possesses a copy 180 | of it. In addition, you must do these things in the Modified Version: 181 | 182 | - **A.** Use in the Title Page (and on the covers, if any) a title 183 | distinct from that of the Document, and from those of previous 184 | versions (which should, if there were any, be listed in the 185 | History section of the Document). You may use the same title as a 186 | previous version if the original publisher of that version 187 | gives permission. 188 | - **B.** List on the Title Page, as authors, one or more persons or 189 | entities responsible for authorship of the modifications in the 190 | Modified Version, together with at least five of the principal 191 | authors of the Document (all of its principal authors, if it has 192 | fewer than five), unless they release you from this requirement. 193 | - **C.** State on the Title page the name of the publisher of the 194 | Modified Version, as the publisher. 195 | - **D.** Preserve all the copyright notices of the Document. 196 | - **E.** Add an appropriate copyright notice for your modifications 197 | adjacent to the other copyright notices. 198 | - **F.** Include, immediately after the copyright notices, a license 199 | notice giving the public permission to use the Modified Version 200 | under the terms of this License, in the form shown in the 201 | Addendum below. 202 | - **G.** Preserve in that license notice the full lists of Invariant 203 | Sections and required Cover Texts given in the Document's 204 | license notice. 205 | - **H.** Include an unaltered copy of this License. 206 | - **I.** Preserve the section Entitled "History", Preserve its 207 | Title, and add to it an item stating at least the title, year, new 208 | authors, and publisher of the Modified Version as given on the 209 | Title Page. If there is no section Entitled "History" in the 210 | Document, create one stating the title, year, authors, and 211 | publisher of the Document as given on its Title Page, then add an 212 | item describing the Modified Version as stated in the 213 | previous sentence. 214 | - **J.** Preserve the network location, if any, given in the 215 | Document for public access to a Transparent copy of the Document, 216 | and likewise the network locations given in the Document for 217 | previous versions it was based on. These may be placed in the 218 | "History" section. You may omit a network location for a work that 219 | was published at least four years before the Document itself, or 220 | if the original publisher of the version it refers to 221 | gives permission. 222 | - **K.** For any section Entitled "Acknowledgements" or 223 | "Dedications", Preserve the Title of the section, and preserve in 224 | the section all the substance and tone of each of the contributor 225 | acknowledgements and/or dedications given therein. 226 | - **L.** Preserve all the Invariant Sections of the Document, 227 | unaltered in their text and in their titles. Section numbers or 228 | the equivalent are not considered part of the section titles. 229 | - **M.** Delete any section Entitled "Endorsements". Such a section 230 | may not be included in the Modified Version. 231 | - **N.** Do not retitle any existing section to be Entitled 232 | "Endorsements" or to conflict in title with any Invariant Section. 233 | - **O.** Preserve any Warranty Disclaimers. 234 | 235 | If the Modified Version includes new front-matter sections or 236 | appendices that qualify as Secondary Sections and contain no material 237 | copied from the Document, you may at your option designate some or all 238 | of these sections as invariant. To do this, add their titles to the 239 | list of Invariant Sections in the Modified Version's license notice. 240 | These titles must be distinct from any other section titles. 241 | 242 | You may add a section Entitled "Endorsements", provided it contains 243 | nothing but endorsements of your Modified Version by various 244 | parties--for example, statements of peer review or that the text has 245 | been approved by an organization as the authoritative definition of a 246 | standard. 247 | 248 | You may add a passage of up to five words as a Front-Cover Text, and a 249 | passage of up to 25 words as a Back-Cover Text, to the end of the list 250 | of Cover Texts in the Modified Version. Only one passage of 251 | Front-Cover Text and one of Back-Cover Text may be added by (or 252 | through arrangements made by) any one entity. If the Document already 253 | includes a cover text for the same cover, previously added by you or 254 | by arrangement made by the same entity you are acting on behalf of, 255 | you may not add another; but you may replace the old one, on explicit 256 | permission from the previous publisher that added the old one. 257 | 258 | The author(s) and publisher(s) of the Document do not by this License 259 | give permission to use their names for publicity for or to assert or 260 | imply endorsement of any Modified Version. 261 | 262 | **5. COMBINING DOCUMENTS** 263 | 264 | You may combine the Document with other documents released under this 265 | License, under the terms defined in section 4 above for modified 266 | versions, provided that you include in the combination all of the 267 | Invariant Sections of all of the original documents, unmodified, and 268 | list them all as Invariant Sections of your combined work in its 269 | license notice, and that you preserve all their Warranty Disclaimers. 270 | 271 | The combined work need only contain one copy of this License, and 272 | multiple identical Invariant Sections may be replaced with a single 273 | copy. If there are multiple Invariant Sections with the same name but 274 | different contents, make the title of each such section unique by 275 | adding at the end of it, in parentheses, the name of the original 276 | author or publisher of that section if known, or else a unique number. 277 | Make the same adjustment to the section titles in the list of 278 | Invariant Sections in the license notice of the combined work. 279 | 280 | In the combination, you must combine any sections Entitled "History" 281 | in the various original documents, forming one section Entitled 282 | "History"; likewise combine any sections Entitled "Acknowledgements", 283 | and any sections Entitled "Dedications". You must delete all sections 284 | Entitled "Endorsements." 285 | 286 | **6. COLLECTIONS OF DOCUMENTS** 287 | 288 | You may make a collection consisting of the Document and other 289 | documents released under this License, and replace the individual 290 | copies of this License in the various documents with a single copy 291 | that is included in the collection, provided that you follow the rules 292 | of this License for verbatim copying of each of the documents in all 293 | other respects. 294 | 295 | You may extract a single document from such a collection, and 296 | distribute it individually under this License, provided you insert a 297 | copy of this License into the extracted document, and follow this 298 | License in all other respects regarding verbatim copying of that 299 | document. 300 | 301 | **7. AGGREGATION WITH INDEPENDENT WORKS** 302 | 303 | A compilation of the Document or its derivatives with other separate 304 | and independent documents or works, in or on a volume of a storage or 305 | distribution medium, is called an "aggregate" if the copyright 306 | resulting from the compilation is not used to limit the legal rights 307 | of the compilation's users beyond what the individual works permit. 308 | When the Document is included in an aggregate, this License does not 309 | apply to the other works in the aggregate which are not themselves 310 | derivative works of the Document. 311 | 312 | If the Cover Text requirement of section 3 is applicable to these 313 | copies of the Document, then if the Document is less than one half of 314 | the entire aggregate, the Document's Cover Texts may be placed on 315 | covers that bracket the Document within the aggregate, or the 316 | electronic equivalent of covers if the Document is in electronic form. 317 | Otherwise they must appear on printed covers that bracket the whole 318 | aggregate. 319 | 320 | **8. TRANSLATION** 321 | 322 | Translation is considered a kind of modification, so you may 323 | distribute translations of the Document under the terms of section 4. 324 | Replacing Invariant Sections with translations requires special 325 | permission from their copyright holders, but you may include 326 | translations of some or all Invariant Sections in addition to the 327 | original versions of these Invariant Sections. You may include a 328 | translation of this License, and all the license notices in the 329 | Document, and any Warranty Disclaimers, provided that you also include 330 | the original English version of this License and the original versions 331 | of those notices and disclaimers. In case of a disagreement between 332 | the translation and the original version of this License or a notice 333 | or disclaimer, the original version will prevail. 334 | 335 | If a section in the Document is Entitled "Acknowledgements", 336 | "Dedications", or "History", the requirement (section 4) to Preserve 337 | its Title (section 1) will typically require changing the actual 338 | title. 339 | 340 | **9. TERMINATION** 341 | 342 | You may not copy, modify, sublicense, or distribute the Document 343 | except as expressly provided for under this License. Any other attempt 344 | to copy, modify, sublicense or distribute the Document is void, and 345 | will automatically terminate your rights under this License. However, 346 | parties who have received copies, or rights, from you under this 347 | License will not have their licenses terminated so long as such 348 | parties remain in full compliance. 349 | 350 | **10. FUTURE REVISIONS OF THIS LICENSE** 351 | 352 | The Free Software Foundation may publish new, revised versions of the 353 | GNU Free Documentation License from time to time. Such new versions 354 | will be similar in spirit to the present version, but may differ in 355 | detail to address new problems or concerns. See 356 | https://www.gnu.org/licenses/. 357 | 358 | Each version of the License is given a distinguishing version number. 359 | If the Document specifies that a particular numbered version of this 360 | License "or any later version" applies to it, you have the option of 361 | following the terms and conditions either of that specified version or 362 | of any later version that has been published (not as a draft) by the 363 | Free Software Foundation. If the Document does not specify a version 364 | number of this License, you may choose any version ever published (not 365 | as a draft) by the Free Software Foundation. 366 | 367 | ### [How to use this License for your documents]() 368 | 369 | To use this License in a document you have written, include a copy of 370 | the License in the document and put the following copyright and 371 | license notices just after the title page: 372 | 373 | Copyright (c) YEAR YOUR NAME. 374 | Permission is granted to copy, distribute and/or modify this document 375 | under the terms of the GNU Free Documentation License, Version 1.2 376 | or any later version published by the Free Software Foundation; 377 | with no Invariant Sections, no Front-Cover Texts, and no Back-Cover 378 | Texts. A copy of the license is included in the section entitled "GNU 379 | Free Documentation License". 380 | 381 | If you have Invariant Sections, Front-Cover Texts and Back-Cover 382 | Texts, replace the "with...Texts." line with this: 383 | 384 | with the Invariant Sections being LIST THEIR TITLES, with the 385 | Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST. 386 | 387 | If you have Invariant Sections without Cover Texts, or some other 388 | combination of the three, merge those two alternatives to suit the 389 | situation. 390 | 391 | If your document contains nontrivial examples of program code, we 392 | recommend releasing these examples in parallel under your choice of 393 | free software license, such as the GNU General Public License, to 394 | permit their use in free software. 395 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rosetta Code Examples for P5 2 | ![Rosetta Code Examples for P5 Logo 300x300](logo/rosetta_examples_p5-logo-300x300.png) 3 | 4 | Examples from [Rosetta Code](http://rosettacode.org/) 5 | for [Processing](http://processing.org) (Java Mode) 6 | and [Python Mode for Processing](https://py.processing.org/) 7 | and [Processing.R](https://processing-r.github.io/). 8 | 9 | 10 | These sets of example Processing sketches (includiing Java mode, Python mode, 11 | and R mode) compile available versions of code tasks listed on the Rosetta Code 12 | wiki. The examples are directly downloadable from the repository. They may 13 | also be loaded directly into the Processing PDE desktop environment through 14 | Contributions Manager under the Examples tab. 15 | 16 | > Rosetta Code is a programming chrestomathy site. The idea is to present 17 | > solutions to the same task in as many different languages as possible, to 18 | > demonstrate how languages are similar and different, and to aid a person 19 | > with a grounding in one approach to a problem in learning another. 20 | 21 | Rosetta Code has ~1000 tasks including file and sysem access, string 22 | manipulation, math problems, graphics output and more -- with some of these 23 | tasks implemented in dozens or even hundreds of programming languages (although 24 | the example sketches here only the Processing implementations). 25 | 26 | A few examples include: 27 | 28 | - Anagrams 29 | - Archimedean spiral 30 | - Binary digits 31 | - Draw a pixel 32 | - FizzBuzz 33 | - Josephus Problem 34 | - Levenshtein distance 35 | - Mandelbrot set 36 | - Ninety-nine bottles 37 | - Rename a file 38 | - Sieve of Eratosthenes 39 | 40 | Simply put, this project both solicits Processing contributions to Rosetta Code 41 | and curates the resulting examples as a set for Processing language learners. 42 | 43 | 44 | ## Getting the examples 45 | 46 | Examples are available from the github project homepage: 47 | https://github.com/jeremydouglass/rosetta_examples_p5 48 | 49 | You may download the files as a zip or clone the repository using the 50 | "Clone or Download" button. 51 | 52 | Another option is to install all the examples through the desktop Processing 53 | Development Environment (PDE). From the menu, File > Examples > Add Examples 54 | will open the Contributions Manager to the Examples tab. Download the example 55 | set. All sketches will be installed in the Examples subfolder of your 56 | Processing data folder, and available through the Examples pop-up menu under 57 | Contributed Examples > Rosetta Examples for P5. 58 | 59 | Examples are organized in subfolders by mode / language: Java, Python, and R. 60 | 61 | 62 | ## License and Contributions 63 | 64 | This example set uses the same open documentation license as the Rosetta Code 65 | Project, and contributes and redistributes Processing Examples under those same 66 | terms. 67 | 68 | See [LICENSE.md](LICENSE.md) for the current license. 69 | 70 | See [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how you can 71 | contribute to this repository. 72 | 73 | -------------------------------------------------------------------------------- /examples.properties: -------------------------------------------------------------------------------- 1 | name=Rosetta Examples for P5 2 | authors=[Jeremy Douglass](http://jeremydouglass.com) 3 | url=https://github.com/jeremydouglass/rosetta_examples_p5 4 | category=Other 5 | version=14 6 | prettyVersion=v0.14 7 | sentence=Common coding tasks in Processing (Java, Python, and R modes) from the Rosetta Code chrestomathy website. 8 | paragraph=Rosetta Code is a programming chrestomathy site. The idea is to present solutions to the same task in as many different languages as possible, to demonstrate how languages are similar and different, and to aid a person with a grounding in one approach to a problem in learning another. This example set compiles the available RosettaCode.org tasks for Processing (Java, Python, and R modes). 9 | minVersion=0 10 | maxVersion=0 11 | -------------------------------------------------------------------------------- /examples/Java/AckermannFunction/AckermannFunction.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Ackermann function 3 | * https://rosettacode.org/wiki/Ackermann_function#Processing 4 | * Processing 3.4 5 | * 2019-12 Jeremy Douglass 6 | * 2017-10-27 Edmund 7 | * 8 | * The Ackermann function is a classic example of a recursive function, notable 9 | * especially because it is not a primitive recursive function. It grows very 10 | * quickly in value, as does the size of its call tree. 11 | * 12 | * The Ackermann function is usually defined as follows: 13 | * 14 | * ( n+1 if m = 0 15 | * A(m,n) = ( A(m-1, 1) if m > 0 and n = 0 16 | * ( A(m-1, A(m, n-1)) if m > 0 and n > 0 17 | * Its arguments are never negative and it always terminates. 18 | * 19 | * Task: 20 | * 21 | * Write a function which returns the value of A(m,n). 22 | * Arbitrary precision is preferred (since the function grows so quickly), 23 | * but not required. 24 | */ 25 | 26 | void setup() { 27 | for (int m=0; m<4; m++) { 28 | for (int n=0; n<7; n++) { 29 | print(ackermann(m, n), " "); 30 | } 31 | println(); 32 | } 33 | } 34 | 35 | int ackermann(int m, int n) { 36 | if (m == 0) 37 | return n + 1; 38 | else if (m > 0 && n == 0) 39 | return ackermann(m - 1, 1); 40 | else 41 | return ackermann( m - 1, ackermann(m, n - 1) ); 42 | } 43 | 44 | /** 45 | * Output is the first 4x7 Ackermann's numbers. 46 | * 1 2 3 4 5 6 7 47 | * 2 3 4 5 6 7 8 48 | * 3 5 7 9 11 13 15 49 | * 5 13 29 61 125 253 509 50 | */ 51 | -------------------------------------------------------------------------------- /examples/Java/Anagrams/Anagrams.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Anagrams 3 | * https://rosettacode.org/wiki/Anagrams#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * When two or more words are composed of the same characters, but in a 8 | * different order, they are called anagrams. 9 | * 10 | * Task: 11 | * 12 | * Using the word list at http://wiki.puzzlers.org/pub/wordlists/unixdict.txt 13 | * find the sets of words that share the same characters that contain the most 14 | * words in them. 15 | */ 16 | 17 | import java.util.Map; 18 | 19 | void setup() { 20 | String[] words = loadStrings("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"); 21 | topAnagrams(words); 22 | } 23 | 24 | void topAnagrams (String[] words) { 25 | HashMap anagrams = new HashMap(); 26 | int maxcount = 0; 27 | for (String word : words) { 28 | char[] chars = word.toCharArray(); 29 | chars = sort(chars); 30 | String key = new String(chars); 31 | if (!anagrams.containsKey(key)) { 32 | anagrams.put(key, new StringList()); 33 | } 34 | anagrams.get(key).append(word); 35 | maxcount = max(maxcount, anagrams.get(key).size()); 36 | } 37 | for (StringList ana : anagrams.values()) { 38 | if (ana.size() >= maxcount) { 39 | println(ana); 40 | } 41 | } 42 | } 43 | 44 | /** 45 | * OUTPUT 46 | * 47 | * StringList size=5 [ "evil", "levi", "live", "veil", "vile" ] 48 | * StringList size=5 [ "abel", "able", "bale", "bela", "elba" ] 49 | * StringList size=5 [ "elan", "lane", "lean", "lena", "neal" ] 50 | * StringList size=5 [ "angel", "angle", "galen", "glean", "lange" ] 51 | * StringList size=5 [ "alger", "glare", "lager", "large", "regal" ] 52 | * StringList size=5 [ "caret", "carte", "cater", "crate", "trace" ] 53 | */ 54 | -------------------------------------------------------------------------------- /examples/Java/Animation/Animation.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Animation 3 | * https://rosettacode.org/wiki/Animation#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Create a window containing the string "Hello World! " (the trailing space 10 | * is significant). Make the text appear to be rotating right by periodically 11 | * removing one letter from the end of the string and attaching it to the front. 12 | * When the user clicks on the (windowed) text, it should reverse its direction. 13 | */ 14 | 15 | String txt = "Hello, world! "; 16 | boolean dir = true; 17 | 18 | void draw() { 19 | background(128); 20 | text(txt, 10, height/2); 21 | if (frameCount%10==0) { 22 | if (dir) { 23 | txt = rotate(txt, 1); 24 | } else { 25 | txt = rotate(txt, txt.length()-1); 26 | } 27 | println(txt); 28 | } 29 | } 30 | 31 | void mouseReleased() { 32 | dir = !dir; 33 | } 34 | 35 | String rotate(String text, int startIdx) { 36 | char[] rotated = new char[text.length()]; 37 | for (int i = 0; i < text.length(); i++) { 38 | rotated[i] = text.charAt((i + startIdx) % text.length()); 39 | } 40 | return String.valueOf(rotated); 41 | } 42 | -------------------------------------------------------------------------------- /examples/Java/ArchimedeanSpiral_Lines/ArchimedeanSpiral_Lines.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Archimedean Spiral -- Line Segments 3 | * https://rosettacode.org/wiki/Archimedean_spiral#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 7 | * The Archimedean spiral is a spiral named after the Greek mathematician 8 | * Archimedes. An Archimedean spiral can be described by the equation: 9 | * 10 | * r = a + bθ 11 | * 12 | * with real numbers a and b. 13 | * 14 | * Task: 15 | * 16 | * Draw an Archimedean spiral. 17 | */ 18 | 19 | // Draw each new line segments anchored to the previous point in order to keep 20 | // the spiral visually connected no matter how much the radius expands. 21 | 22 | float px, py, x, y; 23 | float theta; 24 | float rotation; 25 | 26 | void setup() { 27 | size(300, 300); 28 | px = py = x = y = theta = 0; 29 | rotation = 0.1; 30 | background(255); 31 | } 32 | 33 | void draw() { 34 | translate(width/2.0, height/2.0); 35 | x = theta*cos(theta/PI); 36 | y = (theta)*sin(theta/PI); 37 | line(x, y, px, py); 38 | theta = theta + rotation; 39 | px = x; 40 | py = y; 41 | // check restart 42 | if (px>width/2.0) frameCount=-1; 43 | } 44 | -------------------------------------------------------------------------------- /examples/Java/ArchimedeanSpiral_LinesRotated/ArchimedeanSpiral_LinesRotated.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Archimedean Spiral -- Lines Rotated 3 | * https://rosettacode.org/wiki/Archimedean_spiral#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 7 | * The Archimedean spiral is a spiral named after the Greek mathematician 8 | * Archimedes. An Archimedean spiral can be described by the equation: 9 | * 10 | * r = a + bθ 11 | * 12 | * with real numbers a and b. 13 | * 14 | * Task: 15 | * 16 | * Draw an Archimedean spiral. 17 | */ 18 | 19 | // Uses the built-in rotate() and screenX() to rotate the frame of reference 20 | // and then recover the rotated screen position of each next point. 21 | // 22 | // Draw each new line segments anchored to the previous point in order to keep 23 | // the spiral visaully connected no matter how much the radius expands. 24 | 25 | float x, y, px, py; 26 | float theta; 27 | float rotation; 28 | 29 | void setup() { 30 | size(300, 300); 31 | x = y = px = py = theta = 0; 32 | rotation = 0.1; 33 | background(255); 34 | } 35 | 36 | void draw() { 37 | // find coordinates with rotating reference frame 38 | pushMatrix(); 39 | rotate(theta/PI); 40 | x = screenX(theta, 0); 41 | y = screenY(theta, 0); 42 | popMatrix(); 43 | 44 | translate(width/2.0, height/2.0); 45 | theta += rotation; 46 | line(px, py, x, y); 47 | px = x; 48 | py = y; 49 | if (theta>width/2.0) frameCount=-1; // start over 50 | } 51 | -------------------------------------------------------------------------------- /examples/Java/ArchimedeanSpiral_Points/ArchimedeanSpiral_Points.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Archimedean Spiral -- Points 3 | * https://rosettacode.org/wiki/Archimedean_spiral#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 2019-04-12 Cdr6934 7 | * 8 | * The Archimedean spiral is a spiral named after the Greek mathematician 9 | * Archimedes. An Archimedean spiral can be described by the equation: 10 | * 11 | * r = a + bθ 12 | * 13 | * with real numbers a and b. 14 | * 15 | * Task: 16 | * 17 | * Draw an Archimedean spiral. 18 | */ 19 | 20 | // When drawn with points the rotation must be very small, and initially the 21 | // animation is very slow. This is because the points will move further and 22 | // further apart as the radius increases. 23 | 24 | float x, y; 25 | float theta; 26 | float rotation; 27 | 28 | void setup() { 29 | size(300, 300); 30 | theta = 0; 31 | rotation = 0.1; 32 | background(255); 33 | } 34 | 35 | void draw() { 36 | translate(width/2.0, height/2.0); 37 | x = theta*cos(theta/PI); 38 | y = theta*sin(theta/PI); 39 | point(x, y); 40 | theta = theta + rotation; 41 | // check restart 42 | if (x>width/2.0) frameCount=-1; 43 | } 44 | -------------------------------------------------------------------------------- /examples/Java/ArchimedeanSpiral_PointsRotatedMatrix/ArchimedeanSpiral_PointsRotatedMatrix.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Archimedean Spiral -- Points Rotated Matrix 3 | * https://rosettacode.org/wiki/Archimedean_spiral#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 7 | * The Archimedean spiral is a spiral named after the Greek mathematician 8 | * Archimedes. An Archimedean spiral can be described by the equation: 9 | * 10 | * r = a + bθ 11 | * 12 | * with real numbers a and b. 13 | * 14 | * Task: 15 | * 16 | * Draw an Archimedean spiral. 17 | */ 18 | 19 | // Rotates the canvas matrix using the built-in rotate() and draws a simple 20 | // point, rather than computing rotated coordinates with sin()/cos(). 21 | // 22 | // When drawn with points the rotation must be very small, and initially the 23 | // animation is very slow. This is because the points will move further and 24 | // further apart as the radius increases. 25 | 26 | float theta; 27 | float rotation; 28 | 29 | void setup() { 30 | size(300, 300); 31 | theta = 0; 32 | rotation = 0.1; 33 | background(255); 34 | } 35 | 36 | void draw() { 37 | translate(width/2.0, height/2.0); 38 | theta += rotation; 39 | rotate(theta/PI); 40 | point(theta, 0); 41 | // check restart 42 | if (theta>width/2.0) frameCount=-1; 43 | } 44 | -------------------------------------------------------------------------------- /examples/Java/ArchimedeanSpiral_PointsRotatedPVector/ArchimedeanSpiral_PointsRotatedPVector.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Archimedean Spiral -- Points Rotated PVector 3 | * https://rosettacode.org/wiki/Archimedean_spiral#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 7 | * The Archimedean spiral is a spiral named after the Greek mathematician 8 | * Archimedes. An Archimedean spiral can be described by the equation: 9 | * 10 | * r = a + bθ 11 | * 12 | * with real numbers a and b. 13 | * 14 | * Task: 15 | * 16 | * Draw an Archimedean spiral. 17 | */ 18 | 19 | // Rotates a PVector object of increasing magnitude and draws its point rather 20 | // than computing rotated coordinates with sin()/cos(). 21 | // 22 | // When drawn with points the rotation must be very small, and initially the 23 | // animation is very slow. This is because the points will move further and 24 | // further apart as the radius increases. 25 | 26 | PVector pv; 27 | float rotation; 28 | 29 | void setup() { 30 | size(300, 300); 31 | rotation = 0.1; 32 | pv = new PVector(rotation, 0); 33 | background(255); 34 | } 35 | 36 | void draw() { 37 | translate(width/2.0, height/2.0); 38 | pv.setMag(pv.mag()+rotation); 39 | println(pv.mag()); 40 | pv.rotate(rotation/PI); 41 | point(pv.x, pv.y); 42 | // check restart 43 | if (pv.mag()>width/2.0) frameCount=-1; 44 | } 45 | -------------------------------------------------------------------------------- /examples/Java/BarnsleyFern/BarnsleyFern.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Barnsley Fern 3 | * https://rosettacode.org/wiki/Barnsley_fern#Processing 4 | * Processing 3.4 5 | * 2016-05-03 Trizen 6 | * 7 | * A Barnsley fern is a fractal named after British mathematician Michael 8 | * Barnsley and can be created using an iterated function system (IFS). 9 | * 10 | * Task: 11 | * 12 | * Create this fractal fern, using the following transformations: 13 | * 14 | * ƒ1 (chosen 1% of the time) 15 | * xn + 1 = 0 16 | * yn + 1 = 0.16 yn 17 | * ƒ2 (chosen 85% of the time) 18 | * xn + 1 = 0.85 xn + 0.04 yn 19 | * yn + 1 = −0.04 xn + 0.85 yn + 1.6 20 | * ƒ3 (chosen 7% of the time) 21 | * xn + 1 = 0.2 xn − 0.26 yn 22 | * yn + 1 = 0.23 xn + 0.22 yn + 1.6 23 | * ƒ4 (chosen 7% of the time) 24 | * xn + 1 = −0.15 xn + 0.28 yn 25 | * yn + 1 = 0.26 xn + 0.24 yn + 0.44. 26 | * 27 | * Starting position: x = 0, y = 0 28 | */ 29 | 30 | void setup() { 31 | size(640, 640); 32 | background(0, 0, 0); 33 | } 34 | 35 | float x = 0; 36 | float y = 0; 37 | 38 | void draw() { 39 | for (int i = 0; i < 100000; i++) { 40 | 41 | float xt = 0; 42 | float yt = 0; 43 | 44 | float r = random(100); 45 | 46 | if (r <= 1) { 47 | xt = 0; 48 | yt = 0.16*y; 49 | } else if (r <= 8) { 50 | xt = 0.20*x - 0.26*y; 51 | yt = 0.23*x + 0.22*y + 1.60; 52 | } else if (r <= 15) { 53 | xt = -0.15*x + 0.28*y; 54 | yt = 0.26*x + 0.24*y + 0.44; 55 | } else { 56 | xt = 0.85*x + 0.04*y; 57 | yt = -0.04*x + 0.85*y + 1.60; 58 | } 59 | 60 | x = xt; 61 | y = yt; 62 | 63 | int m = round(width/2 + 60*x); 64 | int n = height-round(60*y); 65 | 66 | set(m, n, #00ff00); 67 | } 68 | noLoop(); 69 | } 70 | -------------------------------------------------------------------------------- /examples/Java/BezierCurvesCubic/BezierCurvesCubic.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Bézier Curves Cubic 3 | * http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic#Processing 4 | * Processing 3.4 5 | * 2019-02-24 Noel 6 | * 7 | * Task: 8 | * 9 | * Using the data storage type for raster images and a draw_line function, 10 | * draw a cubic bezier curve. 11 | */ 12 | 13 | noFill(); 14 | bezier(85, 20, 10, 10, 90, 90, 15, 80); 15 | 16 | /* 17 | bezier(x1, y1, x2, y2, x3, y3, x4, y4) 18 | Can also be drawn in 3D. 19 | bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4) 20 | */ 21 | -------------------------------------------------------------------------------- /examples/Java/BezierCurvesCubicInteractive/BezierCurvesCubicInteractive.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Bézier Curves Cubic (Interactive) 3 | * http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic#Processing 4 | * Processing 3.4 5 | * 2019-02-24 Noel 6 | * 7 | * Task: 8 | * 9 | * Using the data storage type for raster images and a draw_line function, 10 | * draw a cubic bezier curve. 11 | */ 12 | 13 | // A working sketch with movable anchor and control points. 14 | // It can be run online : 15 | // https://www.openprocessing.org/sketch/846556/ 16 | 17 | float[] x = new float[4]; 18 | float[] y = new float[4]; 19 | boolean[] permitDrag = new boolean[4]; 20 | 21 | void setup() { 22 | size(300, 300); 23 | smooth(); 24 | // startpoint coordinates 25 | x[0] = x[1] = 50; 26 | y[0] = 50; 27 | y[1] = y[2] = 150; 28 | x[2] = x[3] = 250; 29 | y[3] = 250; 30 | 31 | } 32 | 33 | void draw() { 34 | background(255); 35 | noFill(); 36 | stroke(0, 0, 255); 37 | bezier (x[1], y[1], x[0], y[0], x[3], y[3], x[2], y[2]); 38 | // the bezier handles 39 | strokeWeight(1); 40 | stroke(100); 41 | line(x[0], y[0], x[1], y[1]); 42 | line(x[2], y[2], x[3], y[3]); 43 | // the anchor and control points 44 | stroke(0); 45 | fill(0); 46 | for (int i =0; i< 4; i++) { 47 | if (i ==0 || i==3) { 48 | fill(255, 100, 10); 49 | rectMode(CENTER); 50 | rect(x[i], y[i], 5, 5); 51 | } else { 52 | fill(0); 53 | ellipse(x[i], y[i], 5, 5); 54 | } 55 | } 56 | 57 | // permit dragging 58 | for (int i =0; i< 4; i++) { 59 | if (permitDrag[i]) { 60 | x[i] = mouseX; 61 | y[i] = mouseY; 62 | } 63 | } 64 | } 65 | 66 | void mouseReleased () { 67 | for (int i =0; i< 4; i++) { 68 | permitDrag[i] = false; 69 | } 70 | } 71 | 72 | void mousePressed () { 73 | for (int i =0; i< 4; i++) { 74 | if (mouseX>=x[i]-5 && mouseX<=x[i]+10 && mouseY>=y[i]-5 && mouseY<=y[i]+10) { 75 | permitDrag[i] = true; 76 | } 77 | } 78 | } 79 | 80 | // hand cursor when over dragging over points 81 | void mouseMoved () { 82 | cursor(ARROW); 83 | for (int i =0; i< 4; i++) { 84 | if (mouseX>=x[i]-5 && mouseX<=x[i]+10 && mouseY>=y[i]-5 && mouseY<=y[i]+10) { 85 | cursor(HAND); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /examples/Java/BinaryDigits/BinaryDigits.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * BinaryDigits 3 | * https://rosettacode.org/wiki/Binary_digits#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Create and display the sequence of binary digits for a given non-negative 10 | * integer. 11 | * 12 | * The decimal value 5 should produce an output of 101 13 | * The decimal value 50 should produce an output of 110010 14 | * The decimal value 9000 should produce an output of 10001100101000 15 | * 16 | * The results can be achieved using built-in radix functions within the 17 | * language (if these are available), or alternatively a user defined function 18 | * can be used. The output produced should consist just of the binary digits of 19 | * each number followed by a newline. There should be no other whitespace, 20 | * radix or sign markers in the produced output, and leading zeros should not 21 | * appear in the results. 22 | */ 23 | 24 | println(Integer.toBinaryString(5)); // 101 25 | println(Integer.toBinaryString(50)); // 110010 26 | println(Integer.toBinaryString(9000)); // 10001100101000 27 | 28 | //Processing also has a binary() function, but this returns zero-padded results 29 | 30 | println(binary(5)); // 00000000000101 31 | println(binary(50)); // 00000000110010 32 | println(binary(9000)); // 10001100101000 33 | -------------------------------------------------------------------------------- /examples/Java/Bitmap/Bitmap.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Bitmap 3 | * https://rosettacode.org/wiki/Bitmap#Processing 4 | * Processing 3.4 5 | * 2019-12-08 Noel 6 | * 7 | * Task: 8 | * 9 | * Show a basic storage type to handle a simple RGB raster graphics image, 10 | * and some primitive associated functions. If possible provide a function to 11 | * allocate an uninitialised image, given its width and height, and provide 3 12 | * additional functions: 13 | * - one to fill an image with a plain RGB color, 14 | * - one to set a given pixel with a color, 15 | * -- one to get the color of a pixel. 16 | * (If there are specificities about the storage or the allocation, 17 | * explain those.) 18 | */ 19 | 20 | PGraphics bitmap = createGraphics(100, 100); // Create the bitmap 21 | bitmap.beginDraw(); 22 | bitmap.background(255, 0, 0); // Fill bitmap with red rgb color 23 | bitmap.endDraw(); 24 | image(bitmap, 0, 0); // Place bitmap on screen. 25 | color b = color(0, 0, 255); // Define a blue rgb color 26 | set(50, 50, b); // Set blue colored pixel in the middle of the screen 27 | color c = get(50, 50); // Get the color of same pixel 28 | if (b == c) print("Color changed correctly"); // Verify 29 | -------------------------------------------------------------------------------- /examples/Java/BrownianTree/BrownianTree.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Brownian Tree 3 | * https://rosettacode.org/wiki/Brownian_tree#Processing 4 | * Processing 3.4 5 | * 2016-06 Trizen 6 | * 2020-03 Alexandre Villares 7 | * 8 | * Task: 9 | * 10 | * Generate and draw a Brownian Tree. 11 | * 12 | * A Brownian Tree is generated as a result of an initial seed, 13 | * followed by the interaction of two processes. 14 | * 15 | * The initial "seed" is placed somewhere within the field. Where is not particularly important; 16 | * it could be randomized, or it could be a fixed point. 17 | * Particles are injected into the field, and are individually given a (typically random) motion 18 | * pattern. When a particle collides with the seed or tree, its position is fixed, and it's 19 | * considered to be part of the tree. 20 | * 21 | * Because of the lax rules governing the random nature of the particle's placement and motion, 22 | * no two resulting trees are really expected to be the same, or even necessarily have the same 23 | * general shape. 24 | */ 25 | 26 | boolean SIDESTICK = false; 27 | boolean[][] isTaken; 28 | 29 | void setup() { 30 | size(512, 512); 31 | background(0); 32 | isTaken = new boolean[width][height]; 33 | isTaken[width/2][height/2] = true; 34 | } 35 | 36 | void draw() { 37 | int x = floor(random(width)); 38 | int y = floor(random(height)); 39 | if (isTaken[x][y]) { 40 | return; 41 | } 42 | while (true) { 43 | int xp = x + floor(random(-1, 2)); 44 | int yp = y + floor(random(-1, 2)); 45 | boolean iscontained = ( 46 | 0 <= xp && xp < width && 47 | 0 <= yp && yp < height 48 | ); 49 | if (iscontained && !isTaken[xp][yp]) { 50 | x = xp; 51 | y = yp; 52 | continue; 53 | } else { 54 | if (SIDESTICK || (iscontained && isTaken[xp][yp])) { 55 | isTaken[x][y] = true; 56 | set(x, y, #FFFFFF); 57 | } 58 | break; 59 | } 60 | } 61 | if (frameCount > width * height) { 62 | noLoop(); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /examples/Java/BullsAndCows/BullsAndCows.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Bulls and Cows 3 | * https://rosettacode.org/wiki/Bulls_and_cows#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * Bulls and Cows is an old game played with pencil and paper that was later 8 | * implemented using computers. 9 | * 10 | * Task: 11 | * 12 | * Create a four digit random number from the digits 1 to 9, without 13 | * duplication. 14 | * 15 | * The program should: 16 | * 17 | * ask for guesses to this number 18 | * reject guesses that are malformed 19 | * print the score for the guess 20 | * 21 | * The score is computed as: 22 | * 23 | * The player wins if the guess is the same as the randomly chosen number, 24 | * and the program ends. 25 | * A score of one bull is accumulated for each digit in the guess that equals 26 | * the corresponding digit in the randomly chosen initial number. 27 | * A score of one cow is accumulated for each digit in the guess that also 28 | * appears in the randomly chosen number, but in the wrong position. 29 | * 30 | * This sketch produces both a console transcript and GUI interface to the game. 31 | * Creates a new game each time the guess is correct; tracks number of games 32 | * won. 33 | */ 34 | 35 | IntDict score; 36 | StringList choices; 37 | StringList guess; 38 | StringList secret; 39 | int gamesWon = -1; 40 | 41 | void setup() { 42 | choices = new StringList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); 43 | newGame(); 44 | } 45 | 46 | void newGame() { 47 | gamesWon++; 48 | choices.shuffle(); 49 | secret = new StringList(); 50 | for (int i=0; i<4; i++) { // selections 51 | secret.append(choices.get(i)); 52 | } 53 | newGuess(); 54 | println("\nsecret:", secret, "\n"); 55 | } 56 | 57 | void newGuess() { 58 | guess = new StringList(); 59 | score = null; 60 | } 61 | 62 | void draw() { 63 | background(0); 64 | text("Bulls & Cows " + gamesWon, 5, 20); 65 | for (int i=0; i=48 && key<=57) guess.append(str(key)); 78 | if (guess.size()==secret.size()) { 79 | score = checkScore(secret, guess); 80 | println("guess: ", guess, "\n", score, "wins:", gamesWon); 81 | } 82 | } 83 | 84 | IntDict checkScore(StringList secret, StringList guess) { 85 | IntDict result = new IntDict(); 86 | result.set("bulls", 0); 87 | result.set("cows", 0); 88 | for (int i=0; i> 16 & 0xFF, p >> 8 & 0xFF, p >> 8 & 0xFF); 35 | } 36 | -------------------------------------------------------------------------------- /examples/Java/ColorWheel/ColorWheel.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Color Wheel 3 | * https://rosettacode.org/wiki/Color_wheel#Processing 4 | * Processing 3.4 5 | * 2020-03 Alexandre Villares 6 | * 7 | * Task: 8 | * 9 | * Write a function to draw a HSV color wheel completely with code. 10 | * https://en.wikipedia.org/wiki/HSL_and_HSV 11 | * 12 | * This is strictly for learning purposes only. It's highly recommended that 13 | * you use an image in an actual application to actually draw the color wheel 14 | * (as procedurally drawing is super slow). This does help you understand 15 | * how color wheels work and this can easily be used to determine a color 16 | * value based on a position within a circle. 17 | */ 18 | 19 | size(300, 300); 20 | background(0); 21 | float radius = min(width, height) / 2.0; 22 | float cx = width / 2; 23 | float cy = width / 2; 24 | for (int x = 0; x < width; x++) { 25 | for (int y = 0; y < width; y++) { 26 | float rx = x - cx; 27 | float ry = y - cy; 28 | float s = sqrt(sq(rx) + sq(ry)) / radius; 29 | if (s <= 1.0) { 30 | float h = ((atan2(ry, rx) / PI) + 1.0) / 2.0; 31 | colorMode(HSB); 32 | color c = color(int(h * 255), int(s * 255), 255); 33 | set(x, y, c); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /examples/Java/Comments/Comments.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Comments 3 | * https://rosettacode.org/wiki/Comments#Processing 4 | * Processing 3.4 5 | * 2019-12 Jeremy Douglass 6 | * 2016-04-09 Edmund 7 | * 8 | * Task: 9 | * 10 | * Show all ways to include text in a language source file that's 11 | * completely ignored by the compiler or interpreter. 12 | */ 13 | 14 | 15 | // a single-line comment 16 | 17 | 18 | /* a multi-line 19 | comment 20 | */ 21 | 22 | 23 | /* 24 | * a multi-line comment 25 | * with some decorative stars 26 | */ 27 | 28 | 29 | // comment out a code line 30 | // println("foo"); 31 | 32 | 33 | // comment at the end of a line 34 | println("foo", "bar"); // "baz" 35 | 36 | 37 | // comment inline -- NOT recommended style 38 | println("foo", /*"bar",*/ "baz"); 39 | -------------------------------------------------------------------------------- /examples/Java/DragonCurve/DragonCurve.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Dragon Curve 3 | * https://www.rosettacode.org/wiki/Dragon_curve#Processing 4 | * Processing 3.4 5 | * 2020-02 Noel 6 | * 7 | * Task: 8 | * 9 | * Create and display a dragon curve fractal. 10 | * 11 | * https://en.wikipedia.org/wiki/Dragon_curve 12 | * 13 | * (You may either display the curve directly or write it to an image file.) 14 | * 15 | * For some brief notes on the algorithms used and how they might suit various 16 | * languages, see the Rosetta Code task page. 17 | */ 18 | 19 | float l = 3; 20 | int ints = 13; 21 | 22 | void setup() { 23 | size(700, 600); 24 | background(0, 0, 255); 25 | translate(150, 100); 26 | stroke(255); 27 | turn_left(l, ints); 28 | turn_right(l, ints); 29 | } 30 | 31 | void turn_right(float l, int ints) { 32 | if (ints == 0) { 33 | line(0, 0, 0, -l); 34 | translate(0, -l); 35 | } else { 36 | turn_left(l, ints-1); 37 | rotate(radians(90)); 38 | turn_right(l, ints-1); 39 | } 40 | } 41 | 42 | void turn_left(float l, int ints) { 43 | if (ints == 0) { 44 | line(0, 0, 0, -l); 45 | translate(0, -l); 46 | } else { 47 | turn_left(l, ints-1); 48 | rotate(radians(-90)); 49 | turn_right(l, ints-1); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /examples/Java/DrawAClock/DrawAClock.pde: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Draw a clock 4 | * https://rosettacode.org/wiki/Draw_a_clock#Processing 5 | * Processing 3.4 6 | * 2019-12-19 Jeremy Douglass 7 | * 8 | * Task: 9 | * 10 | * Draw a clock. 11 | * 12 | * More specific: 13 | * 14 | * Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a 15 | * mouth counting "one thousand and one", anything. Only showing the seconds is 16 | * required, e.g.: a watch with just a second hand will suffice. However, it 17 | * must clearly change every second, and the change must cycle every so often 18 | * (one minute, 30 seconds, etc.) It must be drawn; printing a string of 19 | * numbers to your terminal doesn't qualify. Both text-based and graphical 20 | * drawing are OK. 21 | * 22 | * The clock is unlikely to be used to control space flights, so it needs not 23 | * be hyper-accurate, but it should be usable, meaning if one can read the 24 | * seconds off the clock, it must agree with the system clock. 25 | * A clock is rarely (never?) a major application: don't be a CPU hog and poll 26 | * the system timer every microsecond, use a proper timer/signal/event from your 27 | * system or language instead. For a bad example, many OpenGL programs update 28 | * the frame-buffer in a busy loop even if no redraw is needed, which is very 29 | * undesirable for this task. 30 | * 31 | * A clock is rarely (never?) a major application: try to keep your code simple 32 | * and to the point. Don't write something too elaborate or convoluted, instead 33 | * do whatever is natural, concise and clear in your language. 34 | * 35 | * Key points 36 | * - animate simple object 37 | * - timed event 38 | * - polling system resources 39 | * - code clarity 40 | */ 41 | 42 | // This simple example of an analog wall clock uses the Processing built-in 43 | // time functions second(), minute(), and hour(). For each hand it rotates the 44 | // sketch canvas and then draws a straight line. 45 | 46 | void draw() { 47 | drawClock(); 48 | } 49 | void drawClock() { 50 | background(192); 51 | translate(width/2, height/2); 52 | float s = second() * TWO_PI / 60.0; 53 | float m = minute() * TWO_PI / 60.0; 54 | float h = hour() * TWO_PI / 12.0; 55 | rotate(s); 56 | strokeWeight(1); 57 | line(0, 0, 0, -width*0.5); 58 | rotate(-s+m); 59 | strokeWeight(2); 60 | line(0, 0, 0, -width*0.4); 61 | rotate(-m+h); 62 | strokeWeight(4); 63 | line(0, 0, 0, -width*0.2); 64 | } 65 | 66 | // The sketch redraws at Processing's default 60fps. To redraw the screen only 67 | // when the second hand changes, add a global variable and change draw() as 68 | // follows: 69 | // 70 | // int lastSec = second(); 71 | // void draw() { 72 | // if (lastSec!=second()) { 73 | // drawClock(); 74 | // lastSec=second(); 75 | // } 76 | // } 77 | // 78 | // One of the official Processing language examples is a more graphically 79 | // detailed Clock example: https://processing.org/examples/clock.html 80 | -------------------------------------------------------------------------------- /examples/Java/DrawACuboid/DrawACuboid.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Draw a cuboid 3 | * https://rosettacode.org/wiki/Draw_a_cuboid#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Draw a cuboid with relative dimensions of 2 × 3 × 4. 10 | * 11 | * The cuboid can be represented graphically, or in ASCII art, depending on the 12 | * language capabilities. 13 | * To fulfill the criteria of being a cuboid, three faces must be visible. 14 | * 15 | * Either static or rotational projection is acceptable for this task. 16 | */ 17 | 18 | // A cuboid in Processing is created with box(). It may be styled with stroke, 19 | // fill, and lighting. 20 | 21 | size(500, 500, P3D); 22 | background(0); 23 | // position 24 | translate(width/2, height/2, -width/2); 25 | rotateZ(radians(15)); 26 | rotateY(radians(-30)); 27 | rotateX(radians(-25)); 28 | // optional fill and lighting colors 29 | noStroke(); 30 | fill(192, 255, 192); 31 | pointLight(255, 255, 255, 400, -400, 400); 32 | // draw cuboid 33 | box(200, 300, 400); 34 | -------------------------------------------------------------------------------- /examples/Java/DrawAPixel/DrawAPixel.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Draw a pixel 3 | * https://rosettacode.org/wiki/Draw_a_pixel#Processing 4 | * Processing 3.4 5 | * 2020-03, 2019-12 Jeremy Douglass 6 | * 2019-04-21 Israel77 7 | * 8 | * Task: 9 | * 10 | * Create a window and draw a pixel in it, subject to the following: 11 | * 1. the window is 320 x 240 12 | * 2. the color of the pixel must be red (255,0,0) 13 | * 3. the position of the pixel is x = 100, y = 100 14 | */ 15 | 16 | // A static-mode sketch setting one pixel on the canvas pixels array: 17 | 18 | size(320, 240); 19 | set(100, 100, color(255,0,0)); 20 | 21 | 22 | /** 23 | * The same sketch in active mode sketch is: 24 | * 25 | * void setup() { 26 | * size(320, 240); 27 | * set(100, 100, color(255,0,0)); 28 | * } 29 | */ 30 | 31 | 32 | /** 33 | * Or a pixel can be manipulated through loading and modifying the pixels array. 34 | * The formula to access a pixel is x + y * image width. 35 | * 36 | * void setup() { 37 | * size(320, 240); 38 | * loadPixels(); 39 | * pixels[width*100 + 100] = color(255,0,0); 40 | * updatePixels(); 41 | * } 42 | */ 43 | 44 | 45 | /** 46 | * Processing can also draw a dot on the canvas using the `point()` command. 47 | * This will also draw a dot on the canvas... 48 | * 49 | * size(320, 240); 50 | * stroke(color(255,0,0)); 51 | * point(100, 100); 52 | * 53 | * ...however, whether a point corresponds to a single pixel on the screen 54 | * may depend on device-specific factors such as `pixelDensity()`, 55 | * render features such as 2D / 3D mode or `smooth()`, or style settings 56 | * such as `strokeWidth()` or `strokeCap()`. 57 | */ 58 | -------------------------------------------------------------------------------- /examples/Java/DrawARotatingCube/DrawARotatingCube.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Draw a rotating cube 3 | * https://rosettacode.org/wiki/Draw_a_rotating_cube#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Draw a rotating cube. 10 | * 11 | * It should be oriented with one vertex pointing straight up, and its opposite 12 | * vertex on the main diagonal (the one farthest away) straight down. It can be 13 | * solid or wire-frame, and you can use ASCII art if your language doesn't have 14 | * graphical capabilities. Perspective is optional. 15 | */ 16 | 17 | // Create a cube in Processing with box(), rotate the scene with rotate(), 18 | // and drive rotation with either the built-in millis() or frameCount timers. 19 | 20 | void setup() { 21 | size(500, 500, P3D); 22 | } 23 | void draw() { 24 | background(0); 25 | // position 26 | translate(width/2, height/2, -width/2); 27 | // optional fill and lighting colors 28 | noStroke(); 29 | strokeWeight(4); 30 | fill(192, 255, 192); 31 | pointLight(255, 255, 255, 0, -500, 500); 32 | // rotation driven by built-in timer 33 | rotateY(millis()/1000.0); 34 | // rotateY(frameCount/60.0); 35 | // draw box 36 | box(300, 300, 300); 37 | } 38 | -------------------------------------------------------------------------------- /examples/Java/DrawASphere/DrawASphere.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Draw a sphere 3 | * https://rosettacode.org/wiki/Draw_a_sphere#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 2013-08-16 Atkindel 7 | * 8 | * Task: 9 | * 10 | * Draw a sphere. 11 | * 12 | * The sphere can be represented graphically, or in ASCII art, 13 | * depending on the language capabilities. 14 | * 15 | * Either static or rotational projection is acceptable for this task. 16 | */ 17 | 18 | // 3D rendering is built into Processing. 19 | 20 | void setup() { 21 | size(500, 500, P3D); 22 | } 23 | void draw() { 24 | background(192); 25 | translate(width/2, height/2); 26 | // optional color and lighting style 27 | stroke(200); 28 | fill(255); 29 | lights(); 30 | // draw sphere 31 | sphere(200); 32 | } 33 | -------------------------------------------------------------------------------- /examples/Java/EmptyProgram/EmptyProgram.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * EmptyProgram 3 | * http://rosettacode.org/wiki/Empty_program#Processing 4 | * Processing 3.4 5 | * 2020-03-04‎ Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Create the simplest possible program that is still considered "correct." 10 | */ 11 | 12 | // An empty or comments-only .pde sketch file. 13 | // When run this will produce a 200x200 inactive default gray canvas. 14 | -------------------------------------------------------------------------------- /examples/Java/EvenOrOdd/EvenOrOdd.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * EvenOrOdd 3 | * https://rosettacode.org/wiki/Even_or_odd#Processing 4 | * Processing 3.5.4 5 | * 2020-02-25 Dawit Ghebrehiwet 6 | * 2017-09-05 CerealKiller 7 | * 8 | * Task: 9 | * 10 | * Test whether an integer is even or odd. 11 | * 12 | * There is more than one way to solve this task: 13 | * 14 | * Use the even and odd predicates, if the language provides them. 15 | * Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. 16 | * Divide i by 2. The remainder equals 0 iff i is even. The remainder equals +1 or -1 iff i is odd. 17 | * Use modular congruences: 18 | * i ≡ 0 (mod 2) iff i is even. 19 | * i ≡ 1 (mod 2) iff i is odd. 20 | * 21 | * Note: 22 | * 23 | * Added examples. 24 | * 25 | * 10 numbers between -100 and 100 are generated. For each one the functions isEven and isOdd are called to see if the number is even or odd. The result is printed to the console. 26 | * 27 | * Example result on the console. 28 | * 29 | * 1. 83 isEven: false - isOdd: true 30 | * 2. -17 isEven: false - isOdd: false 31 | * 3. -5 isEven: false - isOdd: false 32 | * 4. 11 isEven: false - isOdd: true 33 | * 5. -38 isEven: true - isOdd: false 34 | * 6. -22 isEven: true - isOdd: false 35 | * 7. 7 isEven: false - isOdd: true 36 | * 8. 38 isEven: true - isOdd: false 37 | * 9. -44 isEven: true - isOdd: false 38 | * 10. 0 isEven: true - isOdd: false 39 | * 40 | */ 41 | 42 | void setup(){ 43 | println("EvenOrOdd"); 44 | 45 | for (int i=1; i <= 10; i++){ 46 | int n = (int) random(-100, 100); 47 | 48 | println("* " + i + ". " + n + " isEven: " + isEven(n) + " - isOdd: " + isOdd(n)); 49 | } 50 | } 51 | 52 | boolean isEven(int i){ 53 | return i%2 == 0; 54 | } 55 | 56 | boolean isOdd(int i){ 57 | return i%2 == 1; 58 | } 59 | -------------------------------------------------------------------------------- /examples/Java/Factorial/Factorial.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Factorial 3 | * https://rosettacode.org/wiki/Factorial#Processing 4 | * Processing 3.5.4 5 | * 2020-02-26 Dawit Ghebrehiwet (iterative approach) 6 | * 2018-05-29 Wester Iii (recursive approach) 7 | * 8 | * Definitions 9 | * The factorial of 0 (zero) is defined as being 1 (unity). 10 | * The Factorial Function of a positive integer, n, is defined as the product of the sequence: n, n-1, n-2, ... 1 11 | * 12 | * Task: 13 | * 14 | * Write a function to return the factorial of a number. 15 | * 16 | * Solutions can be iterative or recursive. 17 | * 18 | * Support for trapping negative n errors is optional. 19 | * 20 | * Note: 21 | * 22 | * fr implements the recursive approach 23 | * 24 | * fi implements the iterative approach 25 | * 26 | * Factorials of negative numbers return -1 as an error code. 27 | * 28 | * Examples: 29 | * 30 | * Generate 10 random numbers between -5 and 20 calcualate the factorial with the recursive approach and the iterative apporach. 31 | * 32 | * A note on choosing between int and long for the calculation of factorials: as stated in https://processing.org/reference/int.html the maximum number which can be stored as an interger is 2,147,483,647. So 12! = 479,001,600 is the largest factorial wich can be stored as an integer variable. 13! = 6,227,020,800 already exceeds that boundary. In order to calculate bigger factorials the data type of the variables was set to long (https://processing.org/reference/long.html) wich allows numbers up to 9,223,372,036,854,775,807. 20! = 2,432,902,008,176,640,000 is the largest factorial which can be stored as a long variable. 21! = 51,090,942,171,709,440,000 exceeds the boundary again. To keep this example simple the data type of the result was left at long. 33 | * 34 | * Example output: 35 | * 36 | * Factorial 37 | * fr = recursive approach 38 | * fi = iterative approach 39 | * 1. 12 fr(12) = 479001600 fi(12) = 479001600 40 | * 2. 19 fr(19) = 121645100408832000 fi(19) = 121645100408832000 41 | * 3. 1 fr(1) = 1 fi(1) = 1 42 | * 4. 4 fr(4) = 24 fi(4) = 24 43 | * 5. 16 fr(16) = 20922789888000 fi(16) = 20922789888000 44 | * 6. 16 fr(16) = 20922789888000 fi(16) = 20922789888000 45 | * 7. 0 fr(0) = 1 fi(0) = 1 46 | * 8. 10 fr(10) = 3628800 fi(10) = 3628800 47 | * 9. -3 fr(-3) is not defined fi(-3) is not defined 48 | * 10. 19 fr(19) = 121645100408832000 fi(19) = 121645100408832000 49 | * 50 | */ 51 | 52 | void setup(){ 53 | println("* Factorial"); 54 | println("* fr = recursive approach"); 55 | println("* fi = iterative approach"); 56 | 57 | for (int i=1; i <= 10; i++){ 58 | int n = (int) random(-5, 20); 59 | 60 | long rr = fr(n); 61 | 62 | long ri = fi(n); 63 | 64 | print("* " + i + ". " + n); 65 | 66 | if (rr == -1){ 67 | print(" fr(" + n +") is not defined"); 68 | } else { 69 | print(" fr(" + n +") = " + rr); 70 | } 71 | 72 | if (ri == -1){ 73 | print(" fi(" + n +") is not defined"); 74 | } else { 75 | print(" fi(" + n +") = " + ri); 76 | } 77 | 78 | println(); 79 | } 80 | } 81 | 82 | long fr(int n) { 83 | if (n < 0){ 84 | return -1; 85 | } 86 | 87 | if (n == 0){ 88 | return 1; 89 | } else { 90 | return n * fr(n-1); 91 | } 92 | } 93 | 94 | long fi(int n) { 95 | if (n < 0){ 96 | return -1; 97 | } 98 | 99 | if (n == 0){ 100 | return 1; 101 | } else { 102 | long r = 1; 103 | 104 | for (long i = 1; i <= n; i++){ 105 | r = r * i; 106 | } 107 | 108 | return r; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /examples/Java/FizzBuzz/FizzBuzz.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * FizzBuzz: Console 3 | * https://rosettacode.org/wiki/FizzBuzz#Processing 4 | * Processing 3.4 5 | * 2019-12 Jeremy Douglass 6 | * 2015-12-09 Jsheradin "Console Only, Straightforward" 7 | * 8 | * Task: 9 | * 10 | * Write a program that prints the integers from 1 to 100 (inclusive). 11 | * But: 12 | * - for multiples of three, print Fizz (instead of the number) 13 | * - for multiples of five, print Buzz (instead of the number) 14 | * - for multiples of both three and five, print FizzBuzz (instead of the number) 15 | * The FizzBuzz problem was presented as the lowest level of comprehension required' 16 | * to illustrate adequacy. 17 | */ 18 | 19 | for (int i = 1; i <= 100; i++) { 20 | if (i % 3 == 0) { 21 | print("Fizz"); 22 | } 23 | if (i % 5 == 0) { 24 | print("Buzz"); 25 | } 26 | if (i % 3 != 0 && i % 5 != 0) { 27 | print(i); 28 | } 29 | print("\n"); 30 | } 31 | -------------------------------------------------------------------------------- /examples/Java/FizzBuzz_Futureproof/FizzBuzz_Futureproof.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * FizzBuzz: Console, FutureProof 3 | * https://rosettacode.org/wiki/FizzBuzz#Processing 4 | * Processing 3.4 5 | * 2019-12 Jeremy Douglass 6 | * 2018-12-06 Wester Iii "Console Only, Futureproof" 7 | * 8 | * Task: 9 | * 10 | * Write a program that prints the integers from 1 to 100 (inclusive). 11 | * But: 12 | * - for multiples of three, print Fizz (instead of the number) 13 | * - for multiples of five, print Buzz (instead of the number) 14 | * - for multiples of both three and five, print FizzBuzz (instead of the number) 15 | * The FizzBuzz problem was presented as the lowest level of comprehension required' 16 | * to illustrate adequacy. 17 | */ 18 | 19 | for (int i = 1; i <= 100; i++) { 20 | String output = ""; 21 | 22 | if (i % 3 == 0) output += "Fizz"; 23 | if (i % 5 == 0) output += "Buzz"; 24 | // copy & paste above line to add more tests 25 | 26 | if (output == "") output = str(i); 27 | println(output); 28 | } 29 | -------------------------------------------------------------------------------- /examples/Java/FizzBuzz_Viz/FizzBuzz_Viz.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * FizzBuzz: Console and Visualization 3 | * https://rosettacode.org/wiki/FizzBuzz#Processing 4 | * Processing 3.4 5 | * 2019-12 Jeremy Douglass 6 | * 7 | * 2014-01-09 Phospheros "Visualization & Console, Straightforward" 8 | * 9 | * Task: 10 | * 11 | * Write a program that prints the integers from 1 to 100 (inclusive). 12 | * But: 13 | * - for multiples of three, print Fizz (instead of the number) 14 | * - for multiples of five, print Buzz (instead of the number) 15 | * - for multiples of both three and five, print FizzBuzz (instead of the number) 16 | * The FizzBuzz problem was presented as the lowest level of comprehension required' 17 | * to illustrate adequacy. 18 | */ 19 | 20 | // Reserved variable "width" in Processing is 100 pixels by default, 21 | // suitable for this FizzBuzz exercise. 22 | // Accordingly, range is pixel index from 0 to 99. 23 | 24 | for (int i = 0; i < width; i++) { 25 | if (i % 3 == 0 && i % 5 == 0) { 26 | stroke(255, 255, 0); 27 | println("FizzBuzz!"); 28 | } else if (i % 5 == 0) { 29 | stroke(0, 255, 0); 30 | println("Buzz"); 31 | } else if (i % 3 == 0) { 32 | stroke(255, 0, 0); 33 | println("Fizz"); 34 | } else { 35 | stroke(0, 0, 255); 36 | println(i); 37 | } 38 | line(i, 0, i, height); 39 | } 40 | -------------------------------------------------------------------------------- /examples/Java/FizzBuzz_VizTernary/FizzBuzz_VizTernary.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * FizzBuzz: Console and Visualization, Ternary 3 | * https://rosettacode.org/wiki/FizzBuzz#Processing 4 | * Processing 3.4 5 | * 2019-12 Jeremy Douglass 6 | * 2014-01-09 Phospheros "Visualization & Console, Ternary" 7 | * 8 | * Task: 9 | * 10 | * Write a program that prints the integers from 1 to 100 (inclusive). 11 | * But: 12 | * - for multiples of three, print Fizz (instead of the number) 13 | * - for multiples of five, print Buzz (instead of the number) 14 | * - for multiples of both three and five, print FizzBuzz (instead of the number) 15 | * The FizzBuzz problem was presented as the lowest level of comprehension required' 16 | * to illustrate adequacy. 17 | */ 18 | 19 | // Reserved variable "width" in Processing is 100 pixels by default, 20 | // suitable for this FizzBuzz exercise. 21 | // Accordingly, range is pixel index from 0 to 99. 22 | 23 | for (int i = 0; i < width; i++) { 24 | stroke((i % 5 == 0 && i % 3 == 0) ? #FFFF00 : (i % 5 == 0) ? #00FF00 : (i % 3 == 0) ? #FF0000 : #0000FF); 25 | line(i, 0, i, height); 26 | println((i % 5 == 0 && i % 3 == 0) ? "FizzBuzz!" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i); 27 | } 28 | -------------------------------------------------------------------------------- /examples/Java/FractalTree_Calculation/FractalTree_Calculation.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * FractalTree -- Calculating coordinates 3 | * https://rosettacode.org/wiki/Fractal_tree#Processing 4 | * Processing 3.4 5 | * 2020-03-18 Alexandre Villares 6 | * 7 | * Task: 8 | * 9 | * Generate and draw a fractal tree. 10 | * 11 | * 1. Draw the trunk 12 | * 2. At the end of the trunk, split by some angle and draw two branches 13 | * 3. Repeat at the end of each branch until a sufficient level of branching is reached 14 | */ 15 | 16 | // Calculating the coordinates of each branch 17 | 18 | void setup() { 19 | size(600, 600); 20 | background(0); 21 | stroke(255); 22 | drawTree(300, 550, -90, 9); 23 | } 24 | 25 | void drawTree(float x1, float y1, float angle, int depth) { 26 | float forkAngle = 20; 27 | float baseLen = 10.0; 28 | if (depth > 0) { 29 | float x2 = x1 + cos(radians(angle)) * depth * baseLen; 30 | float y2 = y1 + sin(radians(angle)) * depth * baseLen; 31 | line(x1, y1, x2, y2); 32 | drawTree(x2, y2, angle - forkAngle, depth - 1); 33 | drawTree(x2, y2, angle + forkAngle, depth - 1); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /examples/Java/FractalTree_Rotation/FractalTree_Rotation.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * FractalTree -- Using rotation 3 | * https://rosettacode.org/wiki/Fractal_tree#Processing 4 | * Processing 3.4 5 | * 2020-03-18 Alexandre Villares 6 | * 7 | * Task: 8 | * 9 | * Generate and draw a fractal tree. 10 | * 11 | * 1. Draw the trunk 12 | * 2. At the end of the trunk, split by some angle and draw two branches 13 | * 3. Repeat at the end of each branch until a sufficient level of branching is reached 14 | */ 15 | 16 | // Using Processing's pushMatrix(), popMatrix() and rotate() 17 | 18 | void setup() { 19 | size(600, 600); 20 | background(0); 21 | stroke(255); 22 | drawTree(300, 550, 9); 23 | } 24 | 25 | void drawTree(float x, float y, int depth) { 26 | float forkAngle = radians(20); 27 | float baseLen = 10.0; 28 | if (depth > 0) { 29 | pushMatrix(); 30 | translate(x, y - baseLen * depth); 31 | line(0, baseLen * depth, 0, 0); 32 | rotate(forkAngle); 33 | drawTree(0, 0, depth - 1); 34 | rotate(2 * -forkAngle); 35 | drawTree(0, 0, depth - 1); 36 | popMatrix(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /examples/Java/GameOfLife/GameOfLife.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Game of Life 3 | * https://rosettacode.org/wiki/Conway%27s_Game_of_Life#ProcessingProcessing 3.4 4 | * 2020-03 Alexandre Villares 5 | * 2020-03 Jeremy Douglass 6 | * 7 | * The Game of Life is a cellular automaton devised by the British mathematician 8 | * John Horton Conway in 1970. It is the best-known example of a cellular automaton. 9 | * 10 | * Task: 11 | * 12 | * Although you should test your implementation on more complex examples 13 | * such as the glider in a larger universe, show the action of the blinker 14 | * (three adjoining cells in a row all alive), over three generations, 15 | * in a 3 by 3 grid. 16 | */ 17 | 18 | boolean play = true; 19 | int cellSize = 10; 20 | int cols, rows; 21 | int lastCell = 0; 22 | int sample = 10; 23 | // Game of life board 24 | int[][] grid; 25 | 26 | void setup() { 27 | size(800, 500); 28 | noStroke(); 29 | // Calculate cols, rows and init array 30 | cols = width/cellSize; 31 | rows = height/cellSize; 32 | grid = new int[cols][rows]; 33 | init(-1); // randomized start 34 | 35 | println("Press 'space' to start/stop"); 36 | println("'e' to clear all cells"); 37 | println("'b' demonstrate 'blinker'"); 38 | println("'g' demonstrate glider"); 39 | println("'r' to randomize grid"); 40 | println("'+' and '-' to change speed"); 41 | 42 | } 43 | 44 | void draw() { 45 | background(0); 46 | 47 | for ( int i = 0; i < cols; i++) { 48 | for ( int j = 0; j < rows; j++) { 49 | if ((grid[i][j] == 1)) fill(255); 50 | else fill(0); 51 | rect(i*cellSize, j*cellSize, cellSize, cellSize); 52 | } 53 | } 54 | if (play && frameCount%sample==0 && !mousePressed) { 55 | generate(); 56 | } 57 | } 58 | 59 | void generate() { 60 | int[][] nextGrid = new int[cols][rows]; 61 | for (int x = 0; x < cols; x++) { 62 | for (int y = 0; y < rows; y++) { 63 | int ngbs = countNgbs(x, y); 64 | // the classic Conway rules 65 | if ((grid[x][y] == 1) && (ngbs < 2)) nextGrid[x][y] = 0; // solitude 66 | else if ((grid[x][y] == 1) && (ngbs > 3)) nextGrid[x][y] = 0; // crowded 67 | else if ((grid[x][y] == 0) && (ngbs == 3)) nextGrid[x][y] = 1; // cell born 68 | else nextGrid[x][y] = grid[x][y]; // keep 69 | } 70 | } 71 | grid = nextGrid; 72 | } 73 | 74 | int countNgbs(int x, int y) { 75 | int ngbCount = 0; 76 | for (int i = -1; i <= 1; i++) { 77 | for (int j = -1; j <= 1; j++) { 78 | // 'united' borders 79 | ngbCount += grid[(x+i+cols)%cols][(y+j+rows)%rows]; 80 | } 81 | } 82 | // cell taken out of count 83 | ngbCount -= grid[x][y]; 84 | return ngbCount; 85 | } 86 | 87 | void init(int option) { 88 | int state; 89 | for (int x = 0; x < cols; x++) { 90 | for (int y = 0; y < rows; y++) { 91 | if (option == -1) { 92 | state = int(random(2)); 93 | } else { 94 | state = option; 95 | } 96 | grid[x][y] = state; 97 | } 98 | } 99 | } 100 | 101 | void keyReleased() { 102 | if (key == 'r') { 103 | init(-1); // randomize grid 104 | } 105 | if (key == 'e') { 106 | init(0); // empty grid 107 | } 108 | if (key == 'g') { 109 | int glider[][] = { 110 | {0, 1, 0}, 111 | {0, 0, 1}, 112 | {1, 1, 1}}; 113 | setNine(10, 10, glider); 114 | } 115 | if (key == 'b') { 116 | int blinker[][] = { 117 | {0, 1, 0}, 118 | {0, 1, 0}, 119 | {0, 1, 0}}; 120 | setNine(10, 10, blinker); 121 | } 122 | if (key == ' ') { 123 | play = !play; 124 | } 125 | if (key == '+' || key == '=') { 126 | sample=max(sample-1, 1); 127 | } 128 | if (key == '-') { 129 | sample++; 130 | } 131 | } 132 | 133 | void setNine(int x, int y, int nine[][]) { 134 | for (int i = 0; i <= 2; i++) { 135 | for (int j = 0; j <= 2; j++) { 136 | grid[(x+i+cols)%cols][(y+j+rows)%rows] = nine[i][j]; 137 | } 138 | } 139 | } 140 | 141 | void mousePressed() { 142 | paint(); 143 | } 144 | void mouseDragged() { 145 | paint(); 146 | } 147 | 148 | void paint() { 149 | int x = mouseX/cellSize; 150 | int y = mouseY/cellSize; 151 | int p = y*cols + x; 152 | if (p!=lastCell) { 153 | lastCell=p; 154 | int states[] = {1, 0}; 155 | grid[x][y] = states[grid[x][y]]; // invert 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /examples/Java/HelloWorld/HelloWorld.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * HelloWorldText 3 | * https://www.rosettacode.org/wiki/Hello_world/Text#Processing 4 | * Processing 3.4 5 | * 2016-04-08‎ Edmund 6 | * 7 | * Task: 8 | * 9 | * Display the string Hello world! on a text console. 10 | */ 11 | 12 | println("Hello world!"); 13 | -------------------------------------------------------------------------------- /examples/Java/HilbertCurve/HilbertCurve.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Hilbert Curve 3 | * https://www.rosettacode.org/wiki/Hilbert_curve#Processing 4 | * Processing 3.4 5 | * 2020-03 Alexandre Villares 6 | * 7 | * Task: 8 | * 9 | * Produce a graphical or ASCII-art representation of a 10 | * Hilbert curve of at least order 3. 11 | * https://en.wikipedia.org/wiki/Hilbert_curve 12 | */ 13 | 14 | // L-System based implementation of Hilbert Curve 15 | 16 | int iterations = 7; 17 | float strokeLen = 600; 18 | int angleDeg = 90; 19 | String axiom = "L"; 20 | StringDict rules = new StringDict(); 21 | String sentence = axiom; 22 | int xo, yo; 23 | 24 | void setup() { 25 | size(700, 700); 26 | xo= 50; 27 | yo = height - 50; 28 | strokeWeight(1); 29 | noFill(); 30 | 31 | rules.set("L", "+RF-LFL-FR+"); 32 | rules.set("R", "-LF+RFR+FL-"); 33 | 34 | generate(iterations); 35 | } 36 | 37 | void draw() { 38 | background(0); 39 | translate(xo, yo); 40 | plot(radians(angleDeg)); 41 | } 42 | 43 | void generate(int n) { 44 | for (int i=0; i < n; i++) { 45 | strokeLen *= 0.5; 46 | String nextSentence = ""; 47 | for (int j=0; j < sentence.length(); j++) { 48 | char c = sentence.charAt(j); 49 | String ruleResult = rules.get(str(c), str(c)); 50 | nextSentence += ruleResult; 51 | } 52 | sentence = nextSentence; 53 | } 54 | } 55 | 56 | void plot(float angle) { 57 | for (int i=0; i < sentence.length(); i++) { 58 | char c = sentence.charAt(i); 59 | if (c == 'F') { 60 | stroke(255); 61 | line(0, 0, 0, -strokeLen); 62 | translate(0, -strokeLen); 63 | } else if (c == '+') { 64 | rotate(angle); 65 | } else if (c == '-') { 66 | rotate(-angle); 67 | } 68 | } 69 | } 70 | 71 | void keyPressed() { 72 | if (key == '-') { 73 | angleDeg -= 1; 74 | println("Angle: " + angleDeg); 75 | } 76 | if (key == '=' || key == '+') { 77 | angleDeg += 1; 78 | println("Angle: " + angleDeg); 79 | } 80 | if (key == 'a') { 81 | strokeLen *= 2; 82 | } 83 | if (key == 'z') { 84 | strokeLen /= 2; 85 | } 86 | if (keyCode == LEFT) { 87 | xo -= 25; 88 | } 89 | if (keyCode == RIGHT) { 90 | xo += 25; 91 | } 92 | if (keyCode == UP) { 93 | yo -= 25; 94 | } 95 | if (keyCode == DOWN) { 96 | yo += 25; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /examples/Java/ImageNoise/ImageNoise.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * ImageNoise 3 | * https://rosettacode.org/wiki/Image_noise#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Generate a random black and white 320x240 image continuously, showing FPS 10 | * (frames per second). 11 | */ 12 | 13 | color black = color(0); 14 | color white = color(255); 15 | 16 | void setup() { 17 | size(320, 240); 18 | // frameRate(300); // 60 by default 19 | } 20 | 21 | void draw() { 22 | loadPixels(); 23 | for (int i=0; i0, find out which prisoner will be the final survivor. 23 | * 24 | * In one such incident, there were 41 prisoners and every 3rd prisoner was 25 | * being killed (k=3). 26 | * 27 | * Among them was a clever chap name Josephus who worked out the problem, stood 28 | * at the surviving position, and lived on to tell the tale. 29 | * 30 | * Which number was he? 31 | */ 32 | 33 | void setup() { 34 | println("Survivor: " + execute(41, 3)); 35 | println("Survivors: " + executeAllButM(41, 3, 3)); 36 | } 37 | 38 | int execute(int n, int k) { 39 | int killIdx = 0; 40 | IntList prisoners = new IntList(n); 41 | for (int i = 0; i < n; i++) { 42 | prisoners.append(i); 43 | } 44 | println("Prisoners executed in order:"); 45 | while (prisoners.size() > 1) { 46 | killIdx = (killIdx + k - 1) % prisoners.size(); 47 | print(prisoners.get(killIdx) + " "); 48 | prisoners.remove(killIdx); 49 | } 50 | println(); 51 | return prisoners.get(0); 52 | } 53 | 54 | IntList executeAllButM(int n, int k, int m) { 55 | int killIdx = 0; 56 | IntList prisoners = new IntList(n); 57 | for (int i = 0; i < n; i++) { 58 | prisoners.append(i); 59 | } 60 | println("Prisoners executed in order:"); 61 | while (prisoners.size() > m) { 62 | killIdx = (killIdx + k - 1) % prisoners.size(); 63 | print(prisoners.get(killIdx) + " "); 64 | prisoners.remove(killIdx); 65 | } 66 | println(); 67 | return prisoners; 68 | } 69 | 70 | /** 71 | * OUTPUT 72 | * 73 | * Prisoners executed in order: 74 | * 2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36 40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 34 15 75 | * Survivor: 30 76 | * Prisoners executed in order: 77 | * 2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36 40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 78 | * Survivors: IntList size=3 [ 15, 30, 34 ] 79 | * 80 | */ 81 | -------------------------------------------------------------------------------- /examples/Java/JuliaSet/JuliaSet.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * JuliaSet 3 | * https://rosettacode.org/wiki/Julia_set#Processing 4 | * Processing 3.4 5 | * 2016-05 Daniel Suteu (Trizen) 6 | * 7 | * Task: 8 | * 9 | * Generate and draw a Julia set. 10 | * https://en.wikipedia.org/wiki/Julia_set 11 | */ 12 | 13 | float cX = -0.7; 14 | float cY = 0.27015; 15 | float zx, zy; 16 | float maxIter = 300; 17 | 18 | void setup() { 19 | size(640, 480); 20 | } 21 | 22 | void draw() { 23 | for (int x = 0; x < width; x++) { 24 | for (int y = 0; y < height; y++) { 25 | zx = 1.5 * (x - width / 2) / (0.5 * width); 26 | zy = (y - height / 2) / (0.5 * height); 27 | float i = maxIter; 28 | while (zx * zx + zy * zy < 4 && i > 0) { 29 | float tmp = zx * zx - zy * zy + cX; 30 | zy = 2.0 * zx * zy + cY; 31 | zx = tmp; 32 | i -= 1; 33 | } 34 | colorMode(HSB); 35 | color c = color(i / maxIter * 255, 255, i > 1 ? 255 : 0); 36 | set(x, y, c); 37 | } 38 | } 39 | noLoop(); 40 | } 41 | -------------------------------------------------------------------------------- /examples/Java/KochCurve/KochCurve.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Koch Curve 3 | * https://www.rosettacode.org/wiki/Koch_curve#Processing 4 | * Processing 3.4 5 | * 2020-02-26 Noel 6 | * 2020-03-03 Jeremy Douglass 7 | * 8 | * Task: 9 | * 10 | * Draw a Koch curve. See details: https://en.wikipedia.org/wiki/Koch_snowflake 11 | */ 12 | 13 | int l = 300; 14 | 15 | void setup() { 16 | size(400, 400); 17 | background(0, 0, 255); 18 | stroke(255); 19 | // draw from center of screen 20 | translate(width/2.0, height/2.0); 21 | // center curve from lower-left corner of base equilateral triangle 22 | translate(-l/2.0, l*sqrt(3)/6.0); 23 | for (int i = 1; i <= 3; i++) { 24 | kcurve(0, l); 25 | rotate(radians(120)); 26 | translate(-l, 0); 27 | } 28 | } 29 | 30 | void kcurve(float x1, float x2) { 31 | float s = (x2-x1)/3; 32 | if (s < 5) { 33 | pushMatrix(); 34 | translate(x1, 0); 35 | line(0, 0, s, 0); 36 | line(2*s, 0, 3*s, 0); 37 | translate(s, 0); 38 | rotate(radians(60)); 39 | line(0, 0, s, 0); 40 | translate(s, 0); 41 | rotate(radians(-120)); 42 | line(0, 0, s, 0); 43 | popMatrix(); 44 | return; 45 | } 46 | pushMatrix(); 47 | translate(x1, 0); 48 | kcurve(0, s); 49 | kcurve(2*s, 3*s); 50 | translate(s, 0); 51 | rotate(radians(60)); 52 | kcurve(0, s); 53 | translate(s, 0); 54 | rotate(radians(-120)); 55 | kcurve(0, s); 56 | popMatrix(); 57 | } 58 | -------------------------------------------------------------------------------- /examples/Java/LevenshteinDistance/LevenshteinDistance.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * LevenshteinDistance 3 | * https://rosettacode.org/wiki/Levenshtein_distance#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * In information theory and computer science, the Levenshtein distance is a 8 | * metric for measuring the amount of difference between two sequences (i.e. an 9 | * edit distance). The Levenshtein distance between two strings is defined as 10 | * the minimum number of edits needed to transform one string into the other, 11 | * with the allowable edit operations being insertion, deletion, or 12 | * substitution of a single character. 13 | * 14 | * Example The Levenshtein distance between "kitten" and "sitting" is 3, since 15 | * the following three edits change one into the other, and there isn't a way 16 | * to so it with fewer than three edits: 17 | * 18 | * kitten sitten (substitution of 'k' with 's') sitten sittin (substitution of 19 | * 'e' with 'i') sittin sitting (insert 'g' at the end). 20 | * 21 | * The Levenshtein distance between "rosettacode", "raisethysword" is 8. 22 | * 23 | * The distance between two strings is same as that when both strings are 24 | * reversed. 25 | * 26 | * Task: 27 | * 28 | * Implements a Levenshtein distance function, or uses a library function, to 29 | * show the Levenshtein distance between "kitten" and "sitting". 30 | */ 31 | 32 | void setup() { 33 | println(distance("kitten", "sitting")); 34 | } 35 | 36 | int distance(String a, String b) { 37 | int [] costs = new int [b.length() + 1]; 38 | for (int j = 0; j < costs.length; j++) 39 | costs[j] = j; 40 | for (int i = 1; i <= a.length(); i++) { 41 | costs[0] = i; 42 | int nw = i - 1; 43 | for (int j = 1; j <= b.length(); j++) { 44 | int cj = min(1 + min(costs[j], costs[j - 1]), a.charAt(i - 1) == b.charAt(j - 1) ? nw : nw + 1); 45 | nw = costs[j]; 46 | costs[j] = cj; 47 | } 48 | } 49 | return costs[b.length()]; 50 | } 51 | 52 | /** 53 | * OUTPUT 54 | * 3 55 | */ 56 | -------------------------------------------------------------------------------- /examples/Java/MandelbrotSet/MandelbrotSet.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * MandelbrotSet 3 | * https://rosettacode.org/wiki/Mandelbrot_set#Processing 4 | * Processing 3.4 5 | * 2017-09-23 Noel 6 | * 7 | * Task: 8 | * 9 | * Generate and draw the Mandelbrot set. 10 | * 11 | * Note that there are many algorithms to draw Mandelbrot set 12 | * and there are many functions which generate it . 13 | */ 14 | 15 | // Click on an area to zoom in. 16 | // Choose areas with multiple colors for interesting zooming. 17 | 18 | double x, y, zr, zi, zr2, zi2, cr, ci, n; 19 | double zmx1, zmx2, zmy1, zmy2, f, di, dj; 20 | double fn1, fn2, fn3, re, gr, bl, xt, yt, i, j; 21 | 22 | void setup() { 23 | size(500, 500); 24 | di = 0; 25 | dj = 0; 26 | f = 10; 27 | fn1 = random(20); 28 | fn2 = random(20); 29 | fn3 = random(20); 30 | zmx1 = int(width / 4); 31 | zmx2 = 2; 32 | zmy1 = int(height / 4); 33 | zmy2 = 2; 34 | } 35 | 36 | void draw() { 37 | if (i <= width) i++; 38 | x = (i + di)/ zmx1 - zmx2; 39 | for ( j = 0; j <= height; j++) { 40 | y = zmy2 - (j + dj) / zmy1; 41 | zr = 0; 42 | zi = 0; 43 | zr2 = 0; 44 | zi2 = 0; 45 | cr = x; 46 | ci = y; 47 | n = 1; 48 | while (n < 200 && (zr2 + zi2) < 4) { 49 | zi2 = zi * zi; 50 | zr2 = zr * zr; 51 | zi = 2 * zi * zr + ci; 52 | zr = zr2 - zi2 + cr; 53 | n++; 54 | } 55 | re = (n * fn1) % 255; 56 | gr = (n * fn2) % 255; 57 | bl = (n * fn3) % 255; 58 | stroke((float)re, (float)gr, (float)bl); 59 | point((float)i, (float)j); 60 | } 61 | } 62 | 63 | void mousePressed() { 64 | background(200); 65 | xt = mouseX; 66 | yt = mouseY; 67 | di = di + xt - float(width / 2); 68 | dj = dj + yt - float(height / 2); 69 | zmx1 = zmx1 * f; 70 | zmx2 = zmx2 * (1 / f); 71 | zmy1 = zmy1 * f; 72 | zmy2 = zmy2 * (1 / f); 73 | di = di * f; 74 | dj = dj * f; 75 | i = 0; 76 | j = 0; 77 | } 78 | -------------------------------------------------------------------------------- /examples/Java/MousePosition/MousePosition.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * Mouse position 3 | * https://rosettacode.org/wiki/Mouse_position#Processing 4 | * Processing 3.4 5 | * 2020-04 Alexandre Villares 6 | * 7 | * Task: 8 | * 9 | * Get the current location of the mouse cursor relative to the active window. 10 | */ 11 | 12 | 13 | void setup() { 14 | size(640, 480); 15 | } 16 | 17 | void draw() { 18 | // mouseX and mouseY provide the current mouse position 19 | ellipse(mouseX, mouseY, 5, 5); // graphic output example 20 | println("x:" + mouseX + " y:" + mouseY); 21 | } 22 | -------------------------------------------------------------------------------- /examples/Java/NinetyNineBottles/NinetyNineBottles.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * NinetyNineBottles 3 | * https://rosettacode.org/wiki/99_Bottles_of_Beer#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 2015-12-09 Jsheradin 7 | * 8 | * Task: 9 | * 10 | * Display the complete lyrics for the song: 11 | * 99 Bottles of Beer on the Wall. 12 | * 13 | * The lyrics follow this form: 14 | * 15 | * 99 bottles of beer on the wall 16 | * 99 bottles of beer 17 | * Take one down, pass it around 18 | * 98 bottles of beer on the wall 19 | * 20 | * 98 bottles of beer on the wall 21 | * 98 bottles of beer 22 | * Take one down, pass it around 23 | * 97 bottles of beer on the wall 24 | * 25 | * ... and so on, until reaching 0. 26 | * 27 | * Grammatical support for "1 bottle of beer" is optional. 28 | * 29 | * As with any puzzle, try to do it in as creative/concise/comical 30 | * a way as possible (simple, obvious solutions allowed, too). 31 | */ 32 | 33 | // immediately prints all output to the console 34 | 35 | for (int i = 99; i > 0; i--) { 36 | print(i + " bottles of beer on the wall\n" 37 | + i + " bottles of beer\nTake one down, pass it around\n" 38 | + (i - 1) + " bottles of beer on the wall\n\n"); 39 | } 40 | -------------------------------------------------------------------------------- /examples/Java/NinetyNineBottles_Viz/NinetyNineBottles_Viz.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * NinetyNineBottles, Visual with Animation 3 | * https://rosettacode.org/wiki/99_Bottles_of_Beer#Processing 4 | * Processing 3.4 5 | * 2019-12-19 Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Display the complete lyrics for the song: 10 | * 99 Bottles of Beer on the Wall. 11 | * 12 | * The lyrics follow this form: 13 | * 14 | * 99 bottles of beer on the wall 15 | * 99 bottles of beer 16 | * Take one down, pass it around 17 | * 98 bottles of beer on the wall 18 | * 19 | * 98 bottles of beer on the wall 20 | * 98 bottles of beer 21 | * Take one down, pass it around 22 | * 97 bottles of beer on the wall 23 | * 24 | * ... and so on, until reaching 0. 25 | * 26 | * Grammatical support for "1 bottle of beer" is optional. 27 | * 28 | * As with any puzzle, try to do it in as creative/concise/comical 29 | * a way as possible (simple, obvious solutions allowed, too). 30 | */ 31 | 32 | // This approach uses Processing's draw loop to display text on the sketch 33 | // canvas, with a global counter for bottles--draw() is called at the default 34 | // 60fps, and acts as the for loop. One round of lyrics is displayed at a time, 35 | // and the counter advances by checking Processing's built-in frameCount. 36 | // Lyrics may also be advanced manually by clicking the mouse on the canvas. 37 | 38 | int i = 99; 39 | void setup() { 40 | size(200, 140); 41 | } 42 | void draw() { 43 | background(0); 44 | text(i + " bottles of beer on the wall\n" 45 | + i + " bottles of beer\nTake one down, pass it around\n" 46 | + (i - 1) + " bottles of beer on the wall\n\n", 47 | 10, 20); 48 | if (frameCount%240==239) next(); // auto-advance every 4 secs 49 | } 50 | void mouseReleased() { 51 | next(); // manual advance 52 | } 53 | void next() { 54 | i = max(i-1, 1); // stop decreasing at 1-0 bottles 55 | } 56 | -------------------------------------------------------------------------------- /examples/Java/OneHundredDoors/OneHundredDoors.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * 100 Doors 3 | * http://rosettacode.org/wiki/100_doors#Processing 4 | * Processing 3.4 5 | * 2019-12-10 Jeremy Douglass 6 | * 2015‎-12-11 Jsheradin 7 | * 8 | * There are 100 doors in a row that are all initially closed. 9 | * You make 100 passes by the doors. 10 | * 11 | * The first time through, visit every door and toggle the door 12 | * (if the door is closed, open it; if it is open, close it). 13 | * The second time, only visit every 2nd door (door #2, #4, #6, ...), 14 | * and toggle it. 15 | * The third time, visit every 3rd door (door #3, #6, #9, ...), 16 | * etc, until you only visit the 100th door. 17 | * 18 | * Task: 19 | * 20 | * Answer the question: 21 | * What state are the doors in after the last pass? 22 | * Which are open, which are closed? 23 | */ 24 | 25 | boolean[] doors = new boolean[100]; 26 | 27 | void setup() { 28 | for (int i = 0; i < 100; i++) { 29 | doors[i] = false; 30 | } 31 | for (int i = 1; i < 100; i++) { 32 | for (int j = 0; j < 100; j += i) { 33 | doors[j] = !doors[j]; 34 | } 35 | } 36 | println("Open:"); 37 | for (int i = 1; i < 100; i++) { 38 | if (doors[i]) { 39 | println(i); 40 | } 41 | } 42 | exit(); 43 | } 44 | 45 | /** 46 | * OUTPUT 47 | * 48 | * Open: 49 | * 1 50 | * 4 51 | * 9 52 | * 16 53 | * 25 54 | * 36 55 | * 49 56 | * 64 57 | * 81 58 | */ 59 | -------------------------------------------------------------------------------- /examples/Java/PalindromeDetection/PalindromeDetection.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * PalindromeDetection 3 | * https://rosettacode.org/wiki/Palindrome_detection#Processing 4 | * Processing 3.5.4 5 | * 2020-03-02 da8 6 | * 2018-05-24 Wester Iii 7 | * 8 | * A palindrome is a phrase which reads the same backward and forward. 9 | * 10 | * Task 11 | * 12 | * Write a function or program that checks whether a given sequence of 13 | * characters (or, if you prefer, bytes) is a palindrome. 14 | * 15 | * For extra credit: 16 | * 17 | * Support Unicode characters. 18 | * Write a second function (possibly as a wrapper to the first) which detects 19 | * inexact palindromes, i.e. phrases that are palindromes if white-space and 20 | * punctuation is ignored and case-insensitive comparison is used. 21 | * 22 | * Hints 23 | * It might be useful for this task to know how to reverse a string. 24 | * This task's entries might also form the subjects of the task 25 | * Test a function. 26 | * 27 | * Related tasks 28 | * Word plays 29 | * Ordered words 30 | * Palindrome detection 31 | * Semordnilap 32 | * Anagrams 33 | * Anagrams/Deranged anagrams 34 | * 35 | * Example result on the console. 36 | * 37 | * PalindromeDetection 38 | * 1. 'abcba' isExactPalindrome: true isInexactPalindrome: true 39 | * 2. 'aa' isExactPalindrome: true isInexactPalindrome: true 40 | * 3. 'a' isExactPalindrome: true isInexactPalindrome: true 41 | * 4. '' isExactPalindrome: true isInexactPalindrome: true 42 | * 5. ' ' isExactPalindrome: true isInexactPalindrome: true 43 | * 6. 'ab' isExactPalindrome: false isInexactPalindrome: false 44 | * 7. 'abcdba' isExactPalindrome: false isInexactPalindrome: false 45 | * 8. 'A man, a plan, a canal: Panama!' isExactPalindrome: false isInexactPalindrome: true 46 | * 9. 'Dammit, I’m Mad!' isExactPalindrome: false isInexactPalindrome: true 47 | * 10. 'Never odd or even' isExactPalindrome: false isInexactPalindrome: true 48 | * 11. 'ingirumimusnocteetconsumimurigni' isExactPalindrome: true isInexactPalindrome: true 49 | * 50 | */ 51 | 52 | void setup(){ 53 | println("PalindromeDetection"); 54 | 55 | String[] tests = { 56 | "abcba", 57 | "aa", 58 | "a", 59 | "", 60 | " ", 61 | "ab", 62 | "abcdba", 63 | "A man, a plan, a canal: Panama!", 64 | "Dammit, I’m Mad!", 65 | "Never odd or even", 66 | "ingirumimusnocteetconsumimurigni" 67 | }; 68 | 69 | for (int i = 0; i < tests.length; i++){ 70 | println((i + 1) + ". '" + tests[i] + "' isExactPalindrome: " + isExactPalindrome(tests[i]) + " isInexactPalindrome: " + isInexactPalindrome(tests[i])); 71 | } 72 | } 73 | 74 | /* 75 | * Check for exact palindrome using StringBuilder since String in Java does 76 | * not provide any reverse functionality because Strings are immutable. 77 | */ 78 | boolean isExactPalindrome(String s){ 79 | StringBuilder sb = new StringBuilder(s); 80 | return s.equals(sb.reverse().toString()); 81 | } 82 | 83 | /* 84 | * Check for inexact palindrome disregarding anythiing but alphabet characters. 85 | * Disregards case, whitespace, and non-visible characters. 86 | * Uses the check for exact palindrome above. 87 | */ 88 | boolean isInexactPalindrome(String s){ 89 | return isExactPalindrome(s.replaceAll("\\s+","").replaceAll("[^A-Za-z]+", "").toLowerCase()); 90 | } 91 | -------------------------------------------------------------------------------- /examples/Java/PythagorasTree/PythagorasTree.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * PythagorasTree 3 | * https://rosettacode.org/wiki/Pythagoras_tree#Processing 4 | * Processing 3.5.4 5 | * 2020-03-02 da8 6 | * 2016-06-08 Trizen 7 | * 8 | * Task: 9 | * 10 | * Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). 11 | * 12 | * Related tasks 13 | * 14 | * Fractal tree (https://rosettacode.org/wiki/Fractal_tree) 15 | * 16 | */ 17 | 18 | void setup() { 19 | size(800, 400); 20 | background(255); 21 | stroke(0, 255, 0); 22 | tree(width/2.3, height, width/1.8, height, 10); 23 | } 24 | 25 | void tree(float x1, float y1, float x2, float y2, int depth) { 26 | 27 | if (depth <= 0) { 28 | return; 29 | } 30 | 31 | float dx = (x2 - x1); 32 | float dy = (y1 - y2); 33 | 34 | float x3 = (x2 - dy); 35 | float y3 = (y2 - dx); 36 | float x4 = (x1 - dy); 37 | float y4 = (y1 - dx); 38 | float x5 = (x4 + 0.5*(dx - dy)); 39 | float y5 = (y4 - 0.5*(dx + dy)); 40 | 41 | // square 42 | beginShape(); 43 | fill(0.0, 255.0/depth, 0.0); 44 | vertex(x1, y1); 45 | vertex(x2, y2); 46 | vertex(x3, y3); 47 | vertex(x4, y4); 48 | vertex(x1, y1); 49 | endShape(); 50 | 51 | // triangle 52 | beginShape(); 53 | fill(0.0, 255.0/depth, 0.0); 54 | vertex(x3, y3); 55 | vertex(x4, y4); 56 | vertex(x5, y5); 57 | vertex(x3, y3); 58 | endShape(); 59 | 60 | tree(x4, y4, x5, y5, depth-1); 61 | tree(x5, y5, x3, y3, depth-1); 62 | } 63 | -------------------------------------------------------------------------------- /examples/Java/RenameAFile/RenameAFile.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * RenameAFile 3 | * https://rosettacode.org/wiki/Rename_a_file#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Rename: 10 | * - a file called `input.txt` into `output.txt` and 11 | * - a directory called `docs` into `mydocs`. 12 | * 13 | * This should be done twice: once "here", i.e. in the current working directory 14 | * and once in the filesystem root. 15 | * 16 | * It can be assumed that the user has the rights to do so. (In unix-type 17 | * systems, only the user root would have sufficient permissions in the 18 | * filesystem root.) 19 | * 20 | * Note that sketches will seldom have write permission to root files/folders; 21 | * these root operations should be expected to fail by default. 22 | */ 23 | 24 | void setup() { 25 | // rename local file 26 | boolean sketchfile = rename(sketchPath("input.txt"), sketchPath("output.txt")); 27 | // rename local folder 28 | boolean sketchfold = rename(sketchPath("docs"), sketchPath("mydocs")); 29 | // rename root file (if permitted) 30 | boolean rootfile = rename("input.txt", "output.txt"); 31 | // rename root folder (if permitted) 32 | boolean rootfold = rename("docs", "mydocs"); 33 | 34 | // display results of four operations: true=success, false=fail 35 | println(sketchfile, sketchfold, rootfile, rootfold); 36 | // output: 37 | // true true false false 38 | } 39 | 40 | boolean rename(String oldname, String newname) { 41 | // File (or directory) with old name 42 | File file = new File(oldname); 43 | // File (or directory) with new name 44 | File file2 = new File(newname); 45 | // Rename file (or directory) 46 | boolean success = file.renameTo(file2); 47 | return success; 48 | } 49 | -------------------------------------------------------------------------------- /examples/Java/RenameAFile/docs/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/examples/Java/RenameAFile/docs/.gitkeep -------------------------------------------------------------------------------- /examples/Java/RenameAFile/input.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum -------------------------------------------------------------------------------- /examples/Java/RepeatAString/RepeatAString.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * RepeatAString 3 | * https://rosettacode.org/wiki/Repeat_a_string#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * Task: 8 | * 9 | * Take a string and repeat it some number of times. 10 | * 11 | * Example: repeat("ha", 5) => "hahahahaha" 12 | * If there is a simpler/more efficient way to repeat a single “character” 13 | * (i.e. creating a string filled with a certain character), 14 | * you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). 15 | */ 16 | 17 | void setup() { 18 | String rep = repeat("ha", 5); 19 | println(rep); 20 | } 21 | String repeat(String str, int times) { 22 | // make an array of n chars, 23 | // replace each char with str, 24 | // and return as a new String 25 | return new String(new char[times]).replace("\0", str); 26 | } 27 | -------------------------------------------------------------------------------- /examples/Java/SieveOfEratosthenes/SieveOfEratosthenes.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * SieveOfEratosthenes 3 | * https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Processing 4 | * Processing 3.4 5 | * 2019-08 Jeremy Douglass 6 | * 7 | * The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers 8 | * up to a given integer. 9 | * 10 | * Task: 11 | * 12 | * Implement the Sieve of Eratosthenes algorithm, with the only allowed 13 | * optimization that the outer loop can stop at the square root of the limit, 14 | * and the inner loop may start at the square of the prime just found. 15 | * 16 | * That means especially that you shouldn't optimize by using pre-computed 17 | * wheels, i.e. don't assume you need only to cross out odd numbers (wheel 18 | * based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or 19 | * similar wheels based on low primes. 20 | * 21 | * If there's an easy way to add such a wheel based optimization, implement it 22 | * as an alternative version. 23 | * 24 | * Note: 25 | * It is important that the sieve algorithm be the actual algorithm used to 26 | * find prime numbers for the task. 27 | * 28 | * Translation of Java:infinite iterator with a very fast page segmentation 29 | * algorithm (sieves odds-only) 30 | */ 31 | 32 | import java.util.Iterator; 33 | 34 | void setup() { 35 | long n = 1000000000; 36 | int strt = millis(); 37 | Iterator gen = new SoEPagedOdds(); 38 | int count = 0; 39 | while (gen.next() <= n) count++; 40 | int elpsd = millis() - strt; 41 | println("Found " + count + " primes up to " + n + " in " + elpsd + " milliseconds."); 42 | } 43 | 44 | class SoEPagedOdds implements Iterator { 45 | int BFSZ = 1 << 16; 46 | int BFBTS = BFSZ * 32; 47 | int BFRNG = BFBTS * 2; 48 | long bi = -1; 49 | long lowi = 0; 50 | IntList bpa = new IntList(); 51 | Iterator bps; 52 | int[] buf = new int[BFSZ]; 53 | 54 | @Override boolean hasNext() { 55 | return true; 56 | } 57 | @Override Long next() { 58 | if (this.bi < 1) { 59 | if (this.bi < 0) { 60 | this.bi = 0; 61 | return 2L; 62 | } 63 | //this.bi muxt be 0 64 | long nxt = 3 + (this.lowi << 1) + BFRNG; 65 | if (this.lowi <= 0) { // special culling for first page as no base primes yet: 66 | for (int i = 0, p = 3, sqr = 9; sqr < nxt; i++, p += 2, sqr = p * p) 67 | if ((this.buf[i >>> 5] & (1 << (i & 31))) == 0) 68 | for (int j = (sqr - 3) >> 1; j < BFBTS; j += p) 69 | this.buf[j >>> 5] |= 1 << (j & 31); 70 | } else { // after the first page: 71 | for (int i = 0; i < this.buf.length; i++) 72 | this.buf[i] = 0; // clear the sieve buffer 73 | if (this.bpa.size()==0) { // if this is the first page after the zero one: 74 | this.bps = new SoEPagedOdds(); // initialize separate base primes stream: 75 | this.bps.next(); // advance past the only even prime of two 76 | this.bpa.append(this.bps.next().intValue()); // get the next prime (3 in this case) 77 | } 78 | // get enough base primes for the page range... 79 | for (long p = this.bpa.get(this.bpa.size() - 1), sqr = p * p; sqr < nxt; 80 | p = this.bps.next(), this.bpa.append((int)p), sqr = p * p) ; 81 | for (int i = 0; i < this.bpa.size() - 1; i++) { 82 | long p = this.bpa.get(i); 83 | long s = (p * p - 3) >>> 1; 84 | if (s >= this.lowi) // adjust start index based on page lower limit... 85 | s -= this.lowi; 86 | else { 87 | long r = (this.lowi - s) % p; 88 | s = (r != 0) ? p - r : 0; 89 | } 90 | for (int j = (int)s; j < BFBTS; j += p) 91 | this.buf[j >>> 5] |= 1 << (j & 31); 92 | } 93 | } 94 | } 95 | while ((this.bi < BFBTS) && 96 | ((this.buf[(int)this.bi >>> 5] & (1 << ((int)this.bi & 31))) != 0)) 97 | this.bi++; // find next marker still with prime status 98 | if (this.bi < BFBTS) // within buffer: output computed prime 99 | return 3 + ((this.lowi + this.bi++) << 1); 100 | else { // beyond buffer range: advance buffer 101 | this.bi = 0; 102 | this.lowi += BFBTS; 103 | return this.next(); // and recursively loop 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /examples/Java/SieveOfEratosthenes_Viz/SieveOfEratosthenes_Viz.pde: -------------------------------------------------------------------------------- 1 | /** 2 | * SieveOfEratosthenes_Viz 3 | * https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Processing 4 | * Processing 3.4 5 | * 2011-10-29‎ AlexLehm 6 | * 2020-03-03 Jeremy Douglass 7 | * 8 | * The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers 9 | * up to a given integer. 10 | * 11 | * Task: 12 | * 13 | * Implement the Sieve of Eratosthenes algorithm, with the only allowed 14 | * optimization that the outer loop can stop at the square root of the limit, 15 | * and the inner loop may start at the square of the prime just found. 16 | * 17 | * That means especially that you shouldn't optimize by using pre-computed 18 | * wheels, i.e. don't assume you need only to cross out odd numbers (wheel 19 | * based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or 20 | * similar wheels based on low primes. 21 | * 22 | * If there's an easy way to add such a wheel based optimization, implement it 23 | * as an alternative version. 24 | * 25 | * Note: 26 | * It is important that the sieve algorithm be the actual algorithm used to 27 | * find prime numbers for the task. 28 | */ 29 | 30 | // Calculate the primes up to 1000000 with Processing, 31 | // including a visualisation of the process. 32 | 33 | int i=2; 34 | int maxx; 35 | int maxy; 36 | int max; 37 | boolean[] sieve; 38 | 39 | void setup() { 40 | size(1000, 1000); 41 | // frameRate(2); 42 | maxx=width; 43 | maxy=height; 44 | max=width*height; 45 | sieve=new boolean[max+1]; 46 | 47 | sieve[1]=false; 48 | plot(0, false); 49 | plot(1, false); 50 | for (int i=2; i<=max; i++) { 51 | sieve[i]=true; 52 | plot(i, true); 53 | } 54 | } 55 | 56 | void draw() { 57 | if (!sieve[i]) { 58 | while (i*i 0 and n = 0 15 | ( A(m-1, A(m, n-1)) if m > 0 and n > 0 16 | Its arguments are never negative and it always terminates. 17 | 18 | Task: 19 | 20 | Write a function which returns the value of A(m,n). 21 | Arbitrary precision is preferred (since the function grows so quickly), 22 | but not required. 23 | """ 24 | 25 | # Python is not very adequate for deep recursion, so 26 | # even setting sys.setrecursionlimit(1000000000) if 27 | # m = 5 it throws 'maximum recursion depth exceeded' 28 | 29 | from __future__ import print_function 30 | 31 | def setup(): 32 | for m in range(4): 33 | for n in range(7): 34 | print("{} ".format(ackermann(m, n)), end="") 35 | print() 36 | # print('finished') 37 | 38 | def ackermann(m, n): 39 | if m == 0: 40 | return n + 1 41 | elif m > 0 and n == 0: 42 | return ackermann(m - 1, 1) 43 | else: 44 | return ackermann(m - 1, ackermann(m, n - 1)) 45 | 46 | """ 47 | Output is the first 4x7 Ackermann's numbers. 48 | 1 2 3 4 5 6 7 49 | 2 3 4 5 6 7 8 50 | 3 5 7 9 11 13 15 51 | 5 13 29 61 125 253 509 52 | """ 53 | -------------------------------------------------------------------------------- /examples/Python/Animation/Animation.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Animation 3 | https://rosettacode.org/wiki/Animation#Processing 4 | Processing 3.4 5 | 2020-03 Alexandre Villares 6 | 7 | Task: 8 | 9 | Create a window containing the string "Hello World! " 10 | (the trailing space is significant). Make the text appear to be rotating 11 | right by periodically removing one letter from the end of the string and 12 | attaching it to the front. 13 | """ 14 | 15 | # When the user clicks on the (windowed) text, it should reverse its direction. 16 | 17 | txt = "Hello, world! " 18 | dir = True 19 | 20 | def draw(): 21 | global txt 22 | background(128) 23 | text(txt, 10, height / 2) 24 | if frameCount % 10 == 0: 25 | if (dir): 26 | txt = rotate(txt, 1) 27 | else: 28 | txt = rotate(txt, -1) 29 | println(txt) 30 | 31 | def mouseReleased(): 32 | global dir 33 | dir = not dir 34 | 35 | def rotate(text, startIdx): 36 | rotated = text[startIdx:] + text[:startIdx] 37 | return rotated 38 | -------------------------------------------------------------------------------- /examples/Python/ArchimedeanSpiral_Points/ArchimedeanSpiral_Points.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Archimedean Spiral -- Points 3 | https:#rosettacode.org/wiki/Archimedean_spiral#Processing 4 | Processing 3.4 5 | 2020-03-14 Alexandre Villares 6 | 7 | The Archimedean spiral is a spiral named after the Greek mathematician 8 | Archimedes. An Archimedean spiral can be described by the equation: 9 | 10 | r = a + bθ 11 | 12 | with real numbers a and b. 13 | 14 | Task: 15 | 16 | Draw an Archimedean spiral. 17 | """ 18 | 19 | # When drawn with points the rotation must be very small, and initially the 20 | # animation is very slow. This is because the points will move further and 21 | # further apart as the radius increases. 22 | 23 | theta = 0 24 | rotation = 0.1 25 | 26 | def setup(): 27 | size(300, 300) 28 | background(255) 29 | 30 | def draw(): 31 | global theta 32 | translate(width / 2.0, height / 2.0) 33 | x = theta * cos(theta / PI) 34 | y = theta * sin(theta / PI) 35 | point(x, y) 36 | theta = theta + rotation 37 | # check restart 38 | if x > width / 2.0: 39 | background(255) 40 | theta = 0 41 | 42 | -------------------------------------------------------------------------------- /examples/Python/BarnsleyFern/BarnsleyFern.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Barnsley Fern 3 | https://rosettacode.org/wiki/Barnsley_fern#Processing 4 | Processing 3.4 5 | 2016-04 Alexandre Villares 6 | 7 | A Barnsley fern is a fractal named after British mathematician Michael 8 | Barnsley and can be created using an iterated function system (IFS). 9 | 10 | Task: 11 | 12 | Create this fractal fern, using the following transformations: 13 | 14 | ƒ1 (chosen 1% of the time) 15 | xn + 1 = 0 16 | yn + 1 = 0.16 yn 17 | ƒ2 (chosen 85% of the time) 18 | xn + 1 = 0.85 xn + 0.04 yn 19 | yn + 1 = −0.04 xn + 0.85 yn + 1.6 20 | ƒ3 (chosen 7% of the time) 21 | xn + 1 = 0.2 xn − 0.26 yn 22 | yn + 1 = 0.23 xn + 0.22 yn + 1.6 23 | ƒ4 (chosen 7% of the time) 24 | xn + 1 = −0.15 xn + 0.28 yn 25 | yn + 1 = 0.26 xn + 0.24 yn + 0.44. 26 | 27 | Starting position: x = 0, y = 0 28 | """ 29 | 30 | size(640, 640) 31 | background(0) 32 | 33 | x = 0 34 | y = 0 35 | 36 | for _ in range(100000): 37 | xt = 0 38 | yt = 0 39 | r = random(100) 40 | 41 | if r <= 1: 42 | xt = 0 43 | yt = 0.16 * y 44 | elif r <= 8: 45 | xt = 0.20 * x - 0.26 * y 46 | yt = 0.23 * x + 0.22 * y + 1.60 47 | elif r <= 15: 48 | xt = -0.15 * x + 0.28 * y 49 | yt = 0.26 * x + 0.24 * y + 0.44 50 | else: 51 | xt = 0.85 * x + 0.04 * y 52 | yt = -0.04 * x + 0.85 * y + 1.60 53 | 54 | x = xt 55 | y = yt 56 | 57 | m = round(width / 2 + 60 * x) 58 | n = height - round(60 * y) 59 | 60 | set(m, n, "#00ff00") 61 | x = xt 62 | y = yt 63 | 64 | m = round(width / 2 + 60 * x) 65 | n = height - round(60 * y) 66 | 67 | set(m, n, "#00ff00") 68 | -------------------------------------------------------------------------------- /examples/Python/BezierCurvesCubicInteractive/BezierCurvesCubicInteractive.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Bézier Curves Cubic (Interactive) 3 | https://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Using the data storage type for raster images and a draw_line function, 10 | draw a cubic bezier curve. 11 | """ 12 | 13 | # A working sketch with movable anchor and control points. 14 | # It can be run online : 15 | # https://www.openprocessing.org/sketch/846556/ 16 | 17 | x = [0] * 4 18 | y = [0] * 4 19 | permitDrag = [False] * 4 20 | 21 | def setup() : 22 | size(300, 300) 23 | smooth() 24 | # startpoint coordinates 25 | x[0] = x[1] = 50 26 | y[0] = 50 27 | y[1] = y[2] = 150 28 | x[2] = x[3] = 250 29 | y[3] = 250 30 | 31 | def draw() : 32 | background(255) 33 | noFill() 34 | stroke(0, 0, 255) 35 | bezier(x[1], y[1], x[0], y[0], x[3], y[3], x[2], y[2]) 36 | # the bezier handles 37 | strokeWeight(1) 38 | stroke(100) 39 | line(x[0], y[0], x[1], y[1]) 40 | line(x[2], y[2], x[3], y[3]) 41 | # the anchor and control points 42 | stroke(0) 43 | fill(0) 44 | for i in range(4): 45 | if i == 0 or i == 3: 46 | fill(255, 100, 10) 47 | rectMode(CENTER) 48 | rect(x[i], y[i], 5, 5) 49 | else: 50 | fill(0) 51 | ellipse(x[i], y[i], 5, 5) 52 | # permit dragging 53 | for i in range(4): 54 | if permitDrag[i]: 55 | x[i] = mouseX 56 | y[i] = mouseY 57 | 58 | def mouseReleased () : 59 | for i in range(4): 60 | permitDrag[i] = False 61 | 62 | def mousePressed () : 63 | for i in range(4): 64 | if (x[i]-5 <= mouseX <= x[i]+10 and 65 | y[i]-5 <= mouseY <= y[i]+10): 66 | permitDrag[i] = True 67 | 68 | # hand cursor when over dragging over points 69 | def mouseMoved () : 70 | cursor(ARROW) 71 | for i in range(4): 72 | if (x[i]-5 <= mouseX <= x[i]+10 and 73 | y[i]-5 <= mouseY <= y[i]+10): 74 | cursor(HAND) 75 | -------------------------------------------------------------------------------- /examples/Python/BinaryDigits/BinaryDigits.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | BinaryDigits 3 | https://rosettacode.org/wiki/Binary_digits#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Create and display the sequence of binary digits for a given non-negative 10 | integer. 11 | 12 | The decimal value 5 should produce an output of 101 13 | The decimal value 50 should produce an output of 110010 14 | The decimal value 9000 should produce an output of 10001100101000 15 | 16 | The results can be achieved using built-in radix functions within the 17 | language (if these are available), or alternatively a user defined function 18 | can be used. The output produced should consist just of the binary digits of 19 | each number followed by a newline. There should be no other whitespace, 20 | radix or sign markers in the produced output, and leading zeros should not 21 | appear in the results. 22 | """ 23 | 24 | println(format(5, 'b')) # 101 25 | println(format(50, 'b')) # 110010 26 | println(format(9000, 'b')) # 10001100101000 27 | 28 | #Processing also has a binary() function, but this returns zero-padded results 29 | println(binary(5)) # 00000000000101 30 | println(binary(50)) # 00000000110010 31 | println(binary(9000)) # 10001100101000 32 | 33 | #Python also has a bin() function, but it returns a representation marked with the 0b prefix 34 | println(bin(5)) # 0b101 35 | println(bin(50)) # 0b110010 36 | println(bin(9000)) # 0b1100101000 37 | -------------------------------------------------------------------------------- /examples/Python/Bitmap/Bitmap.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Bitmap 3 | https://rosettacode.org/wiki/Bitmap#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Show a basic storage type to handle a simple RGB raster graphics image, 10 | and some primitive associated functions. If possible provide a function to 11 | allocate an uninitialised image, given its width and height, and provide 3 12 | additional functions: 13 | - one to fill an image with a plain RGB color, 14 | - one to set a given pixel with a color, 15 | -- one to get the color of a pixel. 16 | (If there are specificities about the storage or the allocation, 17 | explain those.) 18 | """ 19 | 20 | bitmap = createGraphics(100, 100) # Create the bitmap 21 | bitmap.beginDraw() 22 | bitmap.background(255, 0, 0) # Fill bitmap with red rgb color 23 | bitmap.endDraw() 24 | image(bitmap, 0, 0) # Place bitmap on screen. 25 | b = color(0, 0, 255) # Define a blue rgb color 26 | set(50, 50, b) # Set blue colored pixel in the middle of the screen 27 | c = get(50, 50) # Get the color of same pixel 28 | if b == c: 29 | print("Color changed correctly") # Verify 30 | -------------------------------------------------------------------------------- /examples/Python/BrownianTree/BrownianTree.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Brownian Tree 3 | https://rosettacode.org/wiki/Brownian_tree#Processing 4 | Processing 3.4 5 | 2020-03 Alexandre Villares 6 | 7 | Task: 8 | 9 | Generate and draw a Brownian Tree. 10 | 11 | A Brownian Tree is generated as a result of an initial seed, 12 | followed by the interaction of two processes. 13 | 14 | The initial "seed" is placed somewhere within the field. 15 | Where is not particularly important it could be randomized, 16 | or it could be a fixed point. Particles are injected into the 17 | field, and are individually given a (typically random) motion 18 | pattern. When a particle collides with the seed or tree, its 19 | position is fixed, and it's considered to be part of the tree. 20 | 21 | Because of the lax rules governing the random nature of the 22 | particle's placement and motion, no two resulting trees are 23 | really expected to be the same, or even necessarily have the 24 | same general shape. 25 | """ 26 | 27 | SIDESTICK = False 28 | 29 | def setup() : 30 | global is_taken 31 | size(512, 512) 32 | background(0) 33 | is_taken = [[False] * height for _ in range(width)] 34 | is_taken[width/2][height/2] = True 35 | 36 | 37 | def draw() : 38 | x = floor(random(width)) 39 | y = floor(random(height)) 40 | if is_taken[x][y]: 41 | return 42 | while True: 43 | xp = x + floor(random(-1, 2)) 44 | yp = y + floor(random(-1, 2)) 45 | is_contained = 0 <= xp < width and 0 <= yp < height 46 | if is_contained and not is_taken[xp][yp]: 47 | x = xp 48 | y = yp 49 | continue 50 | else: 51 | if SIDESTICK or (is_contained and is_taken[xp][yp]): 52 | is_taken[x][y] = True 53 | set(x, y, color(255)) 54 | break 55 | 56 | if frameCount > width * height: 57 | noLoop() 58 | -------------------------------------------------------------------------------- /examples/Python/ColorWheel/ColorWheel.pyde: -------------------------------------------------------------------------------- 1 | ''' 2 | Color Wheel 3 | https://rosettacode.org/wiki/Color_wheel#Processing 4 | Processing 3.4 5 | 2020-03 Alexandre Villares 6 | 7 | Task: 8 | 9 | Write a function to draw a HSV color wheel completely with code. 10 | https://en.wikipedia.org/wiki/HSL_and_HSV 11 | 12 | This is strictly for learning purposes only. It's highly recommended that 13 | you use an image in an actual application to actually draw the color wheel 14 | (as procedurally drawing is super slow). This does help you understand 15 | how color wheels work and this can easily be used to determine a color 16 | value based on a position within a circle. 17 | ''' 18 | 19 | size(300, 300) 20 | background(0) 21 | radius = min(width, height) / 2.0 22 | cx, cy = width / 2, width / 2 23 | for x in range(width): 24 | for y in range(height): 25 | rx = x - cx 26 | ry = y - cy 27 | s = sqrt(rx ** 2 + ry ** 2) / radius 28 | if s <= 1.0: 29 | h = ((atan2(ry, rx) / PI) + 1.0) / 2.0 30 | colorMode(HSB) 31 | c = color(int(h * 255), int(s * 255), 255) 32 | set(x, y, c) 33 | -------------------------------------------------------------------------------- /examples/Python/Comments/Comments.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Comments 3 | https://rosettacode.org/wiki/Comments#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Show all ways to include text in a language source file that's 10 | completely ignored by the compiler or interpreter. 11 | """ 12 | 13 | # a single-line comment 14 | 15 | """ 16 | Not strictly a comment, bare 17 | multi-line strings are used 18 | in Python as multi-line comments. 19 | They are also 'doc-strings' when 20 | made the first element inside 21 | function or class definitions. 22 | """ 23 | 24 | # comment out a code line 25 | # println("foo") 26 | 27 | # comment at the end of a line 28 | println("foo bar") # "baz" 29 | 30 | # there is no way to make an inline comment 31 | -------------------------------------------------------------------------------- /examples/Python/DragonCurve/DragonCurve.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Dragon Curve 3 | https://www.rosettacode.org/wiki/Dragon_curve#Processing 4 | 2020-03 Alexandre Villares 5 | 6 | Task: 7 | 8 | Create and display a dragon curve fractal. 9 | https://en.wikipedia.org/wiki/Dragon_curve 10 | 11 | (You may either display the curve directly or write it to an image file.) 12 | For some brief notes on the algorithms used and how they might suit various 13 | languages, see the Rosetta Code task page. 14 | """ 15 | 16 | l = 3 17 | ints = 13 18 | 19 | def setup(): 20 | size(700, 600) 21 | background(0, 0, 255) 22 | translate(150, 100) 23 | stroke(255) 24 | turn_left(l, ints) 25 | turn_right(l, ints) 26 | 27 | def turn_right(l, ints): 28 | if ints == 0: 29 | line(0, 0, 0, -l) 30 | translate(0, -l) 31 | else: 32 | turn_left(l, ints - 1) 33 | rotate(radians(90)) 34 | turn_right(l, ints - 1) 35 | 36 | def turn_left(l, ints): 37 | if ints == 0: 38 | line(0, 0, 0, -l) 39 | translate(0, -l) 40 | else: 41 | turn_left(l, ints - 1) 42 | rotate(radians(-90)) 43 | turn_right(l, ints - 1) 44 | -------------------------------------------------------------------------------- /examples/Python/DrawAClock/DrawAClock.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Draw a clock 3 | https://rosettacode.org/wiki/Draw_a_clock#Processing 4 | Processing 3.4 5 | 2020-03-19 Alexandre Villares 6 | 7 | Task: 8 | 9 | Draw a clock. 10 | 11 | More specific: 12 | 13 | Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a 14 | mouth counting "one thousand and one", anything. Only showing the seconds is 15 | required, e.g.: a watch with just a second hand will suffice. However, it 16 | must clearly change every second, and the change must cycle every so often 17 | (one minute, 30 seconds, etc.) It must be drawn; printing a string of 18 | numbers to your terminal doesn't qualify. Both text-based and graphical 19 | drawing are OK. 20 | 21 | The clock is unlikely to be used to control space flights, so it needs not 22 | be hyper-accurate, but it should be usable, meaning if one can read the 23 | seconds off the clock, it must agree with the system clock. 24 | A clock is rarely (never?) a major application: don't be a CPU hog and poll 25 | the system timer every microsecond, use a proper timer/signal/event from your 26 | system or language instead. For a bad example, many OpenGL programs update 27 | the frame-buffer in a busy loop even if no redraw is needed, which is very 28 | undesirable for this task. 29 | 30 | A clock is rarely (never?) a major application: try to keep your code simple 31 | and to the point. Don't write something too elaborate or convoluted, instead 32 | do whatever is natural, concise and clear in your language. 33 | 34 | Key points 35 | - animate simple object 36 | - timed event 37 | - polling system resources 38 | - code clarity 39 | """ 40 | 41 | # This simple example of an analog wall clock uses the Processing built-in 42 | # time functions second(), minute(), and hour(). For each hand it rotates the 43 | # sketch canvas and then draws a straight line. 44 | 45 | last_sec = second() 46 | 47 | def draw(): 48 | global last_sec 49 | if last_sec != second(): 50 | draw_clock() 51 | last_sec = second() 52 | 53 | def draw_clock(): 54 | background(192) 55 | translate(width / 2, height / 2) 56 | s = second() * TWO_PI / 60.0 57 | m = minute() * TWO_PI / 60.0 58 | h = hour() * TWO_PI / 12.0 59 | rotate(s) 60 | strokeWeight(1) 61 | line(0, 0, 0, -width * 0.5) 62 | rotate(-s + m) 63 | strokeWeight(2) 64 | line(0, 0, 0, -width * 0.4) 65 | rotate(-m + h) 66 | strokeWeight(4) 67 | line(0, 0, 0, -width * 0.2) 68 | 69 | # One of the official Processing language examples is a more graphically 70 | # detailed Clock example: https://processing.org/examples/clock.html 71 | -------------------------------------------------------------------------------- /examples/Python/DrawARotatingCube/DrawARotatingCube.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Draw a rotating cube 3 | https://rosettacode.org/wiki/Draw_a_rotating_cube#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Draw a rotating cube. 10 | 11 | It should be oriented with one vertex pointing straight up, and its opposite 12 | vertex on the main diagonal (the one farthest away) straight down. It can be 13 | solid or wire-frame, and you can use ASCII art if your language doesn't have 14 | graphical capabilities. Perspective is optional. 15 | """ 16 | 17 | # Create a cube in Processing with box(), rotate the scene with rotate(), 18 | # and drive rotation with either the built-in millis() or frameCount timers. 19 | 20 | def setup(): 21 | size(500, 500, P3D) 22 | 23 | def draw(): 24 | background(0) 25 | # position 26 | translate(width / 2, height / 2, -width / 2) 27 | # optional fill and lighting colors 28 | noStroke() 29 | strokeWeight(4) 30 | fill(192, 255, 192) 31 | pointLight(255, 255, 255, 0, -500, 500) 32 | # rotation driven by built-in timer 33 | rotateY(millis() / 1000.0) 34 | # rotateY(frameCount/60.0) 35 | # draw box 36 | box(300, 300, 300) 37 | -------------------------------------------------------------------------------- /examples/Python/Factorial/Factorial.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Factorial 3 | https://rosettacode.org/wiki/Factorial#Processing 4 | Processing 3.5.4 5 | 2020-04-04 Alexandre Villares (Python port) 6 | 2020-02-26 Dawit Ghebrehiwet (iterative approach) 7 | 2018-05-29 Wester Iii (recursive approach) 8 | 9 | Definitions 10 | The factorial of 0 (zero) is defined as being 1 (unity). 11 | The Factorial Function of a positive integer, n, is defined as the product of the sequence: n, n-1, n-2, ... 1 12 | 13 | Task: 14 | 15 | Write a function to return the factorial of a number. 16 | Solutions can be iterative or recursive. 17 | Support for trapping negative n errors is optional. 18 | 19 | Note: 20 | 21 | fr implements the recursive approach 22 | fi implements the iterative approach 23 | 24 | Factorials of negative numbers return -1 as an error code. 25 | * 26 | * Examples: 27 | * 28 | Generate 10 random numbers between -5 and 20 calcualate the factorial with the recursive approach and the iterative apporach. 29 | A note on choosing between and for the calculation of factorials: as stated in https://processing.org/reference/int.html the maximum number which can be stored as an interger is 2,147,483,647. So 12! = 479,001,600 is the largest factorial wich can be stored as an integer variable. 13! = 6,227,020,800 already exceeds that boundary. In order to calculate bigger factorials the data type of the variables was set to (https://processing.org/reference/long.html) wich allows numbers up to 9,223,372,036,854,775,807. 20! = 2,432,902,008,176,640,000 is the largest factorial which can be stored as a variable. 21! = 51,090,942,171,709,440,000 exceeds the boundary again. To keep this example simple the data type of the result was left at long. 30 | * 31 | Example output: 32 | * 33 | * Factorial 34 | * fr = recursive approach 35 | * fi = iterative approach 36 | * 1. 12 fr(12) = 479001600 fi(12) = 479001600 37 | * 2. 19 fr(19) = 121645100408832000 fi(19) = 121645100408832000 38 | * 3. 1 fr(1) = 1 fi(1) = 1 39 | * 4. 4 fr(4) = 24 fi(4) = 24 40 | * 5. 16 fr(16) = 20922789888000 fi(16) = 20922789888000 41 | * 6. 16 fr(16) = 20922789888000 fi(16) = 20922789888000 42 | * 7. 0 fr(0) = 1 fi(0) = 1 43 | * 8. 10 fr(10) = 3628800 fi(10) = 3628800 44 | * 9. -3 fr(-3) is not defined fi(-3) is not defined 45 | * 10. 19 fr(19) = 121645100408832000 fi(19) = 121645100408832000 46 | * 47 | """ 48 | from __future__ import print_function 49 | 50 | def setup(): 51 | println("* Factorial") 52 | println("* fr = recursive approach") 53 | println("* fi = iterative approach") 54 | for i in range(11): 55 | n = int(random(-5, 20)) 56 | rr = fr(n) 57 | ri = fi(n) 58 | 59 | print("* {}. {}".format(i, n), end='') 60 | if rr == -1: 61 | print(" fr({}) is not defined".format(n), end='') 62 | else: 63 | print(" fr({}) = {}".format(n, rr), end='') 64 | if ri == -1: 65 | print(" fi({}) is not defined".format(n), end='') 66 | else : 67 | print(" fi({}) = {}".format(n, ri), end='') 68 | println("") 69 | 70 | 71 | def fr(n): 72 | if n < 0: 73 | return -1 74 | if n == 0: 75 | return 1 76 | else: 77 | return n * fr(n-1) 78 | 79 | def fi(n): 80 | if n < 0: 81 | return -1 82 | if n == 0: 83 | return 1 84 | else: 85 | r = 1 86 | for i in range(1, n + 1): 87 | r = r * i 88 | return r 89 | -------------------------------------------------------------------------------- /examples/Python/FractalTree_Calculation/FractalTree_Calculation.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | FractalTree -- Calculating coordinates 3 | https://rosettacode.org/wiki/Fractal_tree#Processing 4 | Processing 3.4 5 | 2020-03-18 Alexandre Villares 6 | 7 | Task: 8 | 9 | Generate and draw a fractal tree. 10 | 11 | 1. Draw the trunk 12 | 2. At the end of the trunk, split by some angle and draw two branches 13 | 3. Repeat at the end of each branch until a sufficient level of branching is reached 14 | """ 15 | # Calculating the coordinates of each branch 16 | 17 | def setup(): 18 | size(600, 600) 19 | background(0) 20 | stroke(255) 21 | drawTree(300, 550, -90, 9) 22 | 23 | def drawTree(x1, y1, angle, depth): 24 | fork_angle = 20 25 | base_len = 10.0 26 | if depth > 0: 27 | x2 = x1 + cos(radians(angle)) * depth * base_len 28 | y2 = y1 + sin(radians(angle)) * depth * base_len 29 | line(x1, y1, x2, y2) 30 | drawTree(x2, y2, angle - fork_angle, depth - 1) 31 | drawTree(x2, y2, angle + fork_angle, depth - 1) 32 | -------------------------------------------------------------------------------- /examples/Python/FractalTree_Rotation/FractalTree_Rotation.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | FractalTree -- Using rotation 3 | https://rosettacode.org/wiki/Fractal_tree#Processing 4 | Processing 3.4 5 | 2020-03-18 Alexandre Villares 6 | 7 | Task: 8 | 9 | Generate and draw a fractal tree. 10 | 11 | 1. Draw the trunk 12 | 2. At the end of the trunk, split by some angle and draw two branches 13 | 3. Repeat at the end of each branch until a sufficient level of branching is reached 14 | """ 15 | 16 | # Using Processing's pushMatrix(), popMatrix() and rotate() 17 | 18 | def setup(): 19 | size(600, 600) 20 | background(0) 21 | stroke(255) 22 | drawTree(300, 550, 9) 23 | 24 | def drawTree(x, y, depth): 25 | fork_ang = radians(20) 26 | base_len = 10 27 | if depth > 0: 28 | pushMatrix() 29 | translate(x, y - baseLen * depth) 30 | line(0, baseLen * depth, 0, 0) 31 | rotate(fork_ang) 32 | drawTree(0, 0, depth - 1) 33 | rotate(2 * -fork_ang) 34 | drawTree(0, 0, depth - 1) 35 | popMatrix() 36 | -------------------------------------------------------------------------------- /examples/Python/GameOfLife/GameOfLife.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Game of Life 3 | https://rosettacode.org/wiki/Conway%27s_Game_of_Life#Processing 4 | Processing 3.4 5 | 2020-03 Alexandre Villares 6 | 2020-03 Jeremy Douglass 7 | 8 | The Game of Life is a cellular automaton devised by the British 9 | mathematician John Horton Conway in 1970. It is the best-known example 10 | of a cellular automaton. 11 | 12 | Task: 13 | 14 | Although you should test your implementation on more complex examples 15 | such as the glider in a larger universe, show the action of the blinker 16 | (three adjoining cells in a row all alive), over three generations, 17 | in a 3 by 3 grid. 18 | """ 19 | 20 | cell_size = 10 21 | sample = 10 22 | play = False # simulation is running 23 | last_cell = 0 24 | 25 | def setup(): 26 | global grid, next_grid, rows, cols 27 | size(800, 500) 28 | noStroke() 29 | rows = height / cell_size 30 | cols = width / cell_size 31 | grid = empty_grid() 32 | next_grid = empty_grid() 33 | randomize_grid() 34 | 35 | println("Press 'space' to start/stop") 36 | println("'e' to clear all cells") 37 | println("'b' demonstrate 'blinker'") 38 | println("'g' demonstrate glider") 39 | println("'r' to randomize grid") 40 | println("'+' and '-' to change speed") 41 | 42 | def draw(): 43 | background(0) 44 | for i in range(cols): 45 | x = i * cell_size 46 | for j in range(rows): 47 | y = j * cell_size 48 | current_state = grid[i][j] 49 | fill(255) 50 | if current_state: 51 | rect(x, y, cell_size, cell_size) 52 | if play: 53 | ngbs_alive = calc_ngbs_alive(i, j) 54 | result = rule(current_state, ngbs_alive) 55 | next_grid[i][j] = result 56 | 57 | if play and frameCount % sample == 0 and not mousePressed: 58 | step() 59 | 60 | def rule(current, ngbs): 61 | """ classic Conway's Game of Life rule """ 62 | if ngbs < 2 or ngbs > 3: 63 | return 0 # dies / dead 64 | elif ngbs == 3: 65 | return 1 # born / alive 66 | else: 67 | return current # stays the same (ngbs == 2) 68 | 69 | def calc_ngbs_alive(i, j): 70 | NEIGHBOURS = ((-1, 00), (01, 00), # a tuple describing the neighbourhood of a cell 71 | (-1, -1), (00, -1), 72 | (01, -1), (-1, 01), 73 | (00, 01), (01, 01)) 74 | alive = 0 75 | for iv, jv in NEIGHBOURS: 76 | alive += grid[(i + iv) % cols][(j + jv) % rows] 77 | return alive 78 | 79 | def empty_grid(): 80 | grid = [] 81 | for _ in range(cols): 82 | grid.append([0] * rows) 83 | return grid 84 | 85 | def randomize_grid(): 86 | from random import choice 87 | for i in range(cols): 88 | for j in range(rows): 89 | grid[i][j] = choice((0, 1)) 90 | 91 | def step(): 92 | global grid, next_grid 93 | grid = next_grid 94 | next_grid = empty_grid() 95 | 96 | def keyReleased(): 97 | global grid, play, sample 98 | if key == "e": 99 | grid = empty_grid() 100 | if key == "r": 101 | randomize_grid() 102 | if key == "g": 103 | grid[10][10:13] = [0, 1, 0] 104 | grid[11][10:13] = [0, 0, 1] 105 | grid[12][10:13] = [1, 1, 1] 106 | if key == "b": 107 | grid[10][10:13] = [0, 1, 0] 108 | grid[11][10:13] = [0, 1, 0] 109 | grid[12][10:13] = [0, 1, 0] 110 | if key == " ": 111 | play = not play 112 | if str(key) in '+=': 113 | sample = max(sample - 1, 1); 114 | if key == '-': 115 | sample += 1 116 | 117 | def mousePressed(): 118 | paint() 119 | 120 | def mouseDragged(): 121 | paint() 122 | 123 | def paint(): 124 | global last_cell 125 | i, j = mouseX // cell_size, mouseY // cell_size 126 | p = j * cols + i 127 | if p != last_cell: 128 | last_cell = p 129 | grid[i][j] = (1, 0)[grid[i][j]] 130 | -------------------------------------------------------------------------------- /examples/Python/HilbertCurve/HilbertCurve.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Hilbert Curve 3 | https://www.rosettacode.org/wiki/Hilbert_curve#Processing 4 | Processing 3.4 5 | 2020-03 Alexandre Villares 6 | 7 | Task: 8 | 9 | Produce a graphical or ASCII-art representation of a 10 | Hilbert curve of at least order 3. 11 | https://en.wikipedia.org/wiki/Hilbert_curve 12 | """ 13 | 14 | # L-System based implementation of Hilbert Curve 15 | 16 | iterations = 7 17 | stroke_len = 600 18 | angle_deg = 90 19 | axiom = "L" 20 | sentence = axiom 21 | rules = { 22 | 'L': '+RF-LFL-FR+', 23 | 'R': '-LF+RFR+FL-', 24 | } 25 | 26 | def setup(): 27 | size(700, 700) 28 | global xo, yo 29 | xo, yo = 50, height - 50 30 | strokeWeight(1) 31 | noFill() 32 | generate(iterations) 33 | 34 | def draw(): 35 | background(0) 36 | translate(xo, yo) 37 | plot(radians(angle_deg)) 38 | 39 | def generate(n): 40 | global stroke_len, sentence 41 | for _ in range(n): 42 | stroke_len *= 0.5 43 | next_sentence = "" 44 | for c in sentence: 45 | next_sentence += rules.get(c, c) 46 | sentence = next_sentence 47 | 48 | def plot(angle): 49 | for c in sentence: 50 | if c == "F": 51 | stroke(255) 52 | line(0, 0, 0, -stroke_len) 53 | translate(0, -stroke_len) 54 | # ellipse(0, 0, 10, 10) 55 | elif c == "+": 56 | rotate(angle) 57 | elif c == "-": 58 | rotate(-angle) 59 | 60 | def keyPressed(): 61 | global angle_deg, xo, yo, stroke_len 62 | if key == '-': 63 | angle_deg -= 1 64 | print(angle_deg) 65 | if str(key) in "=+": 66 | angle_deg += 1 67 | print(angle_deg) 68 | if key == 'a': 69 | stroke_len *= 2 70 | if key == 'z': 71 | stroke_len /= 2 72 | if keyCode == LEFT: 73 | xo -= 25 74 | if keyCode == RIGHT: 75 | xo += 25 76 | if keyCode == UP: 77 | yo -= 25 78 | if keyCode == DOWN: 79 | yo += 25 80 | -------------------------------------------------------------------------------- /examples/Python/ImageNoise/ImageNoise.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | ImageNoise 3 | https://rosettacode.org/wiki/Image_noise#Processing 4 | Processing 3.4 5 | 2020-03-15 Alexandre Villares 6 | 7 | Task: 8 | 9 | Generate a random black and white 320x240 image continuously, showing FPS 10 | (frames per second). 11 | """ 12 | 13 | black = color(0) 14 | white = color(255) 15 | 16 | def setup(): 17 | size(320, 240) 18 | # frameRate(30) # 60 by default 19 | 20 | 21 | def draw(): 22 | loadPixels() 23 | for i in range(len(pixels)): 24 | if random(1) < 0.5: 25 | pixels[i] = black 26 | else: 27 | pixels[i] = white 28 | 29 | updatePixels() 30 | fill(0, 128) 31 | rect(0, 0, 60, 20) 32 | fill(255) 33 | text(frameRate, 5, 15) 34 | -------------------------------------------------------------------------------- /examples/Python/JosephusProblem/JosephusProblem.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | JosephusProblem 3 | https://rosettacode.org/wiki/Josephus_problem#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | [Translation of Processing Java example.] 7 | 8 | Josephus problem is a math puzzle with a grim description: 9 | n prisoners are standing on a circle, sequentially numbered from 0 to n-1. 10 | An executioner walks along the circle, starting from prisoner 0, removing 11 | every k-th prisoner and killing him. 12 | 13 | As the process goes on, the circle becomes smaller and smaller, until only 14 | one prisoner remains, who is then freed. 15 | 16 | For example, if there are 5 prisoners and k=2, the order the prisoners are 17 | killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and 18 | the survivor will be #2. 19 | 20 | Task: 21 | 22 | Given any n, k>0, find out which prisoner will be the final survivor. 23 | 24 | In one such incident, there were 41 prisoners and every 3rd prisoner was 25 | being killed (k=3). 26 | 27 | Among them was a clever chap name Josephus who worked out the problem, stood 28 | at the surviving position, and lived on to tell the tale. 29 | 30 | Which number was he? 31 | """ 32 | 33 | from __future__ import print_function 34 | 35 | def setup() : 36 | print("Survivor: " + str(execute(41, 3))) 37 | print("Survivors: " + str(executeAllButM(41, 3, 3))) 38 | 39 | 40 | def execute(n, k) : 41 | killIdx = 0 42 | prisoners = [] 43 | for i in range(n): 44 | prisoners.append(i) 45 | 46 | print("Prisoners executed in order:") 47 | while len(prisoners) > 1: 48 | killIdx = (killIdx + k - 1) % len(prisoners) 49 | print(str(prisoners[killIdx]) + " ", end='') 50 | del prisoners[killIdx] 51 | 52 | print() 53 | return prisoners[0] 54 | 55 | 56 | def executeAllButM(n, k, m) : 57 | killIdx = 0 58 | prisoners = [] 59 | for i in range(n): 60 | prisoners.append(i) 61 | 62 | print("Prisoners executed in order:") 63 | while len(prisoners) > m: 64 | killIdx = (killIdx + k - 1) % len(prisoners) 65 | print(str(prisoners[killIdx]) + " ", end='') 66 | del prisoners[killIdx] 67 | 68 | print() 69 | return prisoners 70 | 71 | """ 72 | OUTPUT 73 | 74 | Prisoners executed in order: 75 | 2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36 40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 34 15 76 | Survivor: 30 77 | Prisoners executed in order: 78 | 2 5 8 11 14 17 20 23 26 29 32 35 38 0 4 9 13 18 22 27 31 36 40 6 12 19 25 33 39 7 16 28 37 10 24 1 21 3 79 | Survivors: [ 15, 30, 34 ] 80 | """ 81 | -------------------------------------------------------------------------------- /examples/Python/JuliaSet/JuliaSet.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | JuliaSet 3 | https://rosettacode.org/wiki/Julia_set#Processing 4 | Processing 3.4 5 | 2020-03 Alexandre 6 | 7 | Task: 8 | 9 | Generate and draw a Julia set. 10 | https://en.wikipedia.org/wiki/Julia_set 11 | """ 12 | 13 | from __future__ import division 14 | 15 | cX = -0.7 16 | cY = 0.27015 17 | maxIter = 300 18 | 19 | def setup(): 20 | size(640, 480) 21 | 22 | def draw(): 23 | for x in range(width): 24 | for y in range(height): 25 | zx = 1.5 * (x - width / 2) / (0.5 * width) 26 | zy = (y - height / 2) / (0.5 * height) 27 | i = maxIter 28 | while zx * zx + zy * zy < 4 and i > 0: 29 | tmp = zx * zx - zy * zy + cX 30 | zy = 2.0 * zx * zy + cY 31 | zx = tmp 32 | i -= 1 33 | colorMode(HSB) 34 | c = color(i / maxIter * 255, 255, 255 if i > 1 else 0) 35 | set(x, y, c) 36 | noLoop() 37 | -------------------------------------------------------------------------------- /examples/Python/KochCurve/KochCurve.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Koch Curve 3 | https://www.rosettacode.org/wiki/Koch_curve#Processing 4 | Processing 3.4 5 | 2020-03-12 Alexandre Villares 6 | 7 | Task: 8 | 9 | Draw a Koch curve. See details: https://en.wikipedia.org/wiki/Koch_snowflake 10 | """ 11 | 12 | l = 300 13 | 14 | def setup(): 15 | size(400, 400) 16 | background(0, 0, 255) 17 | stroke(255) 18 | # draw from center of screen 19 | translate(width / 2.0, height / 2.0) 20 | # center curve from lower - left corner of base equilateral triangle 21 | translate(-l / 2.0, l * sqrt(3) / 6.0) 22 | for i in range(4): 23 | kcurve(0, l) 24 | rotate(radians(120)) 25 | translate(-l, 0) 26 | 27 | 28 | def kcurve(x1, x2): 29 | s = (x2 - x1) / 3.0 30 | if s < 5: 31 | pushMatrix() 32 | translate(x1, 0) 33 | line(0, 0, s, 0) 34 | line(2 * s, 0, 3 * s, 0) 35 | translate(s, 0) 36 | rotate(radians(60)) 37 | line(0, 0, s, 0) 38 | translate(s, 0) 39 | rotate(radians(-120)) 40 | line(0, 0, s, 0) 41 | popMatrix() 42 | return 43 | 44 | pushMatrix() 45 | translate(x1, 0) 46 | kcurve(0, s) 47 | kcurve(2 * s, 3 * s) 48 | translate(s, 0) 49 | rotate(radians(60)) 50 | kcurve(0, s) 51 | translate(s, 0) 52 | rotate(radians(-120)) 53 | kcurve(0, s) 54 | popMatrix() 55 | -------------------------------------------------------------------------------- /examples/Python/LevenshteinDistance/LevenshteinDistance.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | LevenshteinDistance 3 | https://rosettacode.org/wiki/Levenshtein_distance#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | In information theory and computer science, the Levenshtein distance is a 8 | metric for measuring the amount of difference between two sequences (i.e. an 9 | edit distance). The Levenshtein distance between two strings is defined as 10 | the minimum number of edits needed to transform one string into the other, 11 | with the allowable edit operations being insertion, deletion, or 12 | substitution of a single character. 13 | 14 | Example The Levenshtein distance between "kitten" and "sitting" is 3, since 15 | the following three edits change one into the other, and there isn't a way 16 | to so it with fewer than three edits: 17 | 18 | kitten sitten (substitution of 'k' with 's') sitten sittin (substitution of 19 | 'e' with 'i') sittin sitting (insert 'g' at the end). 20 | 21 | The Levenshtein distance between "rosettacode", "raisethysword" is 8. 22 | 23 | The distance between two strings is same as that when both strings are 24 | reversed. 25 | 26 | Task: 27 | 28 | Implements a Levenshtein distance function, or uses a library function, to 29 | show the Levenshtein distance between "kitten" and "sitting". 30 | """ 31 | 32 | def setup(): 33 | println(distance("kitten", "sitting")) 34 | 35 | def distance(a, b): 36 | costs = [] 37 | for j in range(len(b) + 1): 38 | costs.append(j) 39 | for i in range(1, len(a) + 1): 40 | costs[0] = i 41 | nw = i - 1 42 | for j in range(1, len(b) + 1): 43 | cj = min(1 + min(costs[j], costs[j - 1]), 44 | nw if a[i - 1] == b[j - 1] else nw + 1) 45 | nw = costs[j] 46 | costs[j] = cj 47 | 48 | return costs[len(b)] 49 | 50 | 51 | """ 52 | OUTPUT 53 | 3 54 | """ 55 | -------------------------------------------------------------------------------- /examples/Python/MandelbrotSet/MandelbrotSet.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | MandelbrotSet 3 | https://rosettacode.org/wiki/Mandelbrot_set#Processing 4 | Processing 3.4 5 | 2020-03-13 Alexandre 6 | 7 | Task: 8 | 9 | Generate and draw the Mandelbrot set. 10 | 11 | Note that there are many algorithms to draw Mandelbrot set 12 | and there are many functions which generate it . 13 | """ 14 | 15 | # Click on an area to zoom in. 16 | # Choose areas with multiple colors for interesting zooming. 17 | 18 | i = di = dj = 0 19 | fn1, fn2, fn3 = random(20), random(20), random(20) 20 | f = 10 21 | 22 | def setup(): 23 | global zmx1, zmx2, zmy1, zmy2 24 | size(500, 500) 25 | zmx1 = int(width / 4) 26 | zmx2 = 2 27 | zmy1 = int(height / 4) 28 | zmy2 = 2 29 | 30 | 31 | def draw(): 32 | global i 33 | 34 | if i <= width: 35 | i += 1 36 | x = float(i + di) / zmx1 - zmx2 37 | for j in range(height + 1): 38 | y = zmy2 - float(j + dj) / zmy1 39 | zr = zi = zr2 = zi2 = 0 40 | cr, ci = x, y 41 | n = 1 42 | while n < 200 and (zr2 + zi2) < 4: 43 | zi2 = zi * zi 44 | zr2 = zr * zr 45 | zi = 2 * zi * zr + ci 46 | zr = zr2 - zi2 + cr 47 | n += 1 48 | 49 | re = (n * fn1) % 255 50 | gr = (n * fn2) % 255 51 | bl = (n * fn3) % 255 52 | stroke(re, gr, bl) 53 | point(i, j) 54 | 55 | 56 | def mousePressed(): 57 | global zmx1, zmx2, zmy1, zmy2, di, dj 58 | global i, j 59 | background(200) 60 | xt, yt = mouseX, mouseY 61 | di = di + xt - width / 2. 62 | dj = dj + yt - height / 2. 63 | zmx1 = zmx1 * f 64 | zmx2 = zmx2 * (1. / f) 65 | zmy1 = zmy1 * f 66 | zmy2 = zmy2 * (1. / f) 67 | di, dj = di * f, dj * f 68 | i = j = 0 69 | -------------------------------------------------------------------------------- /examples/Python/MousePosition/MousePosition.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Mouse position 3 | https://rosettacode.org/wiki/Mouse_position#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Get the current location of the mouse cursor relative to the active window. 10 | """ 11 | 12 | def setup(): 13 | size(640, 480) 14 | 15 | def draw(): 16 | # mouseX and mouseY provide the current mouse position 17 | ellipse(mouseX, mouseY, 5, 5) # graphic output example 18 | println("x:{} y:{}".format(mouseX, mouseY)) 19 | -------------------------------------------------------------------------------- /examples/Python/NinetyNineBottles_Viz/NinetyNineBottles_Viz.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | NinetyNineBottles, Visual with Animation 3 | https://rosettacode.org/wiki/99_Bottles_of_Beer#Processing 4 | Processing 3.4 5 | 2019-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Display the complete lyrics for the song: 10 | 99 Bottles of Beer on the Wall. 11 | 12 | The lyrics follow this form: 13 | 14 | 99 bottles of beer on the wall 15 | 99 bottles of beer 16 | Take one down, pass it around 17 | 98 bottles of beer on the wall 18 | 19 | 98 bottles of beer on the wall 20 | 98 bottles of beer 21 | Take one down, pass it around 22 | 97 bottles of beer on the wall 23 | 24 | ... and so on, until reaching 0. 25 | 26 | Grammatical support for "1 bottle of beer" is optional. 27 | 28 | As with any puzzle, try to do it in as creative/concise/comical 29 | a way as possible (simple, obvious solutions allowed, too). 30 | """ 31 | 32 | # This approach uses Processing's draw loop to display text on the sketch 33 | # canvas, with a global counter for bottles--draw() is called at the default 34 | # 60fps, and acts as the for loop. One round of lyrics is displayed at a time, 35 | # and the counter advances by checking Processing's built-in frameCount. 36 | # Lyrics may also be advanced manually by clicking the mouse on the canvas. 37 | 38 | i = 99 39 | def setup(): 40 | size(200, 140) 41 | 42 | def draw(): 43 | background(0) 44 | text("{} bottles of beer on the wall\n".format(i) + 45 | "{} bottles of beer\n".format(i) + 46 | "Take one down, pass it around\n" + 47 | "{} bottles of beer on the wall\n\n".format(i - 1), 48 | 10, 20) 49 | if frameCount % 240 == 239: # auto-advance every 4 secs 50 | next() 51 | 52 | def mouseReleased(): 53 | next() # manual advance 54 | 55 | def next(): 56 | global i 57 | i = max(i - 1, 1) # stop decreasing at 1-0 bottles 58 | -------------------------------------------------------------------------------- /examples/Python/PalindromeDetection/PalindromeDetection.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | PalindromeDetection 3 | https://rosettacode.org/wiki/Palindrome_detection#Processing 4 | Processing 3.5.4 5 | 2020-04 Alexandre Villares 6 | 7 | A palindrome is a phrase which reads the same backward and forward. 8 | 9 | Task: 10 | 11 | Write a function or program that checks whether a given sequence of 12 | characters (or, you prefer, bytes) is a palindrome. 13 | 14 | For extra credit: 15 | 16 | Support Unicode characters. 17 | Write a second function (possibly as a wrapper to the first) which detects 18 | inexact palindromes, i.e. phrases that are palindromes if white-space and 19 | punctuation is ignored and case-insensitive comparison is used. 20 | 21 | Hints 22 | It might be useful for this task to know how to reverse a string. 23 | This task's entries might also form the subjects of the task 24 | Test a function. 25 | 26 | Related tasks 27 | Word plays 28 | Ordered words 29 | Palindrome detection 30 | Semordnilap 31 | Anagrams 32 | Anagrams/Deranged anagrams 33 | 34 | Example result on the console. 35 | 36 | PalindromeDetection 37 | 1. 'abcba' isExactPalindrome: True isInexactPalindrome: True 38 | 2. 'aa' isExactPalindrome: True isInexactPalindrome: True 39 | 3. 'a' isExactPalindrome: True isInexactPalindrome: True 40 | 4. '' isExactPalindrome: True isInexactPalindrome: True 41 | 5. ' ' isExactPalindrome: True isInexactPalindrome: True 42 | 6. 'ab' isExactPalindrome: False isInexactPalindrome: false 43 | 7. 'abcdba' isExactPalindrome: False isInexactPalindrome: false 44 | 8. 'A man, a plan, a canal: Panama!' isExactPalindrome: False isInexactPalindrome: True 45 | 9. 'Dammit, I’m Mad! ' isExactPalindrome: False isInexactPalindrome: True 46 | 10. 'Never odd or even' isExactPalindrome: False isInexactPalindrome: True 47 | 11. 'ingirumimusnocteetconsumimurigni' isExactPalindrome: True isInexactPalindrome: True 48 | 49 | """ 50 | 51 | from __future__ import unicode_literals 52 | 53 | def setup(): 54 | println("PalindromeDetection") 55 | 56 | tests = ( 57 | "abcba", 58 | "aa", 59 | "a", 60 | "", 61 | " ", 62 | "ab", 63 | "abcdba", 64 | "A man, a plan, a canal: Panama!", 65 | "Dammit, I’m Mad!", 66 | "Never odd or even", 67 | "ingirumimusnocteetconsumimurigni" 68 | ) 69 | 70 | for i, test in enumerate(tests): 71 | println(str(i + 1) + ". '" + test + "' isExactPalindrome: " + 72 | isExactPalindrome(test) + " isInexactPalindrome: " + isInexactPalindrome(test)) 73 | 74 | def isExactPalindrome(s): 75 | """ 76 | Check for exact palindrome using reversal 77 | with slice syntax [start:end:step] 78 | """ 79 | return str(s == s[::-1]) 80 | 81 | def isInexactPalindrome(s): 82 | """ 83 | Check for inexact palindrome disregarding anything but alphabet characters. 84 | Disregards case, whitespace, non-visible characters. 85 | Uses the check for exact palindrome above. 86 | """ 87 | s = ''.join(ch for ch in s if ch.isalnum()) 88 | return isExactPalindrome(s.lower()) 89 | -------------------------------------------------------------------------------- /examples/Python/PythagorasTree/PythagorasTree.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | PythagorasTree 3 | https://rosettacode.org/wiki/Pythagoras_tree#Processing 4 | Processing 3.5.4 5 | 2020-03-17 Alexandre Villares 6 | 7 | Task: 8 | 9 | Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions). 10 | 11 | Related tasks: 12 | 13 | Fractal tree (https://rosettacode.org/wiki/Fractal_tree) 14 | """ 15 | 16 | def setup(): 17 | size(800, 400) 18 | background(255) 19 | stroke(0, 255, 0) 20 | tree(width / 2.3, height, width / 1.8, height, 10) 21 | 22 | 23 | def tree(x1, y1, x2, y2, depth): 24 | if depth <= 0: return 25 | dx = (x2 - x1) 26 | dy = (y1 - y2) 27 | 28 | x3 = (x2 - dy) 29 | y3 = (y2 - dx) 30 | x4 = (x1 - dy) 31 | y4 = (y1 - dx) 32 | x5 = (x4 + 0.5 * (dx - dy)) 33 | y5 = (y4 - 0.5 * (dx + dy)) 34 | 35 | # square 36 | beginShape() 37 | fill(0.0, 255.0 / depth, 0.0) 38 | vertex(x1, y1) 39 | vertex(x2, y2) 40 | vertex(x3, y3) 41 | vertex(x4, y4) 42 | vertex(x1, y1) 43 | endShape() 44 | 45 | # triangle 46 | beginShape() 47 | fill(0.0, 255.0 / depth, 0.0) 48 | vertex(x3, y3) 49 | vertex(x4, y4) 50 | vertex(x5, y5) 51 | vertex(x3, y3) 52 | endShape() 53 | 54 | tree(x4, y4, x5, y5, depth - 1) 55 | tree(x5, y5, x3, y3, depth - 1) 56 | -------------------------------------------------------------------------------- /examples/Python/RenameAFile/RenameAFile.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | RenameAFile 3 | https://rosettacode.org/wiki/Rename_a_file#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Rename: 10 | - a file called `input.txt` into `output.txt` and 11 | - a directory called `docs` into `mydocs`. 12 | 13 | This should be done twice: once "here", i.e. in the current working directory 14 | and once in the filesystem root. 15 | 16 | It can be assumed that the user has the rights to do so. (In unix-type 17 | systems, only the user root would have sufficient permissions in the 18 | filesystem root.) 19 | 20 | Note that sketches will seldom have write permission to root files/folders 21 | these root operations should be expected to fail by default. 22 | """ 23 | 24 | from java.io import File 25 | 26 | def setup(): 27 | # rename local file 28 | sketchfile = rename(sketchPath("input.txt"), sketchPath("output.txt")) 29 | # rename local folder 30 | sketchfold = rename(sketchPath("docs"), sketchPath("mydocs")) 31 | # rename root file (if permitted) 32 | rootfile = rename("input.txt", "output.txt") 33 | # rename root folder (if permitted) 34 | rootfold = rename("docs", "mydocs") 35 | 36 | # display results of four operations: True=success, False=fail 37 | println(str(sketchfile) + ' ' + 38 | str(sketchfold) + ' ' + 39 | str(rootfile) + ' ' + 40 | str(rootfold)) 41 | # output: 42 | # True True False False 43 | 44 | 45 | def rename(oldname, newname): 46 | # File (or directory) with old name 47 | file = File(oldname) 48 | # File (or directory) with new name 49 | file2 = File(newname) 50 | # Rename file (or directory) 51 | success = file.renameTo(file2) 52 | return success 53 | -------------------------------------------------------------------------------- /examples/Python/RenameAFile/docs/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/examples/Python/RenameAFile/docs/.gitkeep -------------------------------------------------------------------------------- /examples/Python/RenameAFile/input.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum -------------------------------------------------------------------------------- /examples/Python/RepeatAString/RepeatAString.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | RepeatAString 3 | https://rosettacode.org/wiki/Repeat_a_string#Processing 4 | Processing 3.4 5 | 2020-03 Alexandre Villares 6 | 7 | Task: 8 | 9 | Take a string and repeat it some number of times. 10 | 11 | Example: repeat("ha", 5) => "hahahahaha" 12 | If there is a simpler/more efficient way to repeat a single “character” 13 | (i.e. creating a string filled with a certain character), 14 | you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). 15 | """ 16 | 17 | def setup(): 18 | rep = repeat("ha", 5) 19 | println(rep) 20 | 21 | def repeat(s, times): 22 | return s * times 23 | -------------------------------------------------------------------------------- /examples/Python/SieveOfEratosthenes_Viz/SieveOfEratosthenes_Viz.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | SieveOfEratosthenes_Viz 3 | https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers 8 | up to a given integer. 9 | 10 | Task: 11 | 12 | Implement the Sieve of Eratosthenes algorithm, with the only allowed 13 | optimization that the outer loop can stop at the square root of the limit, 14 | and the inner loop may start at the square of the prime just found. 15 | 16 | That means especially that you shouldn't optimize by using pre-computed 17 | wheels, i.e. don't assume you need only to cross out odd numbers (wheel 18 | based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or 19 | similar wheels based on low primes. 20 | 21 | If there's an easy way to add such a wheel based optimization, implement it 22 | as an alternative version. 23 | 24 | Note: 25 | It is important that the sieve algorithm be the actual algorithm used to 26 | find prime numbers for the task. 27 | """ 28 | 29 | # Calculate the primes up to 1000000 with Processing, 30 | # including a visualisation of the process. 31 | 32 | from __future__ import print_function 33 | 34 | i = 2 35 | 36 | def setup(): 37 | size(1000, 1000) 38 | # frameRate(2) 39 | global maxx, maxy, max_num, sieve 40 | maxx = width 41 | maxy = height 42 | max_num = width * height 43 | sieve = [False] * (max_num + 1) 44 | 45 | sieve[1] = False 46 | plot(0, False) 47 | plot(1, False) 48 | for i in range(2, max_num + 1): 49 | sieve[i] = True 50 | plot(i, True) 51 | 52 | 53 | def draw(): 54 | global i 55 | if not sieve[i]: 56 | while (i * i < max_num and not sieve[i]): 57 | i += 1 58 | 59 | if sieve[i]: 60 | print("{} ".format(i), end='') 61 | for j in range(i * i, max_num + 1, i): 62 | if sieve[j]: 63 | sieve[j] = False 64 | plot(j, False) 65 | 66 | if i * i < max_num: 67 | i += 1 68 | else: 69 | noLoop() 70 | println("finished") 71 | 72 | 73 | def plot(pos, active): 74 | set(pos % maxx, pos / maxx, color(0) if active else color(255)) 75 | -------------------------------------------------------------------------------- /examples/Python/Vector/Vector.pyde: -------------------------------------------------------------------------------- 1 | """ 2 | Vector 3 | https:#rosettacode.org/wiki/Vector#Processing 4 | Processing 3.4 5 | 2020-04 Alexandre Villares 6 | 7 | Task: 8 | 9 | Implement a Vector class (or a set of functions) that models a Physical 10 | Vector. The four basic operations and a pretty print function should be 11 | implemented. 12 | 13 | The Vector may be initialized in any reasonable way. 14 | 15 | - Start and end points, and direction 16 | - Angular coefficient and value (length) 17 | 18 | The four operations to be implemented are: 19 | 20 | Vector + Vector addition 21 | Vector - Vector subtraction 22 | Vectorscalar multiplication 23 | Vector / scalar division 24 | """ 25 | 26 | # A vector class, PVector, is a Processing built-in. It expresses an x,y 27 | # or x,y,z vector from the origin. A vector may return its components, 28 | # magnitude, and heading, and also includes .add(), .sub(), .mult(), and 29 | # .div() -- among other methods. Methods each have both a static form 30 | # which returns a PVector and an object method form which alters the 31 | # original. Python mode adds math operator overloading for static methods. 32 | 33 | v1 = PVector(5, 7) 34 | v2 = PVector(2, 3) 35 | 36 | println('{} {} {} {}\n'.format( v1.x, v1.y, v1.mag(), v1.heading())) 37 | 38 | # math overloaded operators (static methods in the comments) 39 | println(v1 + v2) # PVector.add(v1, v2) 40 | println(v1 - v2) # PVector.sub(v1, v2) 41 | println(v1 * 11) # PVector.mult(v1, 11) 42 | println(v1 / 2) # PVector.div(v1, 2) 43 | println('') 44 | 45 | # object methods (related augmented assigment in the comments) 46 | println(v1.sub(v1)) # v1 -= v1; println(v1) 47 | println(v1.add(v2)) # v1 += v2; println(v2) 48 | println(v1.mult(10)) # v1 *= 10; println(v1) 49 | println(v1.div(10)) # v1 /= 10; println(v1) 50 | 51 | 52 | """ 53 | Output: 54 | 55 | 5.0 7.0 8.602325 0.95054686 56 | 57 | [ 7.0, 10.0, 0.0 ] 58 | [ 3.0, 4.0, 0.0 ] 59 | [ 55.0, 77.0, 0.0 ] 60 | [ 2.5, 3.5, 0.0 ] 61 | 62 | [ 0.0, 0.0, 0.0 ] 63 | [ 2.0, 3.0, 0.0 ] 64 | [ 20.0, 30.0, 0.0 ] 65 | [ 2.0, 3.0, 0.0 ] 66 | """ 67 | -------------------------------------------------------------------------------- /examples/R/AckermannFunction/AckermannFunction.rpde: -------------------------------------------------------------------------------- 1 | # Ackermann function 2 | # https://rosettacode.org/wiki/Ackermann_function#Processing.R 3 | # Processing 3.4 4 | # 2009-06-30 ShinTakezou (R) 5 | # 2020-04-17 Jeremy Douglass 6 | # 7 | # The Ackermann function is a classic example of a recursive function, notable 8 | # especially because it is not a primitive recursive function. It grows very 9 | # quickly in value, as does the size of its call tree. 10 | # 11 | # The Ackermann function is usually defined as follows: 12 | # 13 | # ( n+1 if m = 0 14 | # A(m,n) = ( A(m-1, 1) if m > 0 and n = 0 15 | # ( A(m-1, A(m, n-1)) if m > 0 and n > 0 16 | # Its arguments are never negative and it always terminates. 17 | # 18 | # Task: 19 | # 20 | # Write a function which returns the value of A(m,n). 21 | # Arbitrary precision is preferred (since the function grows so quickly), 22 | # but not required. 23 | 24 | setup <- function() { 25 | for (m in 0:3) { 26 | for (n in 0:4) { 27 | stdout$print(paste(ackermann(m, n), " ")) 28 | } 29 | stdout$println("") 30 | } 31 | } 32 | 33 | ackermann <- function(m, n) { 34 | if ( m == 0 ) { 35 | return(n+1) 36 | } else if ( n == 0 ) { 37 | ackermann(m-1, 1) 38 | } else { 39 | ackermann(m-1, ackermann(m, n-1)) 40 | } 41 | } 42 | 43 | # Output: 44 | # 45 | # 1 2 3 4 5 46 | # 2 3 4 5 6 47 | # 3 5 7 9 11 48 | # 5 13 29 61 125 49 | 50 | # note that Processing.R exceeds its stack depth at ~ n==6 51 | # and returns null. 52 | # -- see also https://rosettacode.org/wiki/Find_limit_of_recursion#R 53 | -------------------------------------------------------------------------------- /examples/R/NinetyNineBottles/NinetyNineBottles.rpde: -------------------------------------------------------------------------------- 1 | # NinetyNineBottles 2 | # https://rosettacode.org/wiki/99_Bottles_of_Beer#Processing.R 3 | # Processing 3.4 4 | # 2020-04-17 Jeremy Douglass 5 | # 6 | # Task: 7 | # 8 | # Display the complete lyrics for the song: 9 | # 99 Bottles of Beer on the Wall. 10 | # 11 | # The lyrics follow this form: 12 | # 13 | # 99 bottles of beer on the wall 14 | # 99 bottles of beer 15 | # Take one down, pass it around 16 | # 98 bottles of beer on the wall 17 | # 18 | # 98 bottles of beer on the wall 19 | # 98 bottles of beer 20 | # Take one down, pass it around 21 | # 97 bottles of beer on the wall 22 | # 23 | # ... and so on, until reaching 0. 24 | # 25 | # Grammatical support for "1 bottle of beer" is optional. 26 | # 27 | # As with any puzzle, try to do it in as creative/concise/comical 28 | # a way as possible (simple, obvious solutions allowed, too). 29 | 30 | 31 | # immediately prints all output to the console 32 | setup <- function() { 33 | stdout$print(bottlesong(99)) 34 | } 35 | 36 | bottlesong <- function(num) { 37 | verses = "" 38 | for(i in num:1){ 39 | verses = paste0(verses, 40 | num," bottles of beer on the wall \n", 41 | num," bottles of beer \n", 42 | "Take one down, pass it around \n", 43 | num-1, " bottles of beer on the wall \n\n", sep=""); 44 | num <- num - 1 45 | } 46 | return(verses) 47 | } 48 | -------------------------------------------------------------------------------- /examples/R/OneHundredDoors/OneHundredDoors.rpde: -------------------------------------------------------------------------------- 1 | # 100 Doors 2 | # http://rosettacode.org/wiki/100_doors#Processing.R 3 | # Processing 3.4 4 | # 2008-09-16 Gregg Lind (R) 5 | # 2019-12-10 Jeremy Douglass 6 | # 7 | # There are 100 doors in a row that are all initially closed. 8 | # You make 100 passes by the doors. 9 | # 10 | # The first time through, visit every door and toggle the door 11 | # (if the door is closed, open it; if it is open, close it). 12 | # The second time, only visit every 2nd door (door #2, #4, #6, ...), 13 | # and toggle it. 14 | # The third time, visit every 3rd door (door #3, #6, #9, ...), 15 | # etc, until you only visit the 100th door. 16 | # 17 | # Task: 18 | # 19 | # Answer the question: 20 | # What state are the doors in after the last pass? 21 | # Which are open, which are closed? 22 | 23 | setup <- function() { 24 | for(door in doors(100, 100)) { 25 | stdout$print(paste(door, "")) 26 | } 27 | } 28 | 29 | doors <- function(ndoors=100,passes=100) { 30 | doors <- rep(FALSE,ndoors) 31 | for (ii in seq(1,passes)) { 32 | mask <- seq(0,ndoors,ii) 33 | doors[mask] <- !doors[mask] 34 | } 35 | return (which(doors == TRUE)) 36 | } 37 | -------------------------------------------------------------------------------- /logo/assets/processing-logo_black.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/assets/processing-logo_black.png -------------------------------------------------------------------------------- /logo/assets/rosetta-stone-detail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/assets/rosetta-stone-detail.png -------------------------------------------------------------------------------- /logo/assets/rosettacodeorg--title.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/assets/rosettacodeorg--title.png -------------------------------------------------------------------------------- /logo/rosetta_examples_p5-logo-300x300.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/rosetta_examples_p5-logo-300x300.png -------------------------------------------------------------------------------- /logo/rosetta_examples_p5-logo-600x600.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/rosetta_examples_p5-logo-600x600.png -------------------------------------------------------------------------------- /logo/rosetta_examples_p5-logo.xcf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/rosetta_examples_p5-logo.xcf -------------------------------------------------------------------------------- /logo/rosetta_examples_p5-social-media-preview-360x180.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/rosetta_examples_p5-social-media-preview-360x180.png -------------------------------------------------------------------------------- /logo/rosetta_examples_p5-social-media-preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/rosetta_examples_p5-social-media-preview.png -------------------------------------------------------------------------------- /logo/rosetta_examples_p5-social-media-preview.xcf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jeremydouglass/rosetta_examples_p5/d6db094375624780ec141de3aac8ecce77ab0249/logo/rosetta_examples_p5-social-media-preview.xcf -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | RELD=release 4 | ZIPD=rosetta_examples_p5 5 | 6 | if [ -d $RELD/$ZIPD ]; then rm -Rf $RELD/$ZIPD; fi 7 | mkdir -p $RELD/$ZIPD 8 | 9 | cp examples.properties $RELD/$ZIPD.txt 10 | 11 | cp -r examples $RELD/$ZIPD/examples 12 | cp CONTRIBUTING.md $RELD/$ZIPD/ 13 | cp examples.properties $RELD/$ZIPD/ 14 | cp LICENSE.md $RELD/$ZIPD/ 15 | cp README.md $RELD/$ZIPD/ 16 | 17 | cd $RELD 18 | if [ -f $ZIPD.zip ]; then rm $ZIPD.zip; fi 19 | zip -r $ZIPD.zip $ZIPD -x "*.DS_Store" "*.git*" 20 | rm -r $ZIPD 21 | 22 | # In order to release 23 | # 24 | # 1. check out a clean master (with no pending files) 25 | # 2. update the version number and pretty version in examples.properties 26 | # 3. commit and push that change to master e.g. "release 0.4" (pretty version) 27 | # 4. run the release script in the repo root -- this generates release files 28 | # 5. on gihub, create a new release tagged with the version, e.g. v0.4 29 | # using the "release" commit on master created in step 3. 30 | # 6. add two release/ assets as attachments to the GitHub release: 31 | # - rosetta_examples_p5.txt 32 | # - rosetta_examples_p5.zip 33 | # 34 | # Done! The "latest" path will automatically point to the newest release 35 | # and its download assets -- this will update what PDE displays and loads. 36 | --------------------------------------------------------------------------------